<template>
  <ion-page  class="list-page">
    <ion-header class="header-theme2">
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-icon :icon="arrowBackOutline" @click="onCancel" style="padding-left:10px;width:24px;height:24px;"></ion-icon>
        </ion-buttons>
        <ion-title>求职意向收集</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content>
      <div class="stepFlex">
        <div v-for="(record,key) in stepList" :key="key" class="stepFlex-item">
          <div
              :class="[(record.val < curStepData?.statusVal || curStepData?.statusVal==stepList.val) ? 'greenCircle' :record.val == curStepData?.statusVal ? 'now' : 'grayCircle']"></div>
          <div v-if="key !== stepList.length - 1"
               :class="[record.val < curStepData?.statusVal ? 'greenLine' : 'grayLine']"></div>
          <div class="stepFlex-item-label">
            <p class="stepFlex-item-label-title">{{ record.title }}</p>
            <p class="stepFlex-item-label-desc">{{ record.desc }}</p>
          </div>
        </div>
      </div>

      <!--          <div class="form-input">
                  <ion-label>工种名称<span class="danger">*</span></ion-label>
                  <ion-input name="workName" id="workName"  style="text-align: left;" class="custom"
                             placeholder="请输入工种名称" v-model="dataModel.workName" ></ion-input>
      &lt;!&ndash;            <ion-note slot="error">工种名称不能为空</ion-note>&ndash;&gt;
                </div>-->
      <form ref="editForm" @submit.prevent="onSave">
        <div class="bw-vue-form">
        <ion-list>
          <div class="form-title">求职意向</div>
          <div class="form-input">
            <ion-label>岗位名称<span class="danger">*</span></ion-label>
            <div>
              <ion-input placeholder="请选择岗位" label-placement="stacked" style="float: left;width:78%;"
                         v-model="dataModel.professionName" class="custom" readonly >
              </ion-input>
              <ion-item style="width:22%;float: right;padding:0px;margin: 0px;">
                <post-selection :ProfessionID="dataModel.professionID" @SetProfessionID="onSetProfessionID"></post-selection>
              </ion-item>
            </div>
            <!--            <ion-note slot="error">请选择求职岗位</ion-note>-->
          </div>
          <div class="form-select">
            <ion-label>求职类型<span class="danger">*</span></ion-label>
              <ion-select name="jobHuntType"  id="jobHuntType" okText="确定" cancelText="取消" v-model="dataModel.jobHuntType"
                          interface="action-sheet" placeholder="请选择求职类型" style="width:100%;text-align: left;">
                <ion-select-option v-for=" (it,key) in jobHuntTypeList" :key="key" :value="it.value">
                  {{ it.name }}
                </ion-select-option>
              </ion-select>
<!--              <ion-note slot="error">求职类型不能为空</ion-note>-->
          </div>
          <div class="form-select">
            <ion-label>人才类型<span class="danger">*</span></ion-label>
              <ion-select name="jobUserType"  id="jobUserType" okText="确定" cancelText="取消" v-model="dataModel.jobUserType"
                          interface="action-sheet" placeholder="请选择人才类型"  style="width:100%;text-align: left;">
                <ion-select-option v-for=" (it,key) in jobUserTypeList" :key="key" :value="it.value">
                  {{ it.name }}
                </ion-select-option>
              </ion-select>
<!--              <ion-note slot="error">人才类型不能为空</ion-note>-->
          </div>
          <div class="form-input">
            <ion-label>月薪要求(元)<span class="danger">*</span></ion-label>
            <div>
              <ion-input placeholder="请输入最低薪资" label-placement="stacked" style="float:left;width:42%;"
                         v-model="dataModel.minSalary" class="custom">
              </ion-input>
              <ion-label style="float:left;width:5%;padding-top: 8px;">至</ion-label>
              <ion-input placeholder="请输入最高薪资" label-placement="stacked" style="float:left;width:42%;"
                         v-model="dataModel.maxSalary" class="custom">
              </ion-input>
              <!--              <ion-note slot="error">月薪要求不能为空</ion-note>-->
            </div>
          </div>
          <div style="overflow: hidden;width:100%;"></div>
          <div class="form-input">
            <ion-label>工作年限<span class="danger">*</span></ion-label>
            <ion-input type="number" :min="0" name="workYear" id="workYear" style="text-align: left;" class="custom"
                       placeholder="请输入工作年限" v-model="dataModel.workYear" ></ion-input>
<!--              <ion-note slot="error">工作年限不能为空</ion-note>-->
          </div>
          <div class="form-select">
            <ion-label>期望工作地区<span class="danger">*</span></ion-label>
            <ion-select name="areaWork"  id="areaWork" okText="确定" cancelText="取消" v-model="dataModel.areaWork"
                        interface="action-sheet" placeholder="请选择期望工作地区"  style="width:100%;text-align: left;">
              <ion-select-option v-for="(it,key) in workAreaList" :key="key" :value="it.name">
                {{ it.name }}
              </ion-select-option>
            </ion-select>
