<template>
  <div class="flex flex-col h-full">
    <div class="page-action">
      <t-space size="small">
        <t-button v-if="perm.BUTTON_Add" theme="primary" @click="handleAdd">
          <template #icon><svg-icon name="add-circle" color="#fff" /></template>
          新增
        </t-button>
        <t-popup v-if="perm.BUTTON_BatchImport" trigger="hover">
          <template #content>
            <t-button
              variant="outline"
              @click="downloadImportTemplate('TEMPLATE_USE_ARCHIVES')"
            >
              <template #icon
                ><svg-icon name="export" color="#262626" /></template
              >下载模板
            </t-button>
          </template>
          <upload-button
            upload-url="/api/admin/user/archives/import"
            :format="['xls', 'xlsx']"
          >
            <t-button variant="outline">
              <template #icon
                ><svg-icon name="import" color="#262626" /></template
              >批量导入
            </t-button>
          </upload-button>
        </t-popup>
        <t-button
          v-if="perm.BUTTON_BatchExport"
          variant="outline"
          @click="multExport"
        >
          <template #icon><svg-icon name="export" color="#262626" /></template
          >批量导出
        </t-button>
        <t-button
          v-if="perm.BUTTON_Cancel"
          variant="outline"
          :disabled="!selectedRowKeys.length"
          @click="handleDestroy"
        >
          <template #icon><svg-icon name="delete" color="#262626" /></template
          >作废
        </t-button>
      </t-space>
    </div>

    <SearchForm :fields="fields" :params="params" :search="mixinSearch">
      <template #city="{ item, params }">
        <select-area v-model="params[item.prop]" :level="2"></select-area>
      </template>
      <template #supplier="{ item, params }">
        <select-supplier
          v-model="params[item.prop]"
          type="HUMAN"
        ></select-supplier>
      </template>
    </SearchForm>
    <div class="flex-1 page-wrap">
      <p class="page-wrap-tips">
        <t-space :size="0">
          <span>
            <ErrorCircleFilledIcon /> 在册：{{ statisticsInfo.totalCount }}人
          </span>
          <span>无效：{{ statisticsInfo.invalidCount }}人</span>
          <span>有效：{{ statisticsInfo.validCount }}人</span>
          <span>
            实施工程师有效：{{ statisticsInfo.effectEngineerCount }}人
          </span>
          <span>
            区域负责人有效：{{ statisticsInfo.regionCoordinatorCount }}人
          </span>
          <span>
            助理实施工程师有效：{{ statisticsInfo.assistantEngineerCount }}人
          </span>
          <template #separator>
            <t-divider layout="vertical" />
          </template>
        </t-space>
      </p>

      <t-table
        size="small"
        row-key="userArchivesId"
        :columns="columns"
        :data="tableData"
        bordered
        :pagination="{
          defaultCurrent: 1,
          defaultPageSize: 10,
          onChange,
          showJumper: true,
          showPageSize: false,
          total: pagination.total,
          current: pagination.pageNumber,
        }"
        :selected-row-keys="selectedRowKeys"
        @select-change="selectChange"
      >
        <template #archives-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #valid-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #gender="{ col, row }">
          {{ genderTypeFilter(row[col.colKey]) }}
        </template>
        <template #education="{ col, row }">
          {{ educationTypeFilter(row[col.colKey]) }}
        </template>
        <template #status="{ col, row }">
          {{ authenticationStatusFilter(row[col.colKey]) }}
        </template>
        <template #remain-day="{ row }">
          <span v-if="row.authenticationValidTime">
            {{ dayCountFilter(row.authenticationValidTime - Date.now()) }}天
          </span>
          <span v-else>-</span>
        </template>
        <template #photo="{ col, row }">
          <!-- <t-image
            v-if="row[col.colKey]"
            :src="row[col.colKey]"
            fit="contain"
            :style="{ width: '80px', height: '80px' }"
          ></t-image> -->
          <image-view
            v-if="row[col.colKey]"
            :src="row[col.colKey]"
            :width="60"
            :height="60"
            :images="[row[col.colKey]]"
          ></image-view>
          <span v-else>-</span>
        </template>
        <template #roles="{ col, row }">
          {{ row[col.colKey].map((item) => item.roleName).join('，') }}
        </template>
        <template #operate="{ row }">
          <div class="table-operations" @click.stop>
            <t-link
              v-if="perm.LINK_Update"
              theme="primary"
              hover="color"
              @click="handleEdit(row)"
            >
              修改
            </t-link>
          </div>
        </template>
      </t-table>
    </div>

    <AddPersonFileDialog
      v-model:visible="showAddPersonFileDialog"
      :curRow="curRow"
      @success="addSuccessHandle"
    ></AddPersonFileDialog>
  </div>
</template>

<script setup name="PersonFiles">
import { ref, reactive, computed, onMounted } from 'vue';
import { omit } from 'lodash';

import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import { ErrorCircleFilledIcon } from 'tdesign-icons-vue-next';
import useFetchTable from '@/hooks/useFetchTable';
import AddPersonFileDialog from './add-person-file-dialog';
import {
  personFilesListApi,
  personFilesStatisticsApi,
  personFilesDestroyApi,
  personFilesExportApi,
} from '@/api/resource-guard';
import { downloadImportTemplate } from '@/api/common';
import { dictToOptionList } from '@/utils/tool';
import { AUTHENTICATION_ROLE, AUTHENTICATION_STATUS } from '@/config/constants';
import {
  authenticationStatusFilter,
  timestampFilter,
  dayCountFilter,
  genderTypeFilter,
  educationTypeFilter,
} from '@/utils/filter';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();

