<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourImMemberRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourImMember()" @reset="resetFormTourImMember">
        <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.userIdFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="userIdFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in userIdFilterWidgetDropdownList"
              :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.groupRoleFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="groupRoleFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in groupRoleFilterWidgetDropdownList"
              :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.isShowFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="isShowFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in isShowFilterWidgetDropdownList"
              :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>
      </filter-box>
    </el-form>
    <table-box
      ref="formTourImMemberTable"
      class="page-table"
      :data="formTourImMemberTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formTourImMemberTableWidgetCurrentPage - 1) * formTourImMemberTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formTourImMemberTableWidget.onSortChange"
      @refresh="formTourImMemberTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onExportTourImMemberClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :on-change="onImportTourImMemberClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formTourImMemberTableWidget.getTableIndex" :width="80" />
      <vxe-column title="聊天群组" field="groupIdDictMap.name" />
      <vxe-column title="成员角色" field="groupRoleDictMap.name" />
      <vxe-column title="用户" field="userIdDictMap.name" />
      <vxe-column title="是否显示" field="isShowDictMap.name" />
      <vxe-column title="是否置顶 " field="isTopDictMap.name" />
      <vxe-column title="是免打扰 " field="isNotDisturbDictMap.name" />
      <vxe-column title="群昵称" field="groupNickname" />
      <vxe-column title="群备注" field="groupRemark" />

      <vxe-column title="聊天背景">
        <template v-slot="scope">
          <upload-file-list
              :file-list="
              parseUploadData(scope.row.groupBackImage, {
                id: scope.row.id,
                fieldName: 'groupBackImage',
                asImage: true
              })
            "
              type="card"
              direction="horizontal"
              :readonly="true"
          />
        </template>
      </vxe-column>

