<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditTourImMessageRef"
        :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="TourImMessage.noticeType">
              <el-select
                class="input-item"
                v-model="formData.TourImMessage.noticeType"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="noticeType_copyWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in noticeType_copyWidgetDropdownList"
                  :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="TourImMessage.messageContent">
              <el-input
                class="input-item"
                v-model="formData.TourImMessage.messageContent"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消息类型" prop="TourImMessage.messageType">
              <el-select
                class="input-item"
                v-model="formData.TourImMessage.messageType"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="messageTypeWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in messageTypeWidgetDropdownList"
                  :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="TourImMessage.groupId">
              <el-select
                class="input-item"
                v-model="formData.TourImMessage.groupId"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="groupIdWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in groupIdWidgetDropdownList"
                  :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="TourImMessage.isTop">
              <el-select
                class="input-item"
                v-model="formData.TourImMessage.isTop"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="isTopWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in isTopWidgetDropdownList"
                  :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="TourImMessage.revocationTag">
              <el-select
                class="input-item"
                v-model="formData.TourImMessage.revocationTag"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="revocationTagWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in revocationTagWidgetDropdownList"
                  :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="TourImMessage.deletedByUsers">
              <el-input
                class="input-item"
                v-model="formData.TourImMessage.deletedByUsers"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已读该条消息的用户" prop="TourImMessage.readByUsers">
              <el-input
                class="input-item"
                v-model="formData.TourImMessage.readByUsers"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="删除标记" prop="TourImMessage.dataState">
              <el-input-number
                class="input-item"
                v-model="formData.TourImMessage.dataState"
                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="onSubmitTourImMessageClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditTourImMessage',
};
</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 { TourImMessageData } from '@/api/generated/tourImMessageController';
import { TourImMessageController } 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 formEditTourImMessageRef = ref();
// 表单数据定义
type FormEditTourImMessageData = {
  TourImMessage: TourImMessageData;
};
// 表单数据
const formData = reactive<FormEditTourImMessageData>({
  TourImMessage: {
    // id
    id: undefined,
    // 消息内容
    messageContent: undefined,
    // 消息类型 0文字 1文件 2系统消息
    messageType: undefined,
    // 聊天群组id
    groupId: undefined,
    // 通知消息类型 1.单聊消息 2 群聊消息 3系统消息 4关注信息 5点赞 6评论 7评论区艾特 8文章内艾特 9访问
    noticeType: undefined,
    // 消息置顶/公告 0不置顶 1置顶
    isTop: undefined,
    // 撤回标记 0不撤回 1撤回
    revocationTag: undefined,
    // 已经删除该条消息的用户
    deletedByUsers: undefined,
    // 已读该条消息的用户
    readByUsers: undefined,
    // 删除标记 1正常 -1删除
    dataState: undefined,
    // 创建人id
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新时间
    updateTime: undefined,
    // 更新人id
    updateUserId: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'TourImMessage.noticeType': [
    {required: true, message: '请输入通知消息类型 ', trigger: 'blur'}
  ],
  'TourImMessage.messageContent': [
    {required: true, message: '请输入消息内容', trigger: 'blur'}
  ],
  'TourImMessage.messageType': [
    {required: true, message: '请输入消息类型', trigger: 'blur'}
  ],
  'TourImMessage.groupId': [
    {required: true, message: '请输入聊天群组', trigger: 'blur'}
  ],
  'TourImMessage.isTop': [
    {required: true, message: '请输入消息置顶/公告', trigger: 'blur'}
  ],
  'TourImMessage.readByUsers': [
  ],
  'TourImMessage.dataState': [
    {required: true, message: '请输入删除标记', trigger: 'blur'}
  ],
  'TourImMessage.revocationTag': [
    {required: true, message: '请输入撤回标记 ', trigger: 'blur'}
  ],
  'TourImMessage.deletedByUsers': [
  ],
});

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

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

// 初始化页面数据
const loadTourImMessageData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourImMessage = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourImMessageController.view(params).then(res => {
      formData.TourImMessage = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 通知消息类型 下拉数据获取函数
 */
const loadNoticeType_copyDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'TourImNoticeType', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 通知消息类型 配置参数
const noticeType_copyOptions: DropdownOptions<DictData> = {
  loadData: loadNoticeType_copyDropdownList,
  isTree: false,
};
// 通知消息类型 下拉组件
const noticeType_copyWidget = useDropdown(noticeType_copyOptions);
const { dropdownList: noticeType_copyWidgetDropdownList } = noticeType_copyWidget
/**
 * 消息类型下拉数据获取函数
 */
const loadMessageTypeDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'MessageType', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 消息类型配置参数
const messageTypeOptions: DropdownOptions<DictData> = {
  loadData: loadMessageTypeDropdownList,
  isTree: false,
};
// 消息类型下拉组件
const messageTypeWidget = useDropdown(messageTypeOptions);
const { dropdownList: messageTypeWidgetDropdownList } = messageTypeWidget
/**
 * 聊天群组下拉数据获取函数
 */
const loadGroupIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourImGroup(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 聊天群组配置参数
const groupIdOptions: DropdownOptions<DictData> = {
  loadData: loadGroupIdDropdownList,
  isTree: false,
};
// 聊天群组下拉组件
const groupIdWidget = useDropdown(groupIdOptions);
const { dropdownList: groupIdWidgetDropdownList } = groupIdWidget
/**
 * 消息置顶/公告下拉数据获取函数
 */
const loadIsTopDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsTrue.getList(),
  });
};
// 消息置顶/公告配置参数
const isTopOptions: DropdownOptions<DictData> = {
  loadData: loadIsTopDropdownList,
  isTree: false,
};
// 消息置顶/公告下拉组件
const isTopWidget = useDropdown(isTopOptions);
const { dropdownList: isTopWidgetDropdownList } = isTopWidget
/**
 * 撤回标记 下拉数据获取函数
 */
const loadRevocationTagDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsTrue.getList(),
  });
};
// 撤回标记 配置参数
const revocationTagOptions: DropdownOptions<DictData> = {
  loadData: loadRevocationTagDropdownList,
  isTree: false,
};
// 撤回标记 下拉组件
const revocationTagWidget = useDropdown(revocationTagOptions);
const { dropdownList: revocationTagWidgetDropdownList } = revocationTagWidget
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditTourImMessage = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditTourImMessage = () => {
  refreshFormEditTourImMessage();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditTourImMessage();
};
/**
 * 保存
 */
