<template>
  <div class="card-edit" :visible="formState.loading">
    <a-form :model="dataModel" autocomplete="off" @finish="onFinish" >
      <a-divider orientation="left">求职意向信息</a-divider>
      <a-row type="flex">
        <a-col :span="7">
          <a-form-item label="姓名"  name="jobUserID" :label-col="{span:8}"  :rules="[{ required: true, message: '请输选择求职人员!' }]">
            <a-auto-complete
              v-model:value="dataModel.jobUserName"
              :disabled="isEdit"
              :options="jobUserList"
              @search="selectJobUserList"
              @change="jobUserChange"
              :field-names="{
                            value:'name',
                          }"
            >
              <template #option="item">
                <span v-html="formatStr(item.name,false)"></span>
              </template>
            </a-auto-complete>
          </a-form-item>
        </a-col>
      <a-col :span="8">
        <a-form-item label="求职岗位"  name="professionName" :label-col="{span:7}" :rules="[{ required: true,message:'请选择求职岗位！' }]">
          <a-auto-complete
            v-model:value="dataModel.professionName"
            :options="professionList"
            @search="selectProfessionList"
            @change="professionChange"
            :field-names="{
                            value:'professionName',
                          }"
          >
            <template #option="item">
              <span v-html="formatStr(item.professionName,true)"></span>({{ item.parentProfessionName }})
            </template>
          </a-auto-complete>
        </a-form-item>
      </a-col>
        <a-col :span="9">
          <a-form-item label="月薪要求" name="salary" style="overflow: hidden;line-height: 35px;height: 35px;" :label-col="{span:7}">
              <label style="color:red;float: left;position:relative;right:80px;line-height: 35px;" >*</label>
              <a-input-group compact>
                <a-input-number :min="0" :controls="false" v-model:value="dataModel.minSalary"
                                style="min-width: 145px;max-width: 150px;" 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="dataModel.minSalary" :controls="false" v-model:value="dataModel.maxSalary"
                                style="min-width: 145px;max-width: 150px;" placeholder=""/>
              </a-input-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row type="flex">
        <a-col :span="7">
          <a-form-item label="工作年限"  name="workYear" :label-col="{span:8}" :rules="[{ required: true, message: '请输入工作年限!' }]">
            <a-input type="number" v-model:value="dataModel.workYear" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="8" >
          <a-form-item label="求职类型" name="jobHuntType" :label-col="{span:7}" :rules="[{ required: true, message: '请选择求职类型!' }]">
            <label v-if="opCategory==3">{{dataModel.jobHuntType}}</label>
            <a-select  ref="select"  v-model:value="dataModel.jobHuntType" :options="jobHuntTypeList"
                       :field-names="{label:'name',value:'value'}"   :allow-clear="true"  >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="9">

          <a-form-item label="人才类型"  name="jobUserType" :label-col="{span:7}" :rules="[{ required: true, message: '请选择人才类型!' }]">
            <label v-if="opCategory==3">{{dataModel.jobUserType }}</label>
            <a-select  ref="select"  v-model:value="dataModel.jobUserType" :options="jobUserTypeList"
                       :field-names="{label:'name',value:'value'}"  :allow-clear="true"  >
            </a-select>
          </a-form-item>
        </a-col>

      </a-row>
      <a-row type="flex">
        <a-col :span="7">
          <a-form-item label="希望工作地区"  name="areaWork" :label-col="{span:8}" :rules="[{ required: true, message: '请输入工作地区!' }]">
            <a-select
              ref="select"
              v-model:value="dataModel.areaWork"
              :options="regionList"
              :field-names="{ label: 'name', value: 'name' }"
              :allow-clear="true"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="可到职日期"  name="inDate" :label-col="{span:7}" :rules="[{ required: true, message: '请输入工作地区!' }]">
            <label v-if="opCategory==3">{{dataModel.inDate}}</label>
            <a-date-picker v-model:value="dataModel.inDate"  picker="date" value-format="YYYY-MM-DD"  />
          </a-form-item>
        </a-col>
        <a-col :span="9">

        </a-col>
      </a-row>
      <a-divider orientation="left">其他信息</a-divider>
      <a-row>
        <a-textarea name="otherDemand" :auto-size="{ minRows: 4, maxRows: 10 }"  v-model:value="dataModel.otherDemand" :disabled="opCategory==3"
                    placeholder="其他信息"  />
      </a-row>
      <a-form-item class="buttom-btns">
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" html-type="submit">提交</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts">
import {defineComponent, reactive, ref, toRefs} from "vue";
import {useTabsViewStore} from "@/store/modules/tabsView";
import {getJobHuntByID, saveJobHuntCopy} from "@/api/jobUserManager/jobhunt"
import {getJobUserDataList} from "@/api/jobUserManager/jobuser";
import {getSysDictionaryList} from '@/api/system/dictionary';
import BUploadFile from "@/components/file/uploadFile.vue";
import {message, SelectProps} from "ant-design-vue";
import {get} from "@/api/common";
import {getProfessionLikeList} from "@/api/jobUserManager/recommendMgt";