<!--              <ion-note slot="error">期望工作地区不能为空</ion-note>-->
          </div>
          <div class="form-input">
            <ion-label>可到职日期<span class="danger">*</span></ion-label>
              <ion-datetime-button datetime="inDate" style="position: relative;right:110px;"></ion-datetime-button>
              <ion-modal :keep-contents-mounted="true">
                <ion-datetime name="inDate" id="inDate" placeholder="可到职日期"
                              v-model="dataModel.inDate"  :prefer-wheel="true"
                              dataformatas="YYYY-MM-DD" presentation="date" cancel-text="取消" done-text="确定"
                              :show-default-buttons="true">
                </ion-datetime>
              </ion-modal>
          </div>
          <div class="form-input">
            <ion-label>其他信息</ion-label>
            <ion-textarea placeholder="请输入其他信息" :rows="3" label-placement="stacked"
                          v-model="dataModel.otherDemand" class="custom" style="border-bottom: 1px solid #fff2e8;">
            </ion-textarea>
          </div>
        </ion-list>
        </div>
      </form>
    </ion-content>
    <ion-footer>
      <ion-toolbar>
          <ion-button style="width: 100%;"  @click="onSave">保  存</ion-button>
      </ion-toolbar>
      <ion-loading
          :is-open="loading"
          message="加载中..."
          @didDismiss="setOpen(false)" >
      </ion-loading>
    </ion-footer>
  </ion-page>
</template>
<script lang="ts">
import {arrowBackOutline,addCircleOutline} from 'ionicons/icons';
import {reactive,defineComponent, computed,ref,toRefs} from "vue";
import {useRoute,useRouter} from "vue-router";
import {required} from "@vuelidate/validators";
import {useVuelidate} from "@vuelidate/core";
import {getJobHuntByID,saveJobHunt} from "@/api/jobHuntInfo";
import {getSysDictionaryList} from '@/api/system/dictionary';
import {alertController, onIonViewDidEnter} from "@ionic/vue";
import dayjs from "dayjs";
import PostSelection from "@/components/postSelection.vue";
import {useUserStore} from "@/store/modules/user";
import {get} from "@/api/common";

interface huntModel {
  dataModel: any;
}
interface SelectProps {
  name: string,
  value: string
}
interface StepParams{
  name: string,
  statusVal: number
}
export class ExampleComponent {
  pinFormatter(value: number) {
    return `${value}`;
  }
}

