<template>
  <div class="card-search">
    <a-form
      ref="formRef"
      name="advanced_search"
      class="ant-advanced-search-form"
      :model="searchParamsState"
    >
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form-item label="姓名" :label-col="{ span: 8 }" name="jobUserName">
            <a-input v-model:value="searchParamsState.jobUserName" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="求职岗位" :label-col="{ span: 8 }" name="professionName">
            <a-input v-model:value="searchParamsState.professionName" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="工作年限" :label-col="{ span: 6 }" name="workYear">
            <a-input-group compact>
              <a-input-number :min="0" :controls="false" v-model:value="searchParamsState.minWorkYear"
                              style="width:110px;" placeholder=""/>
              <a-input placeholder="——" disabled style="width: 30px; border-left: 0;border-right: 0;
                       pointer-events: none;background: #fff;margin-left: 1px; "/>
              <a-input-number :min="searchParamsState.minWorkYear" :controls="false" v-model:value="searchParamsState.maxWorkYear"
                              style="width:110px;" placeholder=""/>
            </a-input-group>
          </a-form-item>
        </a-col>
        <a-col :span="4" style="text-align: left">
          <a-button type="primary" html-type="submit" @click="onSearch">查询</a-button>
          <a-button
            style="margin: 0 8px"
            @click="
              () => {
                searchParamsState.minWorkYear = null;
                searchParamsState.maxWorkYear = null;
                searchParamsState.minSalary = null;
                searchParamsState.maxSalary = null;
                formRef.resetFields();
                loadData();
              }
            ">重置
          </a-button>
          <a style="font-size: 12px" @click="expand = !expand">
            <template v-if="expand">
              <UpOutlined/>
            </template>
            <template v-else>
              <DownOutlined/>
            </template>
            {{ expand ? '收缩' : '展开' }}
          </a>
        </a-col>
      </a-row>
      <a-row :gutter="24" v-show="expand">
        <a-col :span="6">
          <a-form-item label="求职类型" :label-col="{ span: 8 }" name="jobHuntTypeID">
            <a-select ref="select"
                      v-model:value="searchParamsState.jobHuntTypeID"
                      :options="jobHuntTypeList"
                      :field-names="{ label: 'name', value: 'value' }"
                      :allow-clear="true"
                      @change="loadData"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="人才类型" :label-col="{ span: 8 }" name="jobUserTypeID">
            <a-select ref="select"
                      v-model:value="searchParamsState.jobUserTypeID"
                      :options="jobUserTypeList"
                      :field-names="{ label: 'name', value: 'value' }"
                      :allow-clear="true"
                      @change="loadData">
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="月薪要求" :label-col="{ span: 6 }" name="salary">
            <a-input-group compact>
              <a-input-number :min="0" :controls="false" v-model:value="searchParamsState.minSalary"
                              style="width:110px;" placeholder=""/>
              <a-input placeholder="——" disabled style="width: 30px; border-left: 0;border-right: 0;
                       pointer-events: none;background: #fff;margin-left: 1px; "/>
              <a-input-number :min="searchParamsState.minSalary" :controls="false" v-model:value="searchParamsState.maxSalary"
                              style="width:110px;" placeholder=""/>
            </a-input-group>
          </a-form-item>
        </a-col>
        <a-col :span="4" style="text-align: left"></a-col>
      </a-row>
      <a-row :gutter="24" v-show="expand">
        <a-col :span="6">
          <a-form-item label="是否完成求职" :label-col="{ span: 8 }" name="isAccomplish">
            <a-select ref="select"
                      v-model:value="searchParamsState.isAccomplish"
                      :options="isAccomplishList"
                      :field-names="{ label: 'name', value: 'value' }"
                      :allow-clear="true"
                      @change="loadData"
            >
            </a-select>
          </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="searchParamsState.siteID"
              :options="siteList"
              :field-names="{ label: 'siteName', value: 'siteID' }"
              :allow-clear="true"
              @change="loadData"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="所属县区" :label-col="{span:8}" name="regionCode">
            <a-select
              ref="select"
              v-model:value="searchParamsState.regionCode"
              :options="regionList"
              :field-names="{ label: 'name', value: 'code' }"
              :allow-clear="true"
              @change="loadData"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24" v-show="expand">
        <a-col :span="6">
          <a-form-item label="登记时间" :label-col="{ span: 8 }" name="isAccomplish">
            <a-range-picker v-model:value="createDate" :placeholder="['开始日期', '结束日期']" format="YYYY-MM-DD"
                            @change="onCreateTimeChange"/>
          </a-form-item>
        </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="T01030202" @click='onAdd'>新增</a-button>
            <BImportExcel functioncode="T01030205"
                          :options="importOptions"
                          @success="loadData"
            ></BImportExcel>
            <BExportExcel :title="'导出'" :filename="'求职意向信息'" :url="'jobUserService/jobHunt/export'"
                          :params="{...exportSearchParams, rows:100000,jobHuntIDList: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"
               :row-selection="{ selectedRowKeys: formState.selectedRowKeys, onChange: onSelectChange }"
               :row-key="(record) => record.jobHuntID" bordered @change="handleTableChange">
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.key === 'recommendNum'">
            <div>
              <a-button type="link" size="small" @click='onRecommendInfo(record)'>{{ record.recommendNum }}</a-button>
            </div>
          </template>
          <template v-if="column.key === 'operation'">
            <div class="table-operation">
              <a-button type="link" size="small" functioncode="T01030201" @click="onDetail(record.jobHuntID)">查看
              </a-button>
              <a-button type="link" size="small" functioncode="T01030203" @click='onEdit(record.jobHuntID)'>编辑
              </a-button>
              <a-button type="link" size="small" functioncode="T01030204" @click="onDel(record)">删除</a-button>
              <a-button type="link" size="small" functioncode="T01030207" @click="onRecommendCompanyPost(record)">推荐岗位
              </a-button>
            </div>
          </template>
        </template>
      </a-table>
    </div>
    <Recommend ref="recommendRef"></Recommend>
  </div>