const onSubmitTourImMessageClick = () => {
  formEditTourImMessageRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourImMessage
      };
    retFormData.noticeTypeDictMap = findItemFromList(noticeType_copyWidgetDropdownList.value, retFormData.noticeType, 'id');
    retFormData.messageTypeDictMap = findItemFromList(messageTypeWidgetDropdownList.value, retFormData.messageType, 'id');
    retFormData.groupIdDictMap = findItemFromList(groupIdWidgetDropdownList.value, retFormData.groupId, 'id');
    retFormData.isTopDictMap = findItemFromList(isTopWidgetDropdownList.value, retFormData.isTop, 'id');
    retFormData.revocationTagDictMap = findItemFromList(revocationTagWidgetDropdownList.value, retFormData.revocationTag, 'id');
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourImMessageDto: {
        id: formData.TourImMessage.id,
        messageContent: formData.TourImMessage.messageContent,
        messageType: formData.TourImMessage.messageType,
        groupId: formData.TourImMessage.groupId,
        isTop: formData.TourImMessage.isTop,
        revocationTag: formData.TourImMessage.revocationTag,
        deletedByUsers: formData.TourImMessage.deletedByUsers,
        readByUsers: formData.TourImMessage.readByUsers,
        createUserId: formData.TourImMessage.createUserId,
        createTime: formData.TourImMessage.createTime,
        updateTime: formData.TourImMessage.updateTime,
        updateUserId: formData.TourImMessage.updateUserId,
      }
    };

    let httpCall = isEdit.value ? TourImMessageController.update : TourImMessageController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadTourImMessageData().then(res => {
    noticeType_copyWidget.onVisibleChange(true).catch(e => {console.error(e)});
    messageTypeWidget.onVisibleChange(true).catch(e => {console.error(e)});
    groupIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
    isTopWidget.onVisibleChange(true).catch(e => {console.error(e)});
    revocationTagWidget.onVisibleChange(true).catch(e => {console.error(e)});
    if (isEdit.value) refreshFormEditTourImMessage();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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