<!--      <vxe-column title="聊天背景">-->
<!--        <template v-slot="scope">-->
<!--          <upload-file-list-->
<!--            :file-list="-->
<!--              parseUploadData(scope.row.groupBackImage, {-->
<!--                id: scope.row.id,-->
<!--                fieldName: 'groupBackImage',-->
<!--                asImage: true-->
<!--              })-->
<!--            "-->
<!--            type="card"-->
<!--            direction="horizontal"-->
<!--            :readonly="true"-->
<!--          />-->
<!--        </template>-->
<!--      </vxe-column>-->
<!--      <vxe-column title="操作" fixed="right">-->
<!--        <template v-slot="scope">-->
<!--          <el-button-->
<!--            link-->
<!--            type="primary"-->
<!--            :size="layoutStore.defaultFormItemSize"-->
<!--            @click.stop="onEditTourImMemberClick(scope.row)"-->
<!--          >-->
<!--            编辑-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            link-->
<!--            type="primary"-->
<!--            :size="layoutStore.defaultFormItemSize"-->
<!--            @click.stop="onDeleteTourImMemberClick(scope.row)"-->
<!--          >-->
<!--            删除-->
<!--          </el-button>-->
<!--        </template>-->
<!--      </vxe-column>-->
      <vxe-column title="进群时间" field="createTime" />
      <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="formTourImMemberTableWidgetTotalCount"
            :current-page="formTourImMemberTableWidgetCurrentPage"
            :page-size="formTourImMemberTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formTourImMemberTableWidget.onCurrentPageChange"
            @size-change="formTourImMemberTableWidget.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: 'formTourImMember',
};
</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 { TourImMemberData } from '@/api/generated/tourImMemberController';
import { TourImMemberController } from '@/api/generated';
import FormEditTourImMember from '@/pages/ImGroup/formEditTourImMember.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({
  // 群名称
  groupIdFilter: undefined,
  // 成员名称
  userIdFilter: undefined,
  // 成员角色
  groupRoleFilter: undefined,
  // 会话是否显示
  isShowFilter: undefined,
  // 会话是否置顶
  isTopFilter: undefined,
});
const formFilterCopy = reactive({
  // 群名称
  groupIdFilter: undefined,
  // 成员名称
  userIdFilter: undefined,
  // 成员角色
  groupRoleFilter: undefined,
  // 会话是否显示
  isShowFilter: undefined,
  // 会话是否置顶
  isTopFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormTourImMemberTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourImMemberDtoFilter: {
      groupId: props.groupId,
      groupRole: formFilter.groupRoleFilter,
      userId: formFilter.userIdFilter,
      isShow: formFilter.isShowFilter,
      isTop: formFilter.isTopFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourImMemberController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormTourImMemberTableVerify = () => {
  formFilterCopy.groupIdFilter = formFilter.groupIdFilter;
  formFilterCopy.userIdFilter = formFilter.userIdFilter;
  formFilterCopy.groupRoleFilter = formFilter.groupRoleFilter;
  formFilterCopy.isShowFilter = formFilter.isShowFilter;
  formFilterCopy.isTopFilter = formFilter.isTopFilter;
  return true;
};
/**
 * 编辑
 */
const onEditTourImMemberClick = (row?: TourImMemberData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

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

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

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

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    TourImMemberController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formTourImMemberTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formTourImMemberTableOptions: TableOptions<TourImMemberData> = {
  loadTableData: loadFormTourImMemberTableWidgetData,
  verifyTableParameter: loadFormTourImMemberTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formTourImMemberTable = ref();
const formTourImMemberTableWidget = useTable(formTourImMemberTableOptions);
const {
  dataList: formTourImMemberTableWidgetDataList,
  currentPage: formTourImMemberTableWidgetCurrentPage,
  pageSize: formTourImMemberTableWidgetPageSize,
  totalCount: formTourImMemberTableWidgetTotalCount,
} = formTourImMemberTableWidget;
/**
 * 群名称下拉数据获取函数
 */
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 loadUserIdFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictSysUser(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 成员名称配置参数
const userIdFilterOptions: DropdownOptions<DictData> = {
  loadData: loadUserIdFilterDropdownList,
  isTree: false,
};
// 成员名称下拉组件
const userIdFilterWidget = useDropdown(userIdFilterOptions);
const { dropdownList: userIdFilterWidgetDropdownList } = userIdFilterWidget
/**
 * 成员角色下拉数据获取函数
 */
const loadGroupRoleFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'GroupRole', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 成员角色配置参数
const groupRoleFilterOptions: DropdownOptions<DictData> = {
  loadData: loadGroupRoleFilterDropdownList,
  isTree: false,
};
// 成员角色下拉组件
const groupRoleFilterWidget = useDropdown(groupRoleFilterOptions);
const { dropdownList: groupRoleFilterWidgetDropdownList } = groupRoleFilterWidget
/**
 * 会话是否显示下拉数据获取函数
 */
const loadIsShowFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsTrue.getList(),
  });
};
// 会话是否显示配置参数
const isShowFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsShowFilterDropdownList,
  isTree: false,
};
// 会话是否显示下拉组件
const isShowFilterWidget = useDropdown(isShowFilterOptions);
const { dropdownList: isShowFilterWidgetDropdownList } = isShowFilterWidget
/**
 * 会话是否置顶 下拉数据获取函数
 */
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 refreshFormTourImMember = () => {
  // 刷新段落
  formTourImMemberTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourImMember = () => {
  formFilter.groupIdFilter = undefined;
  formFilterCopy.groupIdFilter = undefined;
  formFilter.userIdFilter = undefined;
  formFilterCopy.userIdFilter = undefined;
  formFilter.groupRoleFilter = undefined;
  formFilterCopy.groupRoleFilter = undefined;
  formFilter.isShowFilter = undefined;
  formFilterCopy.isShowFilter = undefined;
  formFilter.isTopFilter = undefined;
  formFilterCopy.isTopFilter = undefined;
  refreshFormTourImMember();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourImMember();
};
const formInit = () => {
  groupIdFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  userIdFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  groupRoleFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  isShowFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  isTopFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourImMember();
};

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

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