interface jobHuntModel {
  dataModel: any;
}
export default defineComponent({
  name:'JobHuntEditForm',
  components: {BUploadFile},
  props: {
    loadData: {
      type: Function,
      default: null
    }
  },
  setup() {
    const title = ref();
    const opCategory = ref<any>();
    const tabsViewStore = useTabsViewStore();
    const isAllowCommit = ref<boolean>(true);
    const formData = reactive<jobHuntModel>({dataModel:{}});
    const formState = reactive({
      total: 0,
      selectedRowKeys: [],
      loading: false
    });
    const jobWorkTypeList =  ref<SelectProps['options']>();
    const jobHuntTypeList =  ref<SelectProps['options']>();
    const jobUserTypeList =  ref<SelectProps['options']>();
    const regionList = ref<SelectProps['options']>();
    const professionList = ref<Array<any>>([]);
    const jobUserList = ref<Array<any>>([]);
    const isEdit = ref<boolean>(false);

    const getWorkAreas = async function(){
      const result :any = await get('system/area/getCityList',{});
      regionList.value = result;
    }



    const getJobWorkTypeList = async function(){
      const data :any = await getSysDictionaryList("JobWorkType");
      jobWorkTypeList.value = data;
    }
    const getJobHuntTypeList = async function(){
      const data :any = await getSysDictionaryList("JobHuntType");
      jobHuntTypeList.value = data;
    }
    const getJobUserTypeList = async function(){
      const data :any = await getSysDictionaryList("JobUserType");
      jobUserTypeList.value = data;
    }

    const loadData = (id: string) => {
      isEdit.value = id != null;
      formState.loading = true;
      getWorkAreas();
      getJobUserTypeList();
      getJobHuntTypeList();
      getJobWorkTypeList();
      getJobHuntByID(id).then((result: any) => {
        formData.dataModel = result;
        console.log("初始化数据",formData.dataModel);
        formData.dataModel.hasProfession = true;
      });
      formState.loading = false;
    };

    const onClose = (reload: any) => {
      tabsViewStore.closeCurrentTabByPath('/jobusermgr/jobhunt/add');
      tabsViewStore.closeCurrentTabByPath('/jobusermgr/jobhunt/edit');
      tabsViewStore.openTab('/jobusermgr/jobhunt/index', {reload: reload});
    };

    const onFinish = () => {
      isAllowCommit.value = true;
      if(formData.dataModel.minSalary==null||formData.dataModel.maxSalary==null){
        message.error("最低/最高月薪不能为空!");
        isAllowCommit.value = false;
      }else{
        if(formData.dataModel.minSalary!=""&&formData.dataModel.maxSalary!=""){
          if(formData.dataModel.minSalary>formData.dataModel.maxSalary){
            message.error("最低月薪不能大于最高月薪!");
            isAllowCommit.value = false;
          }
        }
      }

      if(!formData.dataModel.hasProfession){
        message.error("请选择完整的岗位信息!");
        isAllowCommit.value = false;
      }
      if (isAllowCommit.value){
        saveJobHuntCopy(formData.dataModel).then(result => {
          if (result) {
            onClose(1);
          }
        });
      }
    };

    // 查询岗位
    const selectProfessionList = (professionName: string) => {
      if (professionName) {
        getProfessionLikeList({
          pageIndex: 1,
          pageSize: 30,
          professionName,
        }).then(data => {
          professionList.value = data.list;
          setProfessionId(professionName);
          console.log("professionList",professionList.value);
        })
      }
    }

    const selectJobUserList = (jobUserName: string) => {
      if (jobUserName) {
        getJobUserDataList({
          pageIndex: 1,
          pageSize: 30,
          jobUserName,
        }).then(data => {
          jobUserList.value = data.list;
          setJobUserId(jobUserName);
          console.log("jobUserList",jobUserList.value);
        })
      }
    }

    // 岗位名称变更
    function professionChange(value: any) {
      formData.dataModel.professionName = value;
      setProfessionId(value);
    }
    function jobUserChange(value: any) {
      formData.dataModel.name = value;
      setJobUserId(value);
    }

    function setProfessionId(value:any){
      const profession = professionList.value.find(prof => prof.professionName === value);
      if (profession) {
        formData.dataModel.professionID = profession.professionID;
      } else {
        formData.dataModel.professionID = "";
      }
      formData.dataModel.hasProfession = true;
    }

    function setJobUserId(value:any){
      const curJobUser = jobUserList.value.find(x => x.name === value);
      if (curJobUser) {
        formData.dataModel.jobUserID = curJobUser.jobUserID;
      } else {
        formData.dataModel.jobUserID = null;
      }
    }

    // 名称搜索关键字高亮
    const formatStr = (str: any,isProfessionName:boolean) => {
      if (!str) {
        return "";
      }

      if(!isProfessionName){
        return str.replace(formData.dataModel.jobUserName, '<span style="color: coral">' + formData.dataModel.jobUserName + '</span>');
      }
      return str.replace(formData.dataModel.professionName, '<span style="color: coral">' + formData.dataModel.professionName + '</span>');
    }


    return {
      ...toRefs(formData),
      loadData,
      onClose,
      onFinish,
      title,
      formState,
      opCategory,
      regionList,
      jobUserList,
      jobUserTypeList,
      jobHuntTypeList,
      jobWorkTypeList,
      isAllowCommit,
      professionList,
      selectProfessionList,
      selectJobUserList,
      professionChange,
      jobUserChange,
      formatStr,
      isEdit
    };
  },
  created() {
    const id = history.state.params?.id;
    if (id) this.isEdit = true;
    this.loadData(id);
  },
})
</script>

