<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditTourImGroupRef"
        :model="formData"
        :size="layoutStore.defaultFormItemSize"
        :rules="rules"
        label-width="120px"
        label-position="right"
        @submit.prevent
      >
        <el-row :gutter="16">
<!--          <el-col :span="12">-->
<!--            <el-form-item label="群主" prop="TourImGroup.leaderId">-->
<!--              <el-select-->
<!--                class="input-item"-->
<!--                v-model="formData.TourImGroup.leaderId"-->
<!--                placeholder=""-->
<!--                :clearable="true"-->
<!--                :filterable="true"-->
<!--                @visible-change="leaderIdWidget.onVisibleChange"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="item in leaderIdWidgetDropdownList"-->
<!--                  :key="item.id"-->
<!--                  :label="item.name"-->
<!--                  :value="item.id"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="群聊所属类型" prop="TourImGroup.belongTypeId">-->
<!--              <el-cascader-->
<!--                class="input-item"-->
<!--                v-model="belongTypeIdPath"-->
<!--                :options="belongTypeIdWidgetDropdownList"-->
<!--                placeholder=""-->
<!--                :clearable="true"-->
<!--                :filterable="true"-->
<!--                :show-all-levels="false"-->
<!--                :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"-->
<!--                @change="onBelongTypeIdValueChange"-->
<!--              />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="群聊名称" prop="TourImGroup.groupName">-->
<!--              <el-input-->
<!--                class="input-item"-->
<!--                v-model="formData.TourImGroup.groupName"-->
<!--                type="text"-->
<!--                placeholder=""-->
<!--                :clearable="true"-->
<!--                :show-word-limit="false"-->
<!--                maxlength=""-->
<!--              />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="群聊头像" prop="TourImGroup.groupAvatar">-->
<!--              <custom-upload-->
<!--                v-model="groupAvatarWidgetFileList"-->
<!--                name="uploadFile"-->
<!--                :size="layoutStore.defaultFormItemSize"-->
<!--                type="expand"-->
<!--                :headers="getUploadHeaders"-->
<!--                :action="getUploadActionUrl('/admin/app/tourImGroup/upload')"-->
<!--                :data="{fieldName: 'groupAvatar', asImage: true}"-->
<!--                :limit="groupAvatarWidgetMaxCount"-->
<!--                @change="onGroupAvatarChange"-->
<!--              />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="群聊描述" prop="TourImGroup.description">-->
<!--              <el-input-->
<!--                class="input-item"-->
<!--                v-model="formData.TourImGroup.description"-->
<!--                type="text"-->
<!--                placeholder=""-->
<!--                :clearable="true"-->
<!--                :show-word-limit="false"-->
<!--                maxlength=""-->
<!--              />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="是否公开展示" prop="TourImGroup.isPublic">-->
<!--              <el-select-->
<!--                class="input-item"-->
<!--                v-model="formData.TourImGroup.isPublic"-->
<!--                placeholder=""-->
<!--                :clearable="true"-->
<!--                :filterable="true"-->
<!--                @visible-change="isPublicWidget.onVisibleChange"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="item in isPublicWidgetDropdownList"-->
<!--                  :key="item.id"-->
<!--                  :label="item.name"-->
<!--                  :value="item.id"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="是否开启群聊邀请确认" prop="TourImGroup.isNeedConfirm">-->
<!--              <el-select-->
<!--                class="input-item"-->
<!--                v-model="formData.TourImGroup.isNeedConfirm"-->
<!--                placeholder=""-->
<!--                :clearable="true"-->
<!--                :filterable="true"-->
<!--                @visible-change="isNeedConfirmWidget.onVisibleChange"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="item in isNeedConfirmWidgetDropdownList"-->
<!--                  :key="item.id"-->
<!--                  :label="item.name"-->
<!--                  :value="item.id"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="通知分类 " prop="TourImGroup.noticeType">-->
<!--              <el-select-->
<!--                class="input-item"-->
<!--                v-model="formData.TourImGroup.noticeType"-->
<!--                placeholder=""-->
<!--                :clearable="true"-->
<!--                :filterable="true"-->
<!--                @visible-change="noticeTypeWidget.onVisibleChange"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="item in noticeTypeWidgetDropdownList"-->
<!--                  :key="item.id"-->
<!--                  :label="item.name"-->
<!--                  :value="item.id"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="是否封禁 " prop="TourImGroup.bannedStatus">
              <el-select
                class="input-item"
                v-model="formData.TourImGroup.bannedStatus"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="bannedStatusWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in bannedStatusWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="热度值" prop="TourImGroup.hotValue">
              <el-input-number
                class="input-item"
                v-model="formData.TourImGroup.hotValue"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-scrollbar>
    <el-row class="footer-box" type="flex" justify="end" align="middle">
      <el-button :size="layoutStore.defaultFormItemSize" @click="onCancel()">取消</el-button>
      <el-button :size="layoutStore.defaultFormItemSize" type="primary" @click="onSubmitTourImGroupClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditTourImGroup',
};
</script>