export default defineComponent({
  name: 'jobHuntEdit',
  components:{PostSelection},
  setup() {
    const router = useRouter();
    const route = useRoute();
    const loading = ref(false);
    const isCommit = ref(false);
    const editForm = ref();
    const curStepData = ref<StepParams>({
      name:"",
      statusVal: 2
    });
    const stepList = ref([
      {title: '基础信息', desc: '个人基础信息', val: 1},
      {title: '教育经历', desc: '完善教育经历',val: 2},
      {title: '工作经验', desc: '完善工作经验', val: 3},
      {title: '求职意向', desc: '个人求职意向', val: 4}
    ]);
    const jobHuntTypeList = ref<SelectProps[]>([]);
    const jobUserTypeList = ref<SelectProps[]>([]);
    const workYearTypeList = ref<SelectProps[]>([]);
    const workAreaList = ref([]);

    const jobHuntData = reactive<huntModel>({dataModel:{
        jobUserID:null,
        loginUserID:'',
        jobHuntType:null,
        jobUserType:null,
        professionID:null,
        professionName:null,
        minSalary:null,
        maxSalary:null,
        workYear:null,
        areaWork:null,
        inDate:dayjs().format("YYYY-MM-DD"),
        otherDemand:null
      }});
    const huntDataRule = computed(()=>{
      return {dataModel:{
          jobHuntType:{required},
          jobUserType:{required},
          professionID:{required},
          professionName:{required},
          minSalary:{required},
          maxSalary:{required},
          workYear:{required},
          areaWork:{required},
          inDate:{required}
        }}});
    const huntDataValid = useVuelidate(huntDataRule,jobHuntData);

    const setOpen = (isOpen: boolean) => {
      loading.value = isOpen;
    };

    const presentAlert = async (message: string) => {
      const alert = await alertController.create({
        header: '错误！',
        message: message,
        buttons: [
          '确定'
        ],
      });

      await alert.present();
    }


    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 getWorkYearTypeList = async function(){
      const data :any = await getSysDictionaryList("WorkYearType");
      workYearTypeList.value = data;
    }
    const getWorkAreaList = async function(){
      const result :any = await get('system/area/getCityList',{});
      workAreaList.value = result;
    }

    const onSetProfessionID = (data: any)=>{
      jobHuntData.dataModel.professionID = data.value;
      jobHuntData.dataModel.professionName = data.text;
    }

    const ifInputAllValid = ()=>{
      let errorMessage = "";
      let hasMinSalary = false;
      let curMinSalary = 0.0;
      if (jobHuntData.dataModel.workYear!=null) {
        if(jobHuntData.dataModel.workYear<0){
          errorMessage +="工作年限不能小于0！";
          isCommit.value = false;
        }
      }
      if (jobHuntData.dataModel.minSalary!=null) {
        hasMinSalary = true;
        curMinSalary = parseFloat(jobHuntData.dataModel.minSalary);
        if(jobHuntData.dataModel.minSalary<0){
          errorMessage +="最低月薪要求不能小于0！";
          isCommit.value = false;
        }
      }
      if (jobHuntData.dataModel.maxSalary!=null) {
        if(jobHuntData.dataModel.maxSalary<0){
          errorMessage +="最高月薪要求不能小于0！";
          isCommit.value = false;
        }
        if(hasMinSalary){
          if(parseFloat(jobHuntData.dataModel.maxSalary) < curMinSalary){
            errorMessage +="最高月薪要求不能小于最低月薪要求！";
            isCommit.value = false;
          }
        }
      }
      if(!isCommit.value){presentAlert(errorMessage);}
    }

    const onSave = async function (){
      isCommit.value = true;
      const isFormCorrect = await huntDataValid.value.$validate();
      if(!isFormCorrect){
        console.log("当前求职意向数据",jobHuntData.dataModel);
        await presentAlert("请填写完整的信息！");
        return null;
      }
      ifInputAllValid();
      if(isCommit.value){
        saveJobHunt(jobHuntData.dataModel).then(result => {
          if (result) {
            router.push({path: './edit', query: {reload:1,jobUserID: jobHuntData.dataModel.jobUserID,status:4}});
          }
        });
      }
    }

    const onCancel = () => {
      router.push({path: './edit', query: {reload:1,jobUserID: jobHuntData.dataModel.jobUserID,status:4}});
    }

    const loadData = async (jobHuntID: any,jobUserID:any,status:any) => {
      loading.value = true;
      isCommit.value = false;
      await getJobHuntTypeList();
      await getJobUserTypeList();
      await getWorkYearTypeList();
      await getWorkAreaList();
      const loginUserInfo = useUserStore().getUserInfo;
      const reqData = await getJobHuntByID(jobHuntID);
      curStepData.value.statusVal = status;
      jobHuntData.dataModel = reqData;
      jobHuntData.dataModel.jobUserID = jobUserID;
      jobHuntData.dataModel.loginUserID = loginUserInfo.userID == undefined?"":loginUserInfo.userID;
      console.log("初始化求职意向 ",jobHuntData.dataModel);
      loading.value = false;
    };

    const reload = (educationID: any,jobUserID:any,status:any) => {
      loadData(educationID,jobUserID,status);
    }

    onIonViewDidEnter(() => {
      if (route.query.reload){
        reload(route.query.jobHuntID,route.query.jobUserID,route.query.status);
      }
    });

    return {
      ...toRefs(jobHuntData),
      arrowBackOutline,
      addCircleOutline,
      editForm,
      curStepData,
      stepList,
      jobUserTypeList,
      jobHuntTypeList,
      workYearTypeList,
      workAreaList,
      setOpen,
      onSetProfessionID,
      onSave,
      onCancel,
      loadData,
      route,
      router,
      loading,
      huntDataValid,
    }
  }
});
</script>
<style lang="less">
.custom{
  --placeholder-color: gray;
  --placeholder-opacity: 0.5;
}

.title-item{
  margin-left: 15px;
  color:#1c3d70 !important;
  font-size: 14px !important;
  font-weight: bold;
}

.stepFlex {
  margin: 0;
  display: flex;
  width: 100%;

  .stepFlex-item {
    position: relative;
    flex: 1;
    text-align: center;
    margin-top: -10px;

    .stepFlex-item-label {
      padding-top: 60px;
      font-size: 14px;

      .stepFlex-item-label-title{
        margin-top:30px;
      }

      .stepFlex-item-label-desc{
        margin-top:5px;color: #b9b9bd;
      }
    }
  }

  .greenCircle {
    top: calc(50% - 15px);
    left: calc(50% - 4px);
    position: absolute;
    z-index: 2;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: #31A2FE;
  }

  .now {
    top: calc(50% - 18px);
    left: calc(50% - 8px);
    position: absolute;
    z-index: 3;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #31A2FE;
    border: 4px solid #c5e8f9;
  }

  .grayCircle {
    top: calc(50% - 15px);
    left: calc(50% - 4px);
    position: absolute;
    z-index: 2;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: #ccc;
  }

  .greenLine {
    width: 100%;
    top: calc(50% - 11px);
    left: calc(50% - 2px);
    height: 2px;
    background-color: #31A2FE;
    position: absolute;
  }

  .grayLine {
    height: 0;
    border: 1px dashed #ccc;
    width: 100%;
    top: calc(50% - 11px);
    left: calc(50% - 2px);
    position: absolute;
  }
}

</style>