</template>

<script lang="ts">
import {computed, createVNode, defineComponent, reactive, ref} from 'vue';
import type {FormInstance, SelectProps, TableProps} from 'ant-design-vue';
import {message, Modal} from "ant-design-vue";
import {delJobHunt, getJobHuntList} from '@/api/jobUserManager/jobhunt';
import {getSysDictionaryList} from '@/api/system/dictionary';
import {getPaginationTotalTitle} from '@/utils/common';
import dayjs from 'dayjs';
import BImportExcel from "@/components/basic/excel/importExcel/importExcel.vue";
import BExportExcel from "@/components/basic/excel/exportExcel/exportExcel.vue";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";
import type {ImportProps} from "@/components/basic/excel/importExcel/ImportProps";
import {useTabsViewStore} from "@/store/modules/tabsView";
import Recommend from "@/views/jobUserManager/jobhunt/recommend.vue";
import {getSiteList} from "@/api/baseSettings/siteInfo";
import {get} from "@/api/common";
import ColumnsSetting from "@/components/common/ColumnsSetting.vue";

export default defineComponent({
  name: 'JobHuntList',
  components: {ColumnsSetting, BImportExcel, BExportExcel, Recommend},
  setup() {
    const formRef = ref<FormInstance>();
    const tabsViewStore = useTabsViewStore();
    const expand = ref(false);
    const recommendRef = ref();
    const searchParamsState = reactive({
      pageIndex: 1,
      pageSize: 20,
      jobUserName: null,
      professionName: null,
      minWorkYear: null,
      maxWorkYear: null,
      jobHuntTypeID: null,
      jobUserTypeID: null,
      minSalary: null,
      maxSalary: null,
      isAccomplish: null,
      siteID: null,
      regionCode: null,
      startDate: null,
      endDate: null
    });
    // 导出Excel查询参数
    const exportSearchParams = computed(() => {
      let data = JSON.parse(JSON.stringify(searchParamsState));
      data.pageSize = formState.total;
      return data;
    })
    const formState = reactive({
      total: 0,
      selectedRowKeys: [],
      loading: false,
    });
    // 原始表格定义数据
    const originalColumns = [
      {
        title: '序号',
        align: 'center',
        width: 80,
        key: 'jobHuntID',
        customRender: (item) =>
          `${searchParamsState.pageSize * (searchParamsState.pageIndex - 1) + item.index + 1}`,
        isDisabled: true
      },
      {title: '姓名', dataIndex: 'jobUserName', key: 'jobUserName', width: 120, align: "center",},
      {title: '希望工作地区', dataIndex: 'areaWork', key: 'areaWork', width: 180, align: "center",},
      {title: '工作年限', dataIndex: 'workYear', key: 'workYear', width: 140, align: "center",},
      {title: '求职类型', dataIndex: 'jobHuntTypeStr', key: 'jobHuntTypeStr', align: "center",},
      {title: '求职岗位', dataIndex: 'professionName', key: 'professionName', align: "center",},
      {title: '推荐数量', dataIndex: 'recommendNum', key: 'recommendNum', align: "center"},
      {
        title: '可到职日期', dataIndex: 'inDate', key: 'inDate', width: 120, align: "center",
        customRender: ({record}) => record.inDate == null ? "" : dayjs(record.inDate).format('YYYY-MM-DD'),
        isDefaultClose: true
      },
      {title: '人才类型', dataIndex: 'jobUserTypeStr', key: 'jobUserTypeStr', align: "center", isDefaultClose: true},
      {
        title: '月薪要求', dataIndex: 'salary', key: 'salary', align: "center",
        customRender: (item) => {
          const salary = showSalary(item.record.minSalary, item.record.maxSalary);
          return salary;
        }, isDefaultClose: true
      },
      {title: '操作', key: 'operation', fixed: 'right', width: 220, align: "center", isDisabled: true},
    ];
    // 响应式表格定义
    const columns = ref<Array<any>>(originalColumns.filter(item => !item.isDefaultClose));
    const pagination = computed(() => ({
      total: formState.total,
      current: searchParamsState.pageIndex,
      pageSize: searchParamsState.pageSize,
      showSizeChanger: true,
      showTotal: (total) => getPaginationTotalTitle(total),
    }));
    const importOptions = ref<ImportProps>({
      title: '导入',
      url: '/jobUserService/jobHunt/importJobHunt',
      columns: [
        {cnName: '姓名', enName: 'jobUserName', width: 100},
        // {cnName: '工种名称', enName: 'workName', width: 100},
        {cnName: '求职类型', enName: 'jobHuntTypeStr', width: 100},
        {cnName: '人才类型', enName: 'jobUserTypeStr', width: 100},
        {cnName: '最低月薪(元)', enName: 'minSalary', width: 100},
        {cnName: '最高月薪(元)', enName: 'maxSalary', width: 100},
        {cnName: '求职岗位', enName: 'professionName', width: 100},
        {cnName: '希望工作地区', enName: 'areaWork', width: 100},
        {cnName: '可到职日期', enName: 'inDate', width: 100},
        {cnName: '工作年限', enName: 'workYear', width: 100},
        {cnName: '其他要求', enName: 'otherDemand', width: 100},
      ],
      template: {
        tempFileName: '求职意向导入模板.xlsx',
        url: '',
        params: null,
      },
    });
    const dataList = ref([]);
    const jobHuntTypeList = ref<SelectProps['options']>();
    const jobUserTypeList = ref<SelectProps['options']>();
    const isAccomplishList = ref<SelectProps['options']>();
    const createDate = ref([]);
    const siteList = ref<Array<any>>([]);
    const regionList = ref<SelectProps['options']>();
    const showSalary = (minSalary: any, maxSalary: any) => {
      if (minSalary != null) {
        if (maxSalary != null) {
          return minSalary.toString() + "-" + maxSalary.toString();
        } else {
          return "≥" + minSalary.toString();
        }
      } else {
        if (maxSalary != null) {
          return "≤" + maxSalary.toString();
        } else {
          return "";
        }
      }
    }
    const onSelectChange = (selectedRowKeys: any) => {
      formState.selectedRowKeys = selectedRowKeys;
    };

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

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

    const onDel = (item: any) => {
      formState.selectedRowKeys = [];
      if (item) {
        formState.selectedRowKeys.push(item.jobHuntID as never)
      }
      if (formState.selectedRowKeys.length <= 0) {
        message.warning('请选择需要删除的数据！');
        return false;
      }
      Modal.confirm({
        title: '确认删除选中的求职意向?',
        icon: createVNode(ExclamationCircleOutlined),
        content: '',
        okText: '确认删除',
        okType: 'danger',
        okButtonProps: {},
        cancelText: '取消',
        onOk() {
          delJobHunt(formState.selectedRowKeys).then(() => {
            loadData();
          });
        },
        onCancel() {
          formState.selectedRowKeys = [];
        },
      });
    };

    function getAllSites() {
      getSiteList({pageIndex: 1, pageSize: 9999}).then((result: any) => {
        siteList.value = result.list;
      })
    }

    function getAllRegion() {
      get('system/area/getCityList', {}).then(data => {
        regionList.value = data;
      });
    }

    const loadData = async function () {
      formState.loading = true;
      getJobHuntTypeList();
      getJobUserTypeList();
      getIsAccomplishList();
      const result: any = await getJobHuntList(searchParamsState);
      dataList.value = result.list;
      formState.total = result.total;
      formState.loading = false;
    };

    const onAdd = () => {
      tabsViewStore.addTabByPath('/jobusermgr/jobhunt/add', {id: null});
    };

    const onEdit = (id: string) => {
      tabsViewStore.addTabByPath('/jobusermgr/jobhunt/edit', {id: id});
    };

    const onDetail = (id: string) => {
      tabsViewStore.addTabByPath('/jobusermgr/jobhunt/detail', {id: id});
    };

    const onRecommendCompanyPost = (item) => {
      recommendRef.value.show(item.professionID, item.professionName, item.jobHuntID, item.jobUserName, 0,
        item.parentProfessionID, item.cultureRank, item.workYear, item.minSalary, item.maxSalary, "推荐企业岗位");
    }

    const onRecommendInfo = (item) => {
      if(item.recommendNum == 0){
        return;
      }
      recommendRef.value.show('', item.professionName, item.jobHuntID, item.jobUserName, 1,
       '', null, null, null, null, '已推荐企业岗位信息');
    }

    const getJobHuntTypeList = () => {
      getSysDictionaryList('JobHuntType').then((data) => {
        jobHuntTypeList.value = data;
      });
    };

    const getJobUserTypeList = () => {
      getSysDictionaryList('JobUserType').then((data) => {
        jobUserTypeList.value = data;
      });
    };

    const getIsAccomplishList = () => {
      getSysDictionaryList('ContractRecord').then((data) => {
        isAccomplishList.value = data;
      });
    };

    // 登记时间组件调整
    const onCreateTimeChange = (dateString) => {
      createDate.value = dateString;
      searchParamsState.startDate = dateString ? dateString[0].format("YYYY-MM-DD") : '';
      searchParamsState.endDate = dateString ? dateString[1].format("YYYY-MM-DD") : '';
      loadData();
    }

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

    return {
      formRef,
      expand,
      searchParamsState,
      formState,
      columns,
      originalColumns,
      columnsCheckSub,
      pagination,
      dataList,
      importOptions,
      jobHuntTypeList,
      jobUserTypeList,
      isAccomplishList,
      recommendRef,
      exportSearchParams,
      showSalary,
      loadData,
      onSearch,
      onAdd,
      onEdit,
      onDel,
      onRecommendCompanyPost,
      onRecommendInfo,
      onSelectChange,
      handleTableChange,
      getJobHuntTypeList,
      getJobUserTypeList,
      getIsAccomplishList,
      onDetail,
      getAllSites,
      getAllRegion,
      siteList,
      regionList,
      createDate,
      onCreateTimeChange
    };
  },
  created() {
    this.getAllSites();
    this.getAllRegion();
    this.loadData();
  },
  activated() {
    if (history.state.params?.reload) this.loadData();
  },
});
</script>

<style lang="less" scoped></style>
