<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:6}" name="professionName">
            <a-input v-model:value="searchParams.professionName" placeholder="" :allow-clear="true"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
        <a-form-item label="招聘企业" :label-col="{span:6}" name="companyName">
          <a-select ref="select" @change="loadData"
                    show-search optionFilterProp="label"
                    v-model:value="searchParams.companyName"
                    :allow-clear="true">
            <a-select-option v-for="item in companyList" :label="item.companyName" :value="item.companyName"
                             :key="item.companyID">
              <span>{{ item.companyName }}</span>
            </a-select-option>
          </a-select>
        </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="招聘人数" :label-col="{span:6}" name="recruitCount">
            <a-input type="number" v-model:value="searchParams.minCount" style="width:110px;" placeholder="" />
            <label style="margin:10px;">-</label>
            <a-input type="number" v-model:value="searchParams.maxCount" style="width:110px;" placeholder="" />
          </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="
              () => {
                searchParams.minCount = null;
                searchParams.maxCount = 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:6}" name="recordStatus">
            <a-select
              ref="select"
              v-model:value="searchParams.recordStatus"
              :options="postStatusList"
              :field-names="{ label: 'name', value: 'value' }"
              :allow-clear="true"
              @change="loadData"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="edit-operation">
        <a-col :span="24" style="text-align: right">
          <a-button type="primary" html-type="submit" functioncode="T01020202" @click='onAdd'>新增</a-button>
          <BImportExcel
            functioncode="T01020205"
            :options="importOptions"
            @success="loadData"
          ></BImportExcel>
          <BExportExcel :title="'导出'" :filename="'岗位信息'"
                        :url="'companyService/post/export'"
                        :params="{...searchParams, isExport: true, rows:10000,postIDList:formState.selectedRowKeys.join(',')}"></BExportExcel>
        </a-col>
      </a-row>
    </a-form>
    <div class="search-result-list">
      <a-table :columns="columns" :data-source="dataList" :scroll="{ x:2000, y: 500 }" :pagination="pagination"
               :loading="formState.loading"
               @change="handleTableChange"
               :row-selection="{ selectedRowKeys: formState.selectedRowKeys, onChange: onSelectChange}"
               :row-key="record=>record.postID"
               bordered>
        <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" @click='onEdit(record)' functioncode="T01020203">编辑</a-button>
              <a-button type="link" size="small" @click="onDel(record)" functioncode="T01020204">删除</a-button>
              <a-button type="link" size="small"  @click="onRecommendJob(record)" functioncode="T01030207">推荐求职人员</a-button>
            </div>
          </template>
        </template>
      </a-table>
    </div>
    <Recommend ref="recommendRef"></Recommend>
  </div>
</template>

<script lang="ts">
import {reactive, ref, computed, defineComponent, createVNode} from 'vue';
import {DownOutlined, UpOutlined} from '@ant-design/icons-vue';
import type {FormInstance} from 'ant-design-vue';
import {Modal, SelectProps} from 'ant-design-vue';
import type {TableColumnsType, TableProps} from 'ant-design-vue';
import {getList, del} from '@/api/companyService/post';
import BExportExcel from "@/components/basic/excel/exportExcel/exportExcel.vue";
import BImportExcel from '@/components/basic/excel/importExcel/importExcel.vue';
import {getPaginationTotalTitle} from "@/utils/common";
import {ExclamationCircleOutlined} from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import {useRoute} from 'vue-router';
import {useTabsViewStore} from "@/store/modules/tabsView";
import type {ImportProps} from "@/components/basic/excel/importExcel/ImportProps";
import {get} from "@/api/common";
import Recommend from "@/views/companyService/post/recommend.vue";

