<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourImMessageRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourImMessage()" @reset="resetFormTourImMessage">
        <el-form-item label="消息内容">
          <el-input
            class="filter-item"
            v-model="formFilter.messageContentFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="消息类型">
          <el-select
            class="filter-item"
            v-model="formFilter.messageTypeFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="messageTypeFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in messageTypeFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="聊天群组">
          <el-select
            class="filter-item"
            v-model="formFilter.groupIdFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="groupIdFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in groupIdFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="消息置顶/公告">
          <el-select
            class="filter-item"
            v-model="formFilter.isTopFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="isTopFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in isTopFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="撤回标记 ">
          <el-select
            class="filter-item"
            v-model="formFilter.revocationTagFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="revocationTagFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in revocationTagFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formTourImMessageTable"
      class="page-table"
      :data="formTourImMessageTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formTourImMessageTableWidgetCurrentPage - 1) * formTourImMessageTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formTourImMessageTableWidget.onSortChange"
      @refresh="formTourImMessageTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onAddTourImMessageClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onExportTourImMessageClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :on-change="onImportTourImMessageClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formTourImMessageTableWidget.getTableIndex" :width="80" />
      <vxe-column title="消息内容" field="messageContent" />
      <vxe-column title="消息类型" field="messageTypeDictMap.name" />
      <vxe-column title="聊天群组" field="groupIdDictMap.name" />
      <vxe-column title="消息置顶/公告" field="isTopDictMap.name" />
      <vxe-column title="撤回标记 " field="revocationTagDictMap.name" />
      <vxe-column title="已经删除该条消息的用户" field="deletedByUsers" />
      <vxe-column title="已读该条消息的用户" field="readByUsers" />
      <vxe-column title="删除标记" field="dataState" />
      <vxe-column title="创建人" field="createUserIdDictMap.name" />
      <vxe-column title="创建时间" field="createTime">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.createTime, 'day')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditTourImMessageClick(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteTourImMessageClick(scope.row)"
          >
            删除
          </el-button>
        </template>
      </vxe-column>
      <template slot="empty">
        <div class="table-empty unified-font">
          <img src="@/assets/img/empty.png">
          <span>暂无数据</span>
        </div>
      </template>
      <!-- 分页 -->
      <template #pagination>
        <el-row type="flex" justify="end" style="margin-top: 10px;">
          <el-pagination
            :total="formTourImMessageTableWidgetTotalCount"
            :current-page="formTourImMessageTableWidgetCurrentPage"
            :page-size="formTourImMessageTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formTourImMessageTableWidget.onCurrentPageChange"
            @size-change="formTourImMessageTableWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
    <label v-if="subPage" class="page-close-box" @click="onCancel()">
      <img src="@/assets/img/back2.png" alt="">
    </label>
  </div>
</template>

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

<script setup lang="ts">
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';
import FormEditTourImMessage from '@/pages/ImGroup/formEditTourImMessage.vue';

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;
    groupId?: ANY_OBJECT;
  }>(),
  {
    subPage: 0,
    id: undefined,
    groupId: undefined,
  },
);

const formFilter = reactive({
  // 消息内容
  messageContentFilter: undefined,
  // 消息类型
  messageTypeFilter: undefined,
  // 聊天群组
  groupIdFilter: undefined,
  // 消息置顶/公告
  isTopFilter: undefined,
  // 撤回标记 
  revocationTagFilter: undefined,
});
const formFilterCopy = reactive({
  // 消息内容
  messageContentFilter: undefined,
  // 消息类型
  messageTypeFilter: undefined,
  // 聊天群组
  groupIdFilter: undefined,
  // 消息置顶/公告
  isTopFilter: undefined,
  // 撤回标记 
  revocationTagFilter: undefined,
});

const onCancel = () => {
  router.go(-1);
  layoutStore.removeCachePage(route.fullPath as string);
  route.meta.refreshParentCachedPage = true;
};