const curRow = ref(null);
const showAddPersonFileDialog = ref(false);

const fields = ref([
  {
    prop: 'city',
    label: '区域',
    labelWidth: 70,
    type: 'select',
    colSpan: 6,
    cell: 'city',
  },
  {
    prop: 'supplierId',
    label: '供应商',
    labelWidth: 80,
    type: 'select',
    colSpan: 6,
    cell: 'supplier',
  },
  {
    prop: 'archivesName',
    label: '姓名',
    labelWidth: 55,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'roleType',
    label: '认证角色',
    labelWidth: 110,
    type: 'select',
    colSpan: 6,
    options: dictToOptionList(AUTHENTICATION_ROLE),
    attrs: {
      clearable: true,
    },
  },
  {
    type: 'buttons',
    colSpan: 2,
    labelWidth: 0,
    children: [
      {
        type: 'button',
        text: '搜索',
        onClick: () => {
          search();
          getStatisticsInfo();
        },
      },
    ],
  },
  {
    prop: 'authenticationStatus',
    label: '认证状态',
    labelWidth: 70,
    type: 'select',
    colSpan: 6,
    options: dictToOptionList(AUTHENTICATION_STATUS),
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'archivesTime',
    label: '入档时间',
    labelWidth: 80,
    type: 'daterange',
    colSpan: 12,
    attrs: {
      clearable: true,
      valueType: 'time-stamp',
    },
  },
  {
    prop: 'remainValidDay',
    label: '剩余有效天数',
    labelWidth: 110,
    colSpan: 6,
    type: 'number',
    attrs: {
      theme: 'column',
      decimalPlaces: 0,
      max: 1000000,
      min: 0,
      label: '≥',
      style: 'width: 100%',
    },
  },
  {
    prop: 'unUploadPic',
    label: '是否上传图片',
    labelWidth: 110,
    colSpan: 6,
    type: 'select',
    options: [
      { label: '是', value: true },
      { label: '否', value: false },
    ],
  },
]);
const mixinSearch = () => {
  search();
  getStatisticsInfo();
};
const params = reactive({
  city: '',
  supplierId: '',
  archivesName: '',
  roleType: '',
  authenticationStatus: '',
  archivesTime: [],
  remainValidDay: null,
  unUploadPic: '',
});
const computedParams = computed(() => {
  let data = omit(params, ['archivesTime']);
  data.archivesTimeStart = params.archivesTime[0];
  data.archivesTimeEnd = params.archivesTime[1];
  return data;
});

const columns = [
  {
    colKey: 'row-select',
    type: 'multiple',
    width: 50,
    fixed: 'left',
  },
  { colKey: 'code', title: '档案流水号', width: 200 },
  { colKey: 'name', title: '姓名', width: 80 },
  { colKey: 'province', title: '省份' },
  { colKey: 'city', title: '城市' },
  { colKey: 'area', title: '区县' },
  { colKey: 'gender', title: '性别', cell: 'gender', width: 70 },
  { colKey: 'age', title: '年龄', width: 70 },
  { colKey: 'identity', title: '身份证号', width: 190 },
  { colKey: 'education', title: '学历', cell: 'education', width: 110 },
  { colKey: 'mobileNumber', title: '手机号', width: 140 },
  { colKey: 'email', title: '电子邮箱', minWidth: 200 },
  { colKey: 'basePhotoPreviewPath', title: '底照', cell: 'photo', width: 120 },
  { colKey: 'supplierName', title: '供应商' },
  {
    colKey: 'archivesTime',
    title: '入档时间',
    cell: 'archives-time',
    width: 180,
  },
  {
    colKey: 'roleInfoList',
    title: '认证项目角色',
    cell: 'roles',
    minWidth: 150,
  },
  { colKey: 'authenticationScore', title: '认证分数' },
  {
    colKey: 'authenticationValidTime',
    title: '认证有效期',
    cell: 'valid-time',
    width: 170,
  },
  {
    colKey: 'remainValidDay',
    title: '剩余有效天数',
    cell: 'remain-day',
    width: 120,
  },
  { colKey: 'authenticationStatus', title: '认证状态', cell: 'status' },
  { colKey: 'remark', title: '备注' },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 80,
  },
];
const { pagination, tableData, fetchData, search, onChange } = useFetchTable(
  personFilesListApi,
  {
    fetchDataHandle: () => {
      selectedRowKeys.value = [];
    },
    params: computedParams,
  }
);

let statisticsInfo = ref({});
const getStatisticsInfo = async () => {
  const res = await personFilesStatisticsApi(computedParams.value);
  statisticsInfo.value = res || {};
};

const selectedRowKeys = ref([]);
const selectChange = (value) => {
  selectedRowKeys.value = value;
};

const addSuccessHandle = () => {
  fetchData();
  getStatisticsInfo();
};

const handleAdd = () => {
  curRow.value = null;
  showAddPersonFileDialog.value = true;
};
const handleEdit = (row) => {
  curRow.value = row;
  showAddPersonFileDialog.value = true;
};
const handleDestroy = () => {
  if (!selectedRowKeys.value.length) {
    MessagePlugin.error('请选择要作废的记录');
    return;
  }

  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `确定要作废当前选择的所有记录吗`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await personFilesDestroyApi(selectedRowKeys.value).catch(
        () => {}
      );
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};
const multExport = () => {
  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `确定要导出所有记录吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await personFilesExportApi(computedParams.value).catch(
        () => {}
      );
      if (!res) return;
      MessagePlugin.success('导出任务提交成功，请前往任务管理中下载');
    },
  });
};

const handleDownloadTemp = () => {
  console.log('11');
};

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