<template>
  <div class="card-search">
    <a-form ref="formRef" name="advanced_search"  class="ant-advanced-search-form" :model="searchParams" >
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form-item label="人员名称" :label-col="{span:8}" name="siteUserName">
            <a-input v-model:value="searchParams.siteUserName" placeholder="" :allow-clear="true"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="工号" :label-col="{span:8}" name="userNo">
            <a-input v-model:value="searchParams.userNo" placeholder="" :allow-clear="true"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="所属驿站" :label-col="{span:8}" name="siteID">
            <a-select
              ref="select"
              v-model:value="searchParams.siteID"
              :options="allSites"
              @change="loadData"
              :field-names="{ label: 'siteName', value: 'siteID' }"
              :allow-clear="true"
              style="width: 200px" >
            </a-select>
          </a-form-item>
        </a-col>
      <a-col :span="6" style="text-align: left">
          <a-button type="primary" html-type="submit" @click="onSearch">查询</a-button>
          <a-button
          style="margin: 0 8px"
          @click="
              () => {
                formRef.resetFields();
                loadData();
              }
            ">重置</a-button>
        </a-col>
      </a-row>

      <a-row class="edit-operation">
        <a-col :span="24" class="flex-space-between">
          <div>
            <!-- 表格字段筛选按钮 -->
            <ColumnsSetting :table-columns="originalColumns" :checked-table-columns="columns"
                            @on-check="columnsCheckSub"></ColumnsSetting>
          </div>
          <div>
            <a-button type="primary" html-type="submit" functioncode="T01010302" @click='onAdd'>新增</a-button>
            <BImportExcel functioncode="T01010306"
                          :options="importOptions"
                          @success="loadData"
            ></BImportExcel>
            <BExportExcel :title="'导出'" :filename="'驿站人员信息'" :url="'userInfo/export'"
                          :params="{...exportSearchParams, rows:100000,siteUserIDList:formState.selectedRowKeys.join(',')}"></BExportExcel>
          </div>
        </a-col>
      </a-row>
    </a-form>
    <div class="search-result-list">
      <a-table :columns="columns" :data-source="dataList" :scroll="{ x:'100%', y: 500 }" :pagination="pagination"
               :loading="formState.loading"
               @change="handleTableChange"
               :row-selection="{ selectedRowKeys: formState.selectedRowKeys, onChange: onSelectChange}"
               :row-key="record=>record.siteUserID"
               bordered>
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.key === 'operation'">
            <div class="table-operation">
              <a-button type="link" size="small" functioncode="T01010301" @click='onDetail(record.siteUserID)'>查看
              </a-button>
              <a-button type="link" size="small"  functioncode="T01010303"  @click='onEdit(record.siteUserID)' >编辑</a-button>
              <a-button type="link" size="small"  functioncode="T01010304"  @click="onDel(record)" >删除</a-button>
              <a-button type="link" size="small"  functioncode="T01010307"  @click="onChangeStatus(record.userID,record.recordStatus==1?0:1)" >{{ record.recordStatus==1?"禁用":"启用" }}</a-button>
            </div>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script lang="ts">
import {computed, createVNode, defineComponent, reactive, ref} from 'vue';
import {useTabsViewStore} from "@/store/modules/tabsView";
import {DownOutlined, ExclamationCircleOutlined, UpOutlined} from '@ant-design/icons-vue';
import type {FormInstance, TableProps} from 'ant-design-vue';
import {message, Modal} from "ant-design-vue";
import {delSiteUser, getSiteUserList} from '@/api/baseSettings/userInfo';
import BExportExcel from "@/components/basic/excel/exportExcel/exportExcel.vue";
import {getPaginationTotalTitle} from "@/utils/common";
import {getSiteList} from "@/api/baseSettings/siteInfo";
import BImportExcel from "@/components/basic/excel/importExcel/importExcel.vue";
import type {ImportProps} from "@/components/basic/excel/importExcel/ImportProps";
import {updateUserStatus} from "@/api/system/user";
import ColumnsSetting from "@/components/common/ColumnsSetting.vue";