export default defineComponent({
  components: {DownOutlined, UpOutlined, BExportExcel, BImportExcel, Recommend},
  setup: function () {
    const formRef = ref<FormInstance>();
    const searchParams = reactive({
      pageIndex: 1,
      pageSize: 20,
      minCount: null,
      maxCount: null,
      professionName: null,
      recordStatus: null
    });
    const expand = ref(false);
    const companyList = ref<SelectProps['options']>();
    const postStatusList = [{name: '启用', value: 1}, {name: '禁用', value: 0}];
    const recommendRef = ref();
    const importOptions = ref<ImportProps>({
      title: '导入',
      url: 'companyService/post/importPost',
      columns: [
        {cnName: '企业名称', enName: 'companyName', width: 100},
        {cnName: '岗位名称', enName: 'professionName', width: 100},
        {cnName: '招聘人数', enName: 'recruitCount', width: 100},
        {cnName: '开始日期', enName: 'startTime', width: 100},
        {cnName: '结束日期', enName: 'endTime', width: 100},
        {cnName: '招聘地点', enName: 'jobPlace', width: 100},
        {cnName: '工作年限', enName: 'workYear', width: 100},
        {cnName: '学历要求', enName: 'cultureLevelName', width: 100},
        {cnName: '岗位最高月薪', enName: 'maxSalary', width: 100},
        {cnName: '岗位最低月薪', enName: 'minSalary', width: 100},
        {cnName: '是否有试用期', enName: 'isTrailName', width: 100},
        {cnName: '试用期时长(月)', enName: 'trailtime', width: 100},
        {cnName: '试用期最高薪酬', enName: 'trailMaxSalary', width: 100},
        {cnName: '试用期最低薪酬', enName: 'trailMinSalary', width: 100},
        {cnName: '福利待遇', enName: 'welfare', width: 100},
        {cnName: '其它要求', enName: 'postDesc', width: 100}
      ],
      template: {
        tempFileName: '岗位信息导入模板.xlsx',
        url: '',
        params: null,
      },
    });
    const formState = reactive({
      total: 0,
      selectedRowKeys: [],
      loading: false
    });
    const columns: TableColumnsType = [
      {
        title: '序号',
        align: "center",
        key: 'institutionID',
        width: 90,
        customRender: item => `${searchParams.pageSize * (searchParams.pageIndex - 1) + item.index + 1}`
      },
      {title: '岗位名称', dataIndex: 'professionName', key: 'professionName', align: "center"},
      {title: '招聘人数', dataIndex: 'recruitCount', key: 'recruitCount', width: 120, align: "center"},
      {
        title: '开始日期', dataIndex: 'startTime', key: 'startTime', align: "center", customRender: (item) => {
          return item.record.startTime == null ? "" : (dayjs(item.record.startTime).format('YYYY-MM-DD'))
        }
      },
      {title: '结束日期', dataIndex: 'endTime', key: 'endTime', align: "center",customRender: (item) => {
          return item.record.endTime == null ? "" : (dayjs(item.record.endTime).format('YYYY-MM-DD'))
        }
      },
      {title: '招聘企业', dataIndex: 'companyName', key: 'companyName', align: "center"},
      {
        title: '岗位状态', dataIndex: 'recordStatus', key: 'recordStatus', align: "center", customRender: (item) => {
          return item.record.recordStatus == 1 ? "启用" : "停用";
        }
      },
      // {title: '工种名称', dataIndex: 'workName', key: 'workName', align: "center"},
      {title: '文化程度', dataIndex: 'cultureLevelName', key: 'cultureLevelName', width: 150, align: "center"},
      {
        title: '薪酬', dataIndex: 'postSalary', key: 'postSalary', align: "center", customRender: (item) => {
          const salary = showSalary(item.record.minSalary,item.record.maxSalary);/*`${item.record.minSalary ?? ""}-${item.record.maxSalary ?? ""}`*/
          return salary;
        }
      },
      {title: '联系人', dataIndex: 'userName', key: 'userName', align: "center"},
      {title: '联系电话', dataIndex: 'userMobile', key: 'userMobile', width: 200, align: "center"},
      {title: '推荐数量', dataIndex: 'recommendNum',key: 'recommendNum',width: 100, align: "center"},
      {title: '操作', key: 'operation', fixed: 'right', width: 200, align: "center"},
    ];
    const pagination = computed(() => ({
      total: formState.total,
      current: searchParams.pageIndex,
      pageSize: searchParams.pageSize,
      showSizeChanger: true,
      showTotal: total => getPaginationTotalTitle(total)
    }));
    const tabsViewStore = useTabsViewStore();
    const dataList = ref([]);
    const loadData = async function () {
      formState.loading = true;
      const result: any = await getList(searchParams);
      dataList.value = result.list;
      console.log("所有岗位信息",dataList.value);
      formState.total = result.total;
      formState.loading = false;
    }

    const onAdd = () => {
      tabsViewStore.addTabByPath('/companyService/post/add', {});
    };
    const onEdit = (item: any) => {
      tabsViewStore.addTabByPath('/companyService/post/edit', {id: item.postID});
    };

    const onRecommendJob = (item) =>{
      recommendRef.value.show(item.professionID,item.professionName,item.postID,item.companyName,0,'推荐求职人员');
    }

    const onRecommendInfo = (item) =>{
      recommendRef.value.show(item.professionID,item.professionName,item.postID,item.companyName,1,'求职人员信息');
    }

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

    const getCompanyList = () => {
      console.log('getCompanyList');
      get('companyService/company/getList', {pageIndex: 1, pageSize: 999}).then(result => {
        companyList.value = result.list;
        console.log(companyList.value);
      })
    }

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

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

    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 onDel = (item: any) => {
      console.log(item.postID);
      Modal.confirm({
        title: '确认删除该岗位？',
        icon: createVNode(ExclamationCircleOutlined),
        content: '',
        okText: '确认删除',
        okType: 'danger',
        okButtonProps: {},
        cancelText: '取消',
        onOk() {
          del([item.postID]).then(() => {
            loadData();
          });
        },
        onCancel() {
        },
      })
    };

    return {
      formRef,
      searchParams,
      formState,
      columns,
      pagination,
      dataList,
      importOptions,
      recommendRef,
      showSalary,
      getCompanyList,
      handleTableChange,
      onSelectChange,
      onSearch,
      onDel,
      loadData,
      onAdd,
      onEdit,
      onRecommendJob,
      onRecommendInfo,
      expand,
      postStatusList,
      companyList
    };
  },
  created() {
    this.loadData();
    this.getCompanyList();
  },
  activated() {
    const route = useRoute();
    if (route.params.reload) this.loadData();
  }
});
</script>
<style lang="less" scoped></style>