<script setup lang="ts">
import { DialogProp } from '@/components/Dialog/types';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { TourImMemberData } from '@/api/generated/tourImMemberController';
import { TourImGroupInvitationData } from '@/api/generated/tourImGroupInvitationController';
import { TourImMessageData } from '@/api/generated/tourImMessageController';
import { TourImGroupData } from '@/api/generated/tourImGroupController';
import { TourImMemberController, TourImGroupInvitationController, TourImMessageController, TourImGroupController } from '@/api/generated';
import TourUser from "@/types/table/tourUser";
import {TourUserController} from '@/api/generated';


const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const {
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
    id?: ANY_OBJECT;
    saveOnSubmit?: boolean;
    rowData?: ANY_OBJECT;
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    subPage: 0,
    id: undefined,
    saveOnSubmit: true,
    rowData: undefined,
    dialog: undefined,
  },
);

const formEditTourImGroupRef = ref();
// 表单数据定义
type FormEditTourImGroupData = {
  TourImGroup: TourImGroupData;
};
// 表单数据
const formData = reactive<FormEditTourImGroupData>({
  TourImGroup: {
    // id
    id: undefined,
    // 群聊所属类型id
    belongTypeId: undefined,
    // 群主id
    leaderId: undefined,
    // 群聊名称
    groupName: undefined,
    // 群聊头像
    groupAvatar: undefined,
    // 群聊描述
    description: undefined,
    // 是否公开展示 0隐藏 1公开
    isPublic: undefined,
    // 是否开启群聊邀请确认 0不开启 1开启
    isNeedConfirm: undefined,
    // 通知分类 0单聊 1群聊
    noticeType: undefined,
    // 是否封禁 0封禁 1正常
    bannedStatus: undefined,
    // 热度值
    hotValue: undefined,
    // 删除标记 1正常 -1删除
    dataState: undefined,
    // 创建人id
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新时间
    updateTime: undefined,
    // 更新人id
    updateUserId: undefined,
    // 聊天去聊邀请数据
    tourImGroupInvitationList: [],
  },
},
);
// 表单验证规则
const rules = reactive({
  'TourImGroup.groupName': [
    {required: true, message: '请输入群聊名称', trigger: 'blur'}
  ],
  'TourImGroup.groupAvatar': [
    {required: true, message: '请输入群聊头像', trigger: 'blur'}
  ],
  'TourImGroup.belongTypeId': [
    {required: true, message: '请输入群聊所属类型', trigger: 'blur'}
  ],
  'TourImGroup.leaderId': [
    {required: true, message: '请输入群主', trigger: 'blur'}
  ],
  'TourImGroup.isNeedConfirm': [
  ],
  'TourImGroup.description': [
  ],
  'TourImGroup.isPublic': [
  ],
  'TourImGroup.bannedStatus': [
    {required: true, message: '请输入是否封禁 ', trigger: 'blur'}
  ],
  'TourImGroup.noticeType': [
    {required: true, message: '请输入通知分类 ', trigger: 'blur'}
  ],
  'TourImGroup.hotValue': [
    {required: true, message: '请输入热度值', trigger: 'blur'}
  ],
});

const onCancel = () => {
  if (props.dialog) {
    props.dialog.cancel();
  }
};

const isEdit = computed(() => {
  return props.saveOnSubmit ? props.id != null : props.rowData != null;
});

// 初始化页面数据
const loadTourImGroupData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourImGroup = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourImGroupController.view(params).then(res => {
      formData.TourImGroup = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 群主下拉数据获取函数
 */
const loadLeaderIdDropdownList = (): Promise<ListData<TourUser>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    TourUserController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 群主配置参数
const leaderIdOptions: DropdownOptions<TourUser> = {
  loadData: loadLeaderIdDropdownList,
  isTree: false,
};
// 群主下拉组件
const leaderIdWidget = useDropdown(leaderIdOptions);
const { dropdownList: leaderIdWidgetDropdownList } = leaderIdWidget
/**
 * 群聊所属类型下拉数据获取函数
 */
const loadBelongTypeIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourImGroupType(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 群聊所属类型选中值改变
 */
const onBelongTypeIdValueChange = (value) => {
  formData.TourImGroup.belongTypeId = Array.isArray(value) ? value[value.length - 1] : value;
};
// 群聊所属类型配置参数
const belongTypeIdOptions: DropdownOptions<DictData> = {
  loadData: loadBelongTypeIdDropdownList,
  isTree: true,
};
// 群聊所属类型选中数据
const belongTypeIdPath = ref<Array<string | number>>([]);
// 群聊所属类型下拉组件
const belongTypeIdWidget = useDropdown(belongTypeIdOptions);
const { dropdownList: belongTypeIdWidgetDropdownList } = belongTypeIdWidget
/**
 * 群聊头像上传文件改变
 */
const onGroupAvatarChange = val => {
  formData.TourImGroup.groupAvatar = fileListToJson(val);
};
// 群聊头像上传文件组件
const groupAvatarWidget = useUploadWidget(1);
const { fileList: groupAvatarWidgetFileList, maxCount: groupAvatarWidgetMaxCount } = groupAvatarWidget;
/**
 * 是否公开展示下拉数据获取函数
 */
const loadIsPublicDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsTrue.getList(),
  });
};
// 是否公开展示配置参数
const isPublicOptions: DropdownOptions<DictData> = {
  loadData: loadIsPublicDropdownList,
  isTree: false,
};
// 是否公开展示下拉组件
const isPublicWidget = useDropdown(isPublicOptions);
const { dropdownList: isPublicWidgetDropdownList } = isPublicWidget
/**
 * 是否开启群聊邀请确认下拉数据获取函数
 */
const loadIsNeedConfirmDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsTrue.getList(),
  });
};
// 是否开启群聊邀请确认配置参数
const isNeedConfirmOptions: DropdownOptions<DictData> = {
  loadData: loadIsNeedConfirmDropdownList,
  isTree: false,
};
// 是否开启群聊邀请确认下拉组件
const isNeedConfirmWidget = useDropdown(isNeedConfirmOptions);
const { dropdownList: isNeedConfirmWidgetDropdownList } = isNeedConfirmWidget
/**
 * 通知分类 下拉数据获取函数
 */
const loadNoticeTypeDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'TourImSingleOrGroup', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 通知分类 配置参数
const noticeTypeOptions: DropdownOptions<DictData> = {
  loadData: loadNoticeTypeDropdownList,
  isTree: false,
};
// 通知分类 下拉组件
const noticeTypeWidget = useDropdown(noticeTypeOptions);
const { dropdownList: noticeTypeWidgetDropdownList } = noticeTypeWidget
/**
 * 是否封禁 下拉数据获取函数
 */
const loadBannedStatusDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsTrue.getList(),
  });
};
// 是否封禁 配置参数
const bannedStatusOptions: DropdownOptions<DictData> = {
  loadData: loadBannedStatusDropdownList,
  isTree: false,
};
// 是否封禁 下拉组件
const bannedStatusWidget = useDropdown(bannedStatusOptions);
const { dropdownList: bannedStatusWidgetDropdownList } = bannedStatusWidget
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditTourImGroup = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditTourImGroup = () => {
  refreshFormEditTourImGroup();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditTourImGroup();
};
/**
 * 保存
 */
const onSubmitTourImGroupClick = () => {
  formEditTourImGroupRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourImGroup
      };
    retFormData.leaderIdDictMap = findItemFromList(leaderIdWidgetDropdownList.value, retFormData.leaderId, 'id');
    retFormData.belongTypeIdDictMap = findTreeNode(belongTypeIdWidgetDropdownList.value, retFormData.belongTypeId, 'id');
    retFormData.isPublicDictMap = findItemFromList(isPublicWidgetDropdownList.value, retFormData.isPublic, 'id');
    retFormData.isNeedConfirmDictMap = findItemFromList(isNeedConfirmWidgetDropdownList.value, retFormData.isNeedConfirm, 'id');
    retFormData.noticeTypeDictMap = findItemFromList(noticeTypeWidgetDropdownList.value, retFormData.noticeType, 'id');
    retFormData.bannedStatusDictMap = findItemFromList(bannedStatusWidgetDropdownList.value, retFormData.bannedStatus, 'id');
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourImGroupDto: {
        id: formData.TourImGroup.id,
        noticeType: formData.TourImGroup.noticeType,
        belongTypeId: formData.TourImGroup.belongTypeId,
        leaderId: formData.TourImGroup.leaderId,
        groupName: formData.TourImGroup.groupName,
        groupAvatar: formData.TourImGroup.groupAvatar,
        description: formData.TourImGroup.description,
        isPublic: formData.TourImGroup.isPublic,
        isNeedConfirm: formData.TourImGroup.isNeedConfirm,
        bannedStatus: formData.TourImGroup.bannedStatus,
        hotValue: formData.TourImGroup.hotValue,
        createUserId: formData.TourImGroup.createUserId,
        createTime: formData.TourImGroup.createTime,
        updateTime: formData.TourImGroup.updateTime,
        updateUserId: formData.TourImGroup.updateUserId,
      }
    };

    let httpCall = isEdit.value ? TourImGroupController.update : TourImGroupController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadTourImGroupData().then(res => {
    leaderIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
    belongTypeIdWidget.onVisibleChange(true).then(res => {
      // TODO: 获取级联选中路径
      belongTypeIdPath.value = findTreeNodePath(res, formData.TourImGroup.belongTypeId);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
    let groupAvatarDownloadParams = {
      id: formData.TourImGroup.id,
      fieldName: 'groupAvatar',
      asImage: true
    };
    groupAvatarWidgetFileList.value = parseUploadData(formData.TourImGroup.groupAvatar, groupAvatarDownloadParams);
    isPublicWidget.onVisibleChange(true).catch(e => {console.error(e)});
    isNeedConfirmWidget.onVisibleChange(true).catch(e => {console.error(e)});
    noticeTypeWidget.onVisibleChange(true).catch(e => {console.error(e)});
    bannedStatusWidget.onVisibleChange(true).catch(e => {console.error(e)});
    if (isEdit.value) refreshFormEditTourImGroup();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

onMounted(() => {
  formInit();
});
</script>