export default defineComponent({
  name: 'UserInfoList',
  components: {ColumnsSetting, BImportExcel, DownOutlined, UpOutlined, BExportExcel},
  setup() {
    const formRef = ref<FormInstance>();
    const tabsViewStore = useTabsViewStore();
    const allSites = ref<any>([]);
    const searchParams = reactive({
      pageIndex: 1,
      pageSize: 20,
      siteUserName: '',
      siteID: '',
      userNo: ""
    });
    // 导出Excel查询参数
    const exportSearchParams = computed(() => {
      let data = JSON.parse(JSON.stringify(searchParams));
      data.pageSize = formState.total;
      return data;
    })
    const formState = reactive({
      total: 0,
      selectedRowKeys: [],
      loading: false
    });
    // 原始表格定义数据
    const originalColumns = [
      {
        title: '序号',
        align: "center",
        key: 'siteUserID',
        customRender: item => `${searchParams.pageSize * (searchParams.pageIndex - 1) + item.index + 1}`,
        isDisabled: true
      },
      {title: '工号', dataIndex: 'userNo', key: 'userNo', align: "center"},
      {title: '人员名称', dataIndex: 'siteUserName', key: 'siteUserName', align: "center"},
      {title: '是否驿站站长', dataIndex: 'isSiteAdmin', key: 'isSiteAdmin', align: "center"},
      {title: '性别', dataIndex: 'genderName', key: 'genderName', align: "center"},
      {title: '联系电话', dataIndex: 'mobile', key: 'mobile', align: "center"},
      {
        title: '年龄', dataIndex: 'age', key: 'age', align: "center",
        customRender: item => {
          return calculateAge(item.record.idCard);
        }
      },
      {title: '所属驿站', dataIndex: 'siteName', key: 'siteName', align: "center"},
      {title: '用户类型', dataIndex: 'roleName', key: 'roleName', width: 120, align: "center", isDefaultClose: true},
      {
        title: '状态', dataIndex: 'recordStatus', key: 'recordStatus', align: "center",
        customRender: ({record}) => record.recordStatus == 1 ? "正常" : "禁用",
        isDefaultClose: true
      },
      {title: '操作', key: 'operation', fixed: 'right', width: 200, align: "center", isDisabled: true},
    ];
    // 响应式表格定义
    const columns = ref<Array<any>>(originalColumns.filter(item => !item.isDefaultClose));
    const importOptions = ref<ImportProps>({
      title: '导入',
      url: 'userInfo/importSiteUser',
      columns: [
        {cnName: '姓名', enName: 'siteUserName', width: 100},
        {cnName: '工号', enName: 'userNo', width: 100},
        {cnName: '性别', enName: 'genderName', width: 100},
        {cnName: '联系电话', enName: 'mobile', width: 100},
        {cnName: '身份证号码', enName: 'idCard', width: 140},
        {cnName: '用户类型', enName: 'roleName', width: 100},
        {cnName: '所属驿站', enName: 'siteName', width: 100},
        {cnName: '社会保障卡号', enName: 'socialSecurityCard', width: 150},
        {cnName: '民族', enName: 'nationName', width: 100},
        {cnName: '政治面貌', enName: 'politicsStatusName', width: 100},
        {cnName: '最高学历', enName: 'cultureRankName', width: 100},
        {cnName: '毕业院校', enName: 'finishSchool', width: 100},
        {cnName: '专业', enName: 'profession', width: 100},
        {cnName: '是否全日制', enName: 'isFullTimeName', width: 130},
        {cnName: '职业资格类别', enName: 'occupationalCategoryName', width: 140},
        {cnName: '职业资格等级', enName: 'occupationalLevelName', width: 140},
        {cnName: '籍贯', enName: 'nativePlace', width: 120},
        {cnName: '电子邮箱', enName: 'email', width: 150},
        {cnName: '现住址', enName: 'address', width: 150},
      ],
      template: {
        tempFileName: '站点人员导入模板.xlsx',
        url: '',
        params: null,
      },
    });
    const pagination = computed(() => ({
      total: formState.total,
      current: searchParams.pageIndex,
      pageSize: searchParams.pageSize,
      showSizeChanger: true,
      showTotal: total => getPaginationTotalTitle(total)
    }));
    const calculateAge = (idCardNumber) => {
      if (!idCardNumber) {
        return "";
      }
      try {
        // 假设身份证号中出生日期的格式为YYYYMMDD
        const birthYear = parseInt(idCardNumber.substring(6, 10), 10);
        const birthMonth = parseInt(idCardNumber.substring(10, 12), 10);
        const birthDay = parseInt(idCardNumber.substring(12, 14), 10);
        // 获取当前日期
        const currentDate = new Date();
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth() + 1; // 月份从 0 开始
        const currentDay = currentDate.getDate();
        // 计算年龄
        let age = currentYear - birthYear;
        if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
          age--; // 生日还未过，减去一岁
        }
        if (Number.isNaN(age) || !Number.isInteger(age)) {
          return "";
        }
        return age;
      } catch (e) {
        return "";
      }
    }

    const getAllSites = () => {
      getSiteList({
        pageIndex:1,
        pageSize:9999
      }).then((result :any) => {
        allSites.value = result.list;
      })
    }
    const dataList = ref([]);

    const handleTableChange: TableProps['onChange'] = (pag: { pageSize: number; current: number },) => {
      searchParams.pageIndex = pag.current;
      searchParams.pageSize = pag.pageSize;
      loadData();
    };

    const onSelectChange = (selectedRowKeys: any) => {
      formState.selectedRowKeys = selectedRowKeys;
    };

    const onSearch = () => {
      loadData();
    }

    const onDel= (item: any) => {
      formState.selectedRowKeys = [];
      if (item) {
        formState.selectedRowKeys.push(item.siteUserID as never)
      }

      if (formState.selectedRowKeys.length <= 0) {
        message.warning('请选择需要删除的数据！');
        return false;
      }

      Modal.confirm({
        title: '确认删除选中的站点人员?',
        icon: createVNode(ExclamationCircleOutlined),
        content: '',
        okText: '确认删除',
        okType: 'danger',
        okButtonProps: {},
        cancelText: '取消',
        onOk() {
          delSiteUser(formState.selectedRowKeys).then(() => {
            loadData();
          });
        },
        onCancel() {
          formState.selectedRowKeys = [];
        },
      });
    };

    const onChangeStatus = (userID: any,statusValue:any) => {
      updateUserStatus({ userId: userID,status:statusValue });
      loadData();
    };

    const loadData = async function () {
      formState.loading = true;
      await getAllSites();
      const result: any = await getSiteUserList(searchParams);
      dataList.value = result.list;
      formState.total = result.total;
      if (result.nextPage <= 1) {
        // 设置分页最大页码
        searchParams.pageIndex = 1;
      }
      formState.loading = false;
    }

    const onAdd =()=>{
      tabsViewStore.addTabByPath('/baseSettings/user/add', {id:null,op:1});
    };

    const onEdit = (id: string) => {
      tabsViewStore.addTabByPath('/baseSettings/user/edit', {id: id, op: 1});
    };

    const onDetail = (id: string) => {
      tabsViewStore.addTabByPath('/baseSettings/user/detail', {id: id, op: 2});
    };

    // 字段展示列选择完毕
    function columnsCheckSub(columnsKeys: Array<string>) {
      // 从原始表格定义数据中过滤出已选择的字段
      columns.value = originalColumns.filter((item: any) => columnsKeys.includes(item.key));
    }

    return {
      formRef,
      allSites,
      searchParams,
      formState,
      originalColumns,
      columns,
      pagination,
      dataList,
      handleTableChange,
      onSelectChange,
      onSearch,
      onAdd,
      onEdit,
      onDel,
      onChangeStatus,
      loadData,
      onDetail,
      importOptions,
      exportSearchParams,
      columnsCheckSub
    };
  },
  created() {
    this.loadData();
  },
  activated() {
    if (history.state.params?.reload)
      this.loadData();
  }
});
</script>
