<template>
  <div class="card-edit">
    <a-form :model="dataModel" autocomplete="off" @finish="onFinish">
      <a-divider orientation="left">求职人员信息</a-divider>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item label="姓名" :label-col="{ span: 6 }"
                       name="name" :rules="[{ required: true, message: '请输入姓名!' }]">
            <a-input v-model:value="dataModel.name" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item  label="身份证号码" :label-col="{ span: 6 }"
                        name="identityNumber" :rules="[{ required: true, message: '请输入身份证号码!' }]" >
            <a-input v-model:value="dataModel.identityNumber" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
        <a-form-item label="性别" :label-col="{span:6}"
                     name="sex" :rules="[{ required: true, message: '请选择性别!' }]">
          <a-select
            ref="select"
            v-model:value="dataModel.sex"
            :options="genderList"
            :field-names="{ label: 'name', value: 'value' }"
            :allow-clear="true"
          >
          </a-select>
        </a-form-item>
      </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item label="重点人员类别" :label-col="{span:6}" name="keyPersonTypeID"
                       :rules="[{ required: true, message: '请选择重点人员类别!' }]">
            <a-select
              ref="select"
              v-model:value="dataModel.keyPersonTypeID"
              :options="keyPersonTypeList"
              :field-names="{ label: 'name', value: 'value' }"
              :allow-clear="true"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="就业状态" :label-col="{span:6}" name="jobStatusID"
                       :rules="[{ required: true, message: '请选择就业状态!' }]">
            <a-select
              ref="select"
              v-model:value="dataModel.jobStatusID"
              :options="jobStatusList"
              :field-names="{ label: 'name', value: 'value' }"
              :allow-clear="true"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="所属驿站" :label-col="{span:6}" name="siteID"
                       :rules="[{ required: true, message: '请选择所属驿站!' }]">
            <a-select
              ref="select"
              v-model:value="dataModel.siteID"
              :options="siteList"
              :field-names="{ label: 'siteName', value: 'siteID' }"
              :allow-clear="true"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item
            label="联系人"
            :label-col="{ span: 6 }"
            name="userName">
            <a-input v-model:value="dataModel.userName" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="联系电话" :label-col="{ span: 6 }"
                       name="userMobile" :rules="[{ required: true,message: '请输入联系电话!' }]">
            <a-input  v-model:value="dataModel.userMobile" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="地址"
            :label-col="{ span: 6 }"
            name="address"
            :rules="[{ required: true, message: '请输入地址!' }]"
          >
            <a-input v-model:value="dataModel.address" placeholder=""/>
          </a-form-item>
        </a-col>
      </a-row>

      <a-divider orientation="left">其它信息</a-divider>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item label="民族" :label-col="{ span: 6 }"  name="nation">
            <!--            <a-input v-model:value="dataModel.nation" placeholder=""/>-->
            <a-select
              ref="select"
              v-model:value="dataModel.nation"
              :options="nationList"
              :field-names="{ label: 'name', value: 'value' }"
              :allow-clear="true"
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="政治面貌" :label-col="{span:6}" name="politicsStatusID">
            <a-select
              ref="select"
              v-model:value="dataModel.politicsStatusID"
              :options="politicsStatusList"
              :field-names="{ label: 'name', value: 'value' }"
              :allow-clear="true"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="出生地" :label-col="{ span: 6 }" name="birthPlace">
            <a-input v-model:value="dataModel.birthPlace" placeholder=""/>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item label="出生日期" :label-col="{ span: 6 }" name="birthDay" >
            <a-date-picker
              v-model:value="dataModel.birthDay"
              picker="date"
              value-format="YYYY-MM-DD"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="户口性质" :label-col="{span:6}" name="familyNatureID" >
            <a-select
              ref="select"
              v-model:value="dataModel.familyNatureID"
              :options="familyNatureList"
              :field-names="{ label: 'name', value: 'value' }"
              :allow-clear="true"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="文化程度" :label-col="{span:6}" name="cultureRank">
            <a-select
              ref="select"
              v-model:value="dataModel.cultureRank"
              :options="cultureList"
              :field-names="{ label: 'name', value: 'value' }"
              :allow-clear="true"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item label="健康状况" :label-col="{span:6}" name="healthID">
            <a-select
              ref="select"
              v-model:value="dataModel.healthID"
              :options="healthList"
              :field-names="{ label: 'name', value: 'value' }"
              :allow-clear="true"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
        <a-form-item label="婚姻状况" :label-col="{span:6}" name="maritalStatusID">
          <a-select
            ref="select"
            v-model:value="dataModel.maritalStatusID"
            :options="maritalStatusList"
            :field-names="{ label: 'name', value: 'value' }"
            :allow-clear="true"
          >
          </a-select>
        </a-form-item>
      </a-col>
        <a-col :span="8">
          <a-form-item
            label="血型"
            :label-col="{ span: 6 }"
            name="bloodTypeID" >
            <a-select
              ref="select"
              v-model:value="dataModel.bloodTypeID"
              :options="bloodTypeList"
              :field-names="{ label: 'name', value: 'value' }"
              :allow-clear="true"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item
            label="身高"
            :label-col="{ span: 6 }"
            name="height">
            <a-input v-model:value="dataModel.height" placeholder="" suffix="cm"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="体重"
            :label-col="{ span: 6 }"
            name="weight" >
            <a-input v-model:value="dataModel.weight" placeholder="" suffix="kg"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="视力"
            :label-col="{ span: 6 }"
            name="vision">
            <a-input v-model:value="dataModel.vision" placeholder=""/>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item label="省份" :label-col="{span:6}" name="provinceCode">
            <a-select
              ref="select"
              v-model:value="dataModel.provinceCode"
              :options="provinceList"
              :field-names="{ label: 'name', value: 'code' }"
              :allow-clear="true"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="市/县" :label-col="{span:6}" name="regionCode">
            <a-select
              ref="select"
              v-model:value="dataModel.regionCode"
              :options="regionList"
              :field-names="{ label: 'name', value: 'code' }"
              :allow-clear="true"
              @change="regionChange"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="镇街" :label-col="{span:6}" name="streetCode">
            <a-select
              ref="select"
              v-model:value="dataModel.streetCode"
              :options="streetList"
              :field-names="{ label: 'name', value: 'code' }"
              :allow-clear="true"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>



      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item
            label="家庭住址"
            :label-col="{ span: 6 }"
            name="familyAddress" >
            <a-input v-model:value="dataModel.familyAddress" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="邮政编码"
            :label-col="{ span: 6 }"
            name="postalCode">
            <a-input v-model:value="dataModel.postalCode" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="电子邮箱"
            :label-col="{ span: 6 }"
            name="email">
            <a-input v-model:value="dataModel.email" placeholder=""/>
          </a-form-item>
        </a-col>
      </a-row>


      <a-row :gutter="24">
        <a-col :span="16">
          <a-form-item label="兴趣爱好" :label-col="{ span: 3}" name="hobby" >
            <a-textarea v-model:value="dataModel.hobby" placeholder="兴趣爱好" :rows="2" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="16">
          <a-form-item label="个人技能" :label-col="{ span: 3 }" name="personalSkills" >
            <a-textarea v-model:value="dataModel.personalSkills" placeholder="个人技能" :rows="4" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" style="text-align: right; margin-top: 20px; margin-right: 20px">
          <Space>
            <a-button @click="addEducation">
              <template #icon>
                <plus-circle-outlined/>
              </template>
              新增
            </a-button>
          </Space>
        </a-col>
      </a-row>
      <a-divider orientation="left">教育经历</a-divider>
      <a-row>
        <a-col style="margin-bottom: 20px;">
          <a-table :columns="educationColumns" :data-source="educationData" :pagination="false" bordered>
            <template #bodyCell="{ column ,index}">
              <template v-if="column.key === 'schoolName'">
                <div>
                  <a-input v-model:value="educationData[index][column.key]" style="width: 200px" />
                </div>
              </template>
              <template v-if="column.key === 'cultureRank'">
                <div>
                  <a-select
                    ref="select"
                    v-model:value="educationData[index][column.key]"
                    :options="cultureList"
                    :field-names="{ label: 'name', value: 'value' }"
                    :allow-clear="false" style="width: 200px" >
                  </a-select>
                </div>
              </template>
              <template v-if="column.key === 'schoolTime'">
                <div>
                  <a-date-picker
                    v-model:value="educationData[index][column.key]"
                    picker="date" :allow-clear="false"
                    value-format="YYYY-MM-DD"
                  />
                </div>
              </template>
              <template v-if="column.key === 'overTime'">
                <div>
                  <a-date-picker
                    v-model:value="educationData[index][column.key]"
                    picker="date" :allow-clear="false"
                    value-format="YYYY-MM-DD"
                  />
                </div>
              </template>
              <template v-if="column.key === 'major'">
                <div>
                  <a-input
                    v-model:value="educationData[index][column.key]" style="width: 200px"
                  />
                </div>
              </template>
              <template v-if="column.key === 'educationOperation'">
                <a-button type="link" size="small" @click="delEducation(index)">删除</a-button>
              </template>
            </template>
          </a-table>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" style="text-align: right; margin-top: 20px; margin-right: 20px">
          <Space>
            <a-button @click="addExperience">
              <template #icon>
                <plus-circle-outlined/>
              </template>
              新增
            </a-button>
          </Space>
        </a-col>
      </a-row>
      <a-divider orientation="left">工作经历</a-divider>
      <a-row>
        <a-col style="margin-bottom: 20px;">
          <a-table :columns="experienceColumns" :data-source="experienceData" :pagination="false"
                   bordered>
            <template #bodyCell="{ column ,index}">
              <template v-if="column.key === 'startTime'">
                <div>
                  <a-date-picker v-model:value="experienceData[index][column.key]"
                                 picker="date" value-format="YYYY-MM-DD" :allow-clear="false"  />
                </div>
              </template>
              <template v-if="column.key === 'endTime'">
                <div>
                  <a-date-picker v-model:value="experienceData[index][column.key]"
                                 picker="date" value-format="YYYY-MM-DD" :allow-clear="false"  />
                </div>
              </template>
              <template v-if="column.key === 'workAddress'">
                <div>
                  <a-input
                    v-model:value="experienceData[index][column.key]" style="width: 200px"
                  />
                </div>
              </template>
              <template v-if="column.key === 'duties'">
                <div>
                  <a-input
                    v-model:value="experienceData[index][column.key]" style="width: 200px"
                  />
                </div>
              </template>
              <template v-if="column.key === 'experienceOperation'">
                <a-button type="link" size="small" @click="deleteExperience(index)">删除</a-button>
              </template>
            </template>
          </a-table>
        </a-col>
      </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 type {SelectProps, TableColumnsType} from 'ant-design-vue';
