<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourImGroupInvitationRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourImGroupInvitation()" @reset="resetFormTourImGroupInvitation">
        <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.inviterFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="inviterFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in inviterFilterWidgetDropdownList"
              :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.inviteeFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="inviteeFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in inviteeFilterWidgetDropdownList"
              :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.statusFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="statusFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in statusFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formTourImGroupInvitationTable"
      class="page-table"
      :data="formTourImGroupInvitationTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formTourImGroupInvitationTableWidgetCurrentPage - 1) * formTourImGroupInvitationTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formTourImGroupInvitationTableWidget.onSortChange"
      @refresh="formTourImGroupInvitationTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onExportTourImGroupInvitationClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :on-change="onImportTourImGroupInvitationClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formTourImGroupInvitationTableWidget.getTableIndex" :width="80" />
      <vxe-column title="聊天群组" field="groupIdDictMap.name" />
      <vxe-column title="邀请人" field="inviterDictMap.name" />
      <vxe-column title="被邀请人" field="inviteeDictMap.name" />
      <vxe-column title="邀请状态" field="statusDictMap.name" />
      <vxe-column title="创建人" field="createUserId" />
      <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="onEditTourImGroupInvitationClick(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteTourImGroupInvitationClick(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="formTourImGroupInvitationTableWidgetTotalCount"
            :current-page="formTourImGroupInvitationTableWidgetCurrentPage"
            :page-size="formTourImGroupInvitationTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formTourImGroupInvitationTableWidget.onCurrentPageChange"
            @size-change="formTourImGroupInvitationTableWidget.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: 'formTourImGroupInvitation',
};
</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 { TourImGroupInvitationData } from '@/api/generated/tourImGroupInvitationController';
import { TourImGroupInvitationController } from '@/api/generated';
import FormEditTourImGroupInvitation from '@/pages/ImGroup/formEditTourImGroupInvitation.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,
  // 邀请人
  inviterFilter: undefined,
  // 被邀请人
  inviteeFilter: undefined,
  // 邀请状态 
  statusFilter: undefined,
});
const formFilterCopy = reactive({
  // 聊天群组
  groupIdFilter: undefined,
  // 邀请人
  inviterFilter: undefined,
  // 被邀请人
  inviteeFilter: undefined,
  // 邀请状态 
  statusFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormTourImGroupInvitationTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourImGroupInvitationDtoFilter: {
      groupId: props.groupId,
      inviter: formFilter.inviterFilter,
      invitee: formFilter.inviteeFilter,
      status: formFilter.statusFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourImGroupInvitationController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormTourImGroupInvitationTableVerify = () => {
  formFilterCopy.groupIdFilter = formFilter.groupIdFilter;
  formFilterCopy.inviterFilter = formFilter.inviterFilter;
  formFilterCopy.inviteeFilter = formFilter.inviteeFilter;
  formFilterCopy.statusFilter = formFilter.statusFilter;
  return true;
};
/**
 * 编辑
 */
const onEditTourImGroupInvitationClick = (row?: TourImGroupInvitationData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

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

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

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

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    TourImGroupInvitationController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formTourImGroupInvitationTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formTourImGroupInvitationTableOptions: TableOptions<TourImGroupInvitationData> = {
  loadTableData: loadFormTourImGroupInvitationTableWidgetData,
  verifyTableParameter: loadFormTourImGroupInvitationTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formTourImGroupInvitationTable = ref();
const formTourImGroupInvitationTableWidget = useTable(formTourImGroupInvitationTableOptions);
const {
  dataList: formTourImGroupInvitationTableWidgetDataList,
  currentPage: formTourImGroupInvitationTableWidgetCurrentPage,
  pageSize: formTourImGroupInvitationTableWidgetPageSize,
  totalCount: formTourImGroupInvitationTableWidgetTotalCount,
} = formTourImGroupInvitationTableWidget;
/**
 * 聊天群组下拉数据获取函数
 */
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 loadInviterFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourUser(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 邀请人配置参数
const inviterFilterOptions: DropdownOptions<DictData> = {
  loadData: loadInviterFilterDropdownList,
  isTree: false,
};
// 邀请人下拉组件
const inviterFilterWidget = useDropdown(inviterFilterOptions);
const { dropdownList: inviterFilterWidgetDropdownList } = inviterFilterWidget
/**
 * 被邀请人下拉数据获取函数
 */
const loadInviteeFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourUser(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 被邀请人配置参数
const inviteeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadInviteeFilterDropdownList,
  isTree: false,
};
// 被邀请人下拉组件
const inviteeFilterWidget = useDropdown(inviteeFilterOptions);
const { dropdownList: inviteeFilterWidgetDropdownList } = inviteeFilterWidget
/**
 * 邀请状态 下拉数据获取函数
 */
const loadStatusFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'GroupInvitationStatus', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 邀请状态 配置参数
const statusFilterOptions: DropdownOptions<DictData> = {
  loadData: loadStatusFilterDropdownList,
  isTree: false,
};
// 邀请状态 下拉组件
const statusFilterWidget = useDropdown(statusFilterOptions);
const { dropdownList: statusFilterWidgetDropdownList } = statusFilterWidget
const refreshFormTourImGroupInvitation = () => {
  // 刷新段落
  formTourImGroupInvitationTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourImGroupInvitation = () => {
  formFilter.groupIdFilter = undefined;
  formFilterCopy.groupIdFilter = undefined;
  formFilter.inviterFilter = undefined;
  formFilterCopy.inviterFilter = undefined;
  formFilter.inviteeFilter = undefined;
  formFilterCopy.inviteeFilter = undefined;
  formFilter.statusFilter = undefined;
  formFilterCopy.statusFilter = undefined;
  refreshFormTourImGroupInvitation();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourImGroupInvitation();
};
const formInit = () => {
  groupIdFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  inviterFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  inviteeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  statusFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourImGroupInvitation();
};

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

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