const onResume = () => {
  refreshFormTourImMessage();
};

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormTourImMessageTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourImMessageDtoFilter: {
      messageContent: formFilter.messageContentFilter,
      messageType: formFilter.messageTypeFilter,
      groupId: props.groupId,
      noticeType: formFilter.messageTypeFilter,
      isTop: formFilter.isTopFilter,
      revocationTag: formFilter.revocationTagFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourImMessageController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormTourImMessageTableVerify = () => {
  formFilterCopy.messageContentFilter = formFilter.messageContentFilter;
  formFilterCopy.messageTypeFilter = formFilter.messageTypeFilter;
  formFilterCopy.groupIdFilter = formFilter.groupIdFilter;
  formFilterCopy.isTopFilter = formFilter.isTopFilter;
  formFilterCopy.revocationTagFilter = formFilter.revocationTagFilter;
  return true;
};
/**
 * 新建
 */
const onAddTourImMessageClick = (row?: TourImMessageData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建', FormEditTourImMessage, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formTourImMessageTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 编辑
 */
const onEditTourImMessageClick = (row?: TourImMessageData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  Dialog
    .show('编辑', FormEditTourImMessage, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formTourImMessageTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportTourImMessageClick = (row?: TourImMessageData) => {
  let params: ANY_OBJECT = {
  };

  TourImMessageController.export(params, '表格组件.xlsx').then(res => {
    ElMessage.success('导出成功');
  }).catch(e => {
    ElMessage.error(e.errorMessage);
  });
};
/**
 * 导入
 */
const onImportTourImMessageClick = (file) => {
  let params: ANY_OBJECT = {
    importFile: file.raw,
    // 是否忽略表头
    skipHeader: false
  };

  TourImMessageController.import(params).then(res => {
    ElMessage.success('导入成功');
    formTourImMessageTableWidget.refreshTable();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 删除
 */
const onDeleteTourImMessageClick = (row?: TourImMessageData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    TourImMessageController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formTourImMessageTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formTourImMessageTableOptions: TableOptions<TourImMessageData> = {
  loadTableData: loadFormTourImMessageTableWidgetData,
  verifyTableParameter: loadFormTourImMessageTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formTourImMessageTable = ref();
const formTourImMessageTableWidget = useTable(formTourImMessageTableOptions);
const {
  dataList: formTourImMessageTableWidgetDataList,
  currentPage: formTourImMessageTableWidgetCurrentPage,
  pageSize: formTourImMessageTableWidgetPageSize,
  totalCount: formTourImMessageTableWidgetTotalCount,
} = formTourImMessageTableWidget;
/**
 * 消息类型下拉数据获取函数
 */
const loadMessageTypeFilterDropdownList = (): 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 messageTypeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadMessageTypeFilterDropdownList,
  isTree: false,
};
// 消息类型下拉组件
const messageTypeFilterWidget = useDropdown(messageTypeFilterOptions);
const { dropdownList: messageTypeFilterWidgetDropdownList } = messageTypeFilterWidget
/**
 * 聊天群组下拉数据获取函数
 */
const loadGroupIdFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourImGroup(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 聊天群组配置参数
const groupIdFilterOptions: DropdownOptions<DictData> = {
  loadData: loadGroupIdFilterDropdownList,
  isTree: false,
};
// 聊天群组下拉组件
const groupIdFilterWidget = useDropdown(groupIdFilterOptions);
const { dropdownList: groupIdFilterWidgetDropdownList } = groupIdFilterWidget
/**
 * 消息置顶/公告下拉数据获取函数
 */
const loadIsTopFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsTrue.getList(),
  });
};
// 消息置顶/公告配置参数
const isTopFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsTopFilterDropdownList,
  isTree: false,
};
// 消息置顶/公告下拉组件
const isTopFilterWidget = useDropdown(isTopFilterOptions);
const { dropdownList: isTopFilterWidgetDropdownList } = isTopFilterWidget
/**
 * 撤回标记 下拉数据获取函数
 */
const loadRevocationTagFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsTrue.getList(),
  });
};
// 撤回标记 配置参数
const revocationTagFilterOptions: DropdownOptions<DictData> = {
  loadData: loadRevocationTagFilterDropdownList,
  isTree: false,
};
// 撤回标记 下拉组件
const revocationTagFilterWidget = useDropdown(revocationTagFilterOptions);
const { dropdownList: revocationTagFilterWidgetDropdownList } = revocationTagFilterWidget
const refreshFormTourImMessage = () => {
  // 刷新段落
  formTourImMessageTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourImMessage = () => {
  formFilter.messageContentFilter = undefined;
  formFilterCopy.messageContentFilter = undefined;
  formFilter.messageTypeFilter = undefined;
  formFilterCopy.messageTypeFilter = undefined;
  formFilter.groupIdFilter = undefined;
  formFilterCopy.groupIdFilter = undefined;
  formFilter.isTopFilter = undefined;
  formFilterCopy.isTopFilter = undefined;
  formFilter.revocationTagFilter = undefined;
  formFilterCopy.revocationTagFilter = undefined;
  refreshFormTourImMessage();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourImMessage();
};
const formInit = () => {
  messageTypeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  groupIdFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  isTopFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  revocationTagFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourImMessage();
};

onMounted(() => {
  formInit();
});

onActivated(() => {
  onResume();
});
</script>