import {message} from "ant-design-vue";
import {useTabsViewStore} from '@/store/modules/tabsView';
import BUploadFile from '@/components/file/uploadFile.vue';
import {get} from "@/api/common";
import {getSysDictionaryList} from '@/api/system/dictionary';
import {getDataById, getEducationList, getExperienceList, save} from '@/api/jobUserManager/jobuser';
import {getSiteList} from "@/api/baseSettings/siteInfo";
import {getInfo} from "@/api/account";

interface FormState {
  dataModel: any;
}

export default defineComponent(
  {
    components: {BUploadFile},
    setup() {
      // const router = useRouter();
      const isAllowCommit = ref(true);
      const formState = reactive<FormState>({dataModel: {}});
      const formTableState = reactive({loading: false});
      const searchParams = reactive({
        pageIndex: 1,
        pageSize: 99
      });
      const provinceList = ref<SelectProps['options']>([{name: '广东省', code: '440000000000000'}]);
      const siteList = ref<any>([]);
      const genderList = ref<SelectProps['options']>();
      const keyPersonTypeList = ref<SelectProps['options']>();
      const jobStatusList = ref<SelectProps['options']>();
      const maritalStatusList = ref<SelectProps['options']>();
      const healthList = ref<SelectProps['options']>();
      const bloodTypeList = ref<SelectProps['options']>();
      const cultureList = ref<SelectProps['options']>();
      const politicsStatusList = ref<SelectProps['options']>();
      const regionList = ref<SelectProps['options']>();
      const streetList = ref<SelectProps['options']>();
      const familyNatureList = ref<SelectProps['options']>();
      const nationList = ref<SelectProps['options']>();

      const educationData = ref([]);
      const educationColumns: TableColumnsType = [
        {
          title: '序号',
          align: "center",
          key: 'educationID',
          width: 120,
          customRender: item => `${searchParams.pageSize * (searchParams.pageIndex - 1) + item.index + 1}`
        },
        {
          title: '学校名',
          dataIndex: 'schoolName',
          key: 'schoolName',
          align: "center",
          width: 120
        },
        {
          title: '文化程度',
          dataIndex: 'cultureRank',
          key: 'cultureRank',
          align: "center",
          width: 120
        },
        {
          title: '就读时间',
          dataIndex: 'schoolTime',
          key: 'schoolTime',
          align: "center",
          width: 120
        },
        {
          title: '毕业时间',
          dataIndex: 'overTime',
          key: 'overTime',
          align: "center",
          width: 120
        },
        {
          title: '专业',
          dataIndex: 'major',
          key: 'major',
          align: "center",
          width: 120
        },
        {title: '操作', key: 'educationOperation', fixed: 'right', width: 120, align: "center"},
      ];
      // const fullpath = router.currentRoute.value.fullPath;
      const tabsViewStore = useTabsViewStore();
      const isEdit = true;

      const fileList = ref();
      const setFileList = (files) => {
        fileList.value = files;
      };

      const inputDataValidate = () =>{
        isAllowCommit.value = true;
        const identReg = /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/;
        if(!formState.dataModel.identityNumber.match(identReg)){
          message.error("输入的身份证号码有误!");
          isAllowCommit.value = false;
        }
        const mobileReg = /^1[3|4|5|6|7|8|9]\d{9}$/;
        if(!mobileReg.test(formState.dataModel.userMobile)){
          message.error("输入的联系电话有误!");
          isAllowCommit.value = false;
        }
        const emailReg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
        if(formState.dataModel.email!=null && formState.dataModel.email.trim()!==""){
          if(!emailReg.test(formState.dataModel.email)){
            message.error("输入的电子邮箱有误!");
            isAllowCommit.value = false;
          }
        }
      };

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


      const getHealthList = () => {
        getSysDictionaryList('Health').then((data) => {
          healthList.value = data;
        });
      };
      const getGenderList = () => {
        getSysDictionaryList('Gender').then((data) => {
          genderList.value = data;
        });
      };
      const getCultureList = () => {
        getSysDictionaryList('CultureLevel').then((data) => {
          cultureList.value = data;
        });
      };
      const getJobStatusList = () => {
        getSysDictionaryList('JobStatus').then((data) => {
          jobStatusList.value = data;
        });
      };
      const getNationList = () => {
        getSysDictionaryList('NationType').then((data) => {
          nationList.value = data;
        });
      };
      const getBloodTypeList = () => {
        getSysDictionaryList('BloodType').then((data) => {
          bloodTypeList.value = data;
        });
      };
      const getFamilyNatureList = () => {
        getSysDictionaryList('FamilyNature').then((data) => {
          familyNatureList.value = data;
        });
      };
      const getKeyPersonTypeList = () => {
        getSysDictionaryList('KeyPersonType').then((data) => {
          keyPersonTypeList.value = data;
        });
      };
      const getMaritalStatusList = () => {
        getSysDictionaryList('MaritalStatus').then((data) => {
          maritalStatusList.value = data;
        });
      };
      const getPoliticsStatusList = () => {
        getSysDictionaryList('PoliticsStatus').then((data) => {
          politicsStatusList.value = data;
        });
      };


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

      const changeCity = () => {
        if (formState.dataModel.regionCode) {
          get('system/area/getAreaList', {code: formState.dataModel.regionCode}).then(data => {
            streetList.value = data;
            // formState.dataModel.streetCode = "";
          })
        }
      }

      const regionChange = async function () {
        formState.dataModel.streetCode = null;
        changeCity();
      }

      const loadEducation = (id: any) => {
        getEducationList(id).then(data => {
          if (data)
            educationData.value = data;
        });
      }
      const addEducation = () => {
        (educationData.value as any[]).push({
          schoolName: '',
          cultureRank: null,
          schoolTime: null,
          overTime: null,
          major: ''
        });
      }
      const delEducation = (record) => {
        (educationData.value as any[]).splice(record, 1);
      }

      const experienceColumns: TableColumnsType = [
        {
          title: '序号',
          align: "center",
          key: 'experienceID',
          width: 120,
          customRender: item => `${searchParams.pageSize * (searchParams.pageIndex - 1) + item.index + 1}`
        },
        {
          title: '开始时间',
          dataIndex: 'startTime',
          key: 'startTime',
          align: "center",
          width: 120
        },
        {
          title: '结束时间',
          dataIndex: 'endTime',
          key: 'endTime',
          align: "center",
          width: 120
        },
        {
          title: '工作单位',
          dataIndex: 'workAddress',
          key: 'workAddress',
          align: "center",
          width: 120
        },
        {
          title: '职务',
          dataIndex: 'duties',
          key: 'duties',
          align: "center",
          width: 120
        },
        {title: '操作', key: 'experienceOperation', fixed: 'right', width: 120, align: "center"},
      ]
      const experienceData = ref([]);
      const loadExperienceData = (id: any) => {
        getExperienceList(id).then(data => {
          if (data) {
            experienceData.value = data;
          }
        })
      }
      const deleteExperience = (record) => {
        (experienceData.value as any[]).splice(record, 1);
      }

      const addExperience = () => {
        (experienceData.value as any[]).push({
          startTime: null,
          endTime: null,
          workAddress: null,
          duties: null,
        });
      }

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

      const onFinish = () => {
        inputDataValidate();
        if(isAllowCommit.value){
          formState.dataModel.jobEducation = educationData.value;
          formState.dataModel.jobExperience = experienceData.value;
          save(formState.dataModel).then(result => {
            if (result) {
              onClose(1)
            }
          });
        }
      }

      const loadData = (id: any) => {
        getAllSites();
        getHealthList();
        getGenderList();
        getCultureList();
        getJobStatusList();
        getNationList();
        getBloodTypeList();
        getFamilyNatureList();
        getKeyPersonTypeList();
        getMaritalStatusList();
        getPoliticsStatusList();
        getInfo().then((loginUserInfo:any)=>{
          getDataById(id,loginUserInfo.userID).then(data => {
            formState.dataModel = data;
            if (formState.dataModel.regionCode) {
              changeCity();
            }
          });
        });
      };

      return {
        ...toRefs(formState),
        isEdit,
        loadData,
        onClose,
        onFinish,
        setFileList,
        addEducation,
        delEducation,
        loadEducation,
        inputDataValidate,
        siteList,
        regionList,
        streetList,
        cultureList,
        genderList,
        healthList,
        jobStatusList,
        provinceList,
        bloodTypeList,
        maritalStatusList,
        familyNatureList,
        formState,
        educationData,
        experienceData,
        formTableState,
        keyPersonTypeList,
        politicsStatusList,
        changeCity,
        regionChange,
        loadExperienceData,
        deleteExperience,
        addExperience,
        experienceColumns,
        educationColumns,
        nationList
      }
    },
    created() {
      const id = history.state.params?.id;
      this.loadData(id);
      if (id) {
        this.loadEducation(id);
        this.loadExperienceData(id);
      }
    }
  })
</script>

