<template>
  <div class="app-container">
    <div class="content total-form">
      <div class="pl-5 mb20 steps-left">
        <el-timeline>
          <el-timeline-item
            v-for="(voteActivity, index) in activities"
            :key="index"
            :color="index === currentIndex ? '#0bbd87': ''"
          >
            <a :style="{color:index === currentIndex ? '#0bbd87': ''}" @click="handleSteps(voteActivity,index)">{{ voteActivity.content }}</a>
          </el-timeline-item>
        </el-timeline>
      </div>
      <div class="steps-right">
        <el-form ref="form" :rules="rules" :model="formState" label-width="100px">
        <div id="section1">
          <div class="top-title">基础信息</div>
          <el-row style="display: flex; flex-wrap: wrap;">
            <el-col :span="12">
              <el-form-item label="专家姓名" prop="nickName">
                <el-input v-model="formState.nickName" placeholder="请输入专家姓名" :minlength="1"
                          :maxlength="10" clearable show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input v-model="formState.phonenumber" placeholder="请输入手机号码" maxlength="11" show-word-limit clearable  />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="formState.sex">
                  <el-radio
                    v-for="dict in dict.type[DictType.sys_sex]"
                    :key="dict.value"
                    :label="dict.value"
                  >{{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formState.email" placeholder="请输入邮箱" maxlength="30" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="政治面貌">
                <el-select v-model="formState.politicalStatus" placeholder="请选择政治面貌" filterable style="width: 100%">
                  <el-option
                    v-for="dict in dict.type[DictType.political_status]"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="identificationCard">
                <el-input v-model="formState.identificationCard" placeholder="请输入身份证号" maxlength="18" clearable show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生日期">
                <el-date-picker
                  v-model="formState.birthDate"
                  type="date"
                  placeholder="请选择出生日期"
                  style="width: 100%"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="民族" >
                <el-select v-model="formState.nation" placeholder="请选择民族" filterable  style="width:100%;">
                  <el-option
                    v-for="dict in dict.type[DictType.sys_nation_type]"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="常驻省市">
                <area-cascader :province-id.sync="formState.provinceId" :city-id.sync="formState.cityId" :placeholder="'请选择所在省市'" :level="2" ></area-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="照片">
                <upload-image :show-text="true" :value.sync="formState.avatar" :max-size="2" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider class="mini-divider-table" />
        </div>
        <div id="section2">
          <div class="top-title">专家资质</div>
          <el-row style="display: flex; flex-wrap: wrap;">
            <el-col :span="12">
              <el-form-item label="工作单位" >
                <el-input v-model="formState.workOrganization" placeholder="请输入工作单位" maxlength="30" clearable show-word-limit  />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作职位" >
                <el-input v-model="formState.workPosition" placeholder="请输入工作职位" maxlength="30" clearable show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职称等级">
                <el-select v-model="formState.professionalTitleGrade" placeholder="请选择职称等级" filterable style="width: 100%">
                  <el-option
                    v-for="dict in dict.type[DictType.professional_title_grade]"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="社会任职" >
                <el-input v-model="formState.socialService" placeholder="请输入社会任职" maxlength="30" clearable show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="研究领域" >
                <el-input v-model="formState.researchField" placeholder="请输入研究领域" maxlength="100" clearable show-word-limit/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="研究学科" >
                <el-input v-model="formState.researchDiscipline" placeholder="请输入研究学科" maxlength="30" clearable show-word-limit />
              </el-form-item>
            </el-col>
            <el-col  :span="24">
              <el-form-item label="工作经历">
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form label-position="top" >
                <div v-for="(item, index) in workExperience" :key="index">
                  <el-row :gutter="20"  type="flex" justify="center"  >
                    <el-col :span="2">
                      <el-form-item label="">
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="工作时间">
                        <el-col :span="11">
                          <el-form-item prop="startTime" >
                            <el-date-picker type="date"  placeholder="请选择开始时间" value-format="yyyy-MM-dd" v-model="item.startTime" style="width: 100%;"></el-date-picker>
                            <span class="err_msg" v-if="item.status">当前行信息不可全部为空</span>
                          </el-form-item>
                        </el-col>
                        <el-col class="line" :span="2" style="text-align: center">-</el-col>
                        <el-col :span="11">
                          <el-form-item prop="endTime" :rules="[{ validator: validateDate, trigger: 'blur' }]">
                            <el-date-picker placeholder="请选择结束时间"   value-format="yyyy-MM-dd" v-model="item.endTime" style="width: 100%;" :class="{'err_border': indices.some( (it)=> it == index && item.endTime)}" @clear="handleClearTime"></el-date-picker>
                            <span class="err_msg" v-if="indices.some( (it)=> it == index && item.endTime)">结束时间不能早于开始时间</span>
                          </el-form-item>
                        </el-col>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="工作单位">
                        <el-input v-model="item.workOrganization" placeholder="请输入工作单位" maxlength="30" clearable show-word-limit></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="3" style="display: flex; align-items: center" >
                      <div class="icons_type" style="transform: translateY(50%)" >
                        <i class="el-icon-circle-plus-outline icon_small icon_small_green" @click="handleAddWork(item,index)" v-if="index + 1 === workExperience.length && workExperience.length < 10"></i>
                        <i class="el-icon-delete icon_small icon_small_red" @click="handleDeleteWork(index)" v-if="index > 0"></i>
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </el-form>
            </el-col>
            <el-col  :span="24">
              <el-form-item label="第一学历" prop="year">
              </el-form-item>
            </el-col>
            <el-form label-position="top">
              <el-row :gutter="20"  type="flex" justify="center"  >
                <el-col :span="3">
                  <el-form-item label="">
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="学历">
                    <el-select v-model="normaleducation[0].educationalBackground" placeholder="请选择学历" filterable>
                      <el-option
                        v-for="dict in dict.type[DictType.educational_background]"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="毕业院校">
                    <el-input v-model="normaleducation[0].graduateSchool" placeholder="请输入毕业院校" maxlength="30" clearable show-word-limit></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="所学专业">
                    <el-input v-model="normaleducation[0].profession" placeholder="请输入所学专业" maxlength="30" clearable show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-divider class="mini-divider-table" />
            <el-col  :span="24">
              <el-form-item label="最高学历">
              </el-form-item>
            </el-col>
            <el-form label-position="top">
              <el-row :gutter="20"  type="flex" justify="center"  >
                <el-col :span="3">
                  <el-form-item label="">
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="学历">
                    <el-select v-model="highestEducation[0].educationalBackground" placeholder="请选择最高学历" filterable>
                      <el-option
                        v-for="dict in dict.type[DictType.educational_background]"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="毕业院校">
                    <el-input v-model="highestEducation[0].graduateSchool" placeholder="请输入毕业院校" maxlength="30" clearable show-word-limit></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="所学专业">
                    <el-input v-model="highestEducation[0].profession" placeholder="请输入所学专业" maxlength="30" clearable show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-divider class="mini-divider-table" />
            <el-col  :span="24">
              <el-form-item label="专家简介" >
                <el-input type="textarea" :rows="3" v-model="formState.expertProfile" maxlength="300" placeholder="请输入专家简介" clearable show-word-limit></el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="24">
              <el-form-item label="专家详细介绍" >
                <el-divider class="mini-divider-table" />
                <editor v-model="formState.expertDetails" :min-height="192" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider class="mini-divider-table" />
        </div>
        <div id="section3">
          <div class="top-title">科研荣誉</div>
          <el-row style="display: flex; flex-wrap: wrap;">
            <el-row>
              <el-col :span="24">
                <el-form-item label="科研成果" >
                  <editor v-model="formState.scientificResearchAchievement" :min-height="192" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="荣誉成果" >
                  <editor v-model="formState.honoraryAchievement" :min-height="192" />
                </el-form-item>
              </el-col>
              <el-col  :span="24">
                <el-form-item label="备注" >
                  <el-input type="textarea" :rows="3" v-model="formState.remark" maxlength="300" placeholder="请输入备注" clearable show-word-limit></el-input>
                </el-form-item>
              </el-col>
            </el-row>

          </el-row>
          <el-divider class="mini-divider-table" />
        </div>
          </el-form>
      </div>
    </div>
    <div class="content" style="margin: 10px 0">
      <div class="footer-btns">
        <el-button type="primary" @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit()">保存</el-button>
      </div>
    </div>
  </div>
</template>
<script>

import { addExpert, editExpert, getExpertDetails } from '@/api/system/expert'
import options from '@/utils/dict/options'
import regex from '@/utils/regex'
import uploadImage from '@/components/Upload/uploadImage.vue'
import { validateIdNo } from '@/utils/validate'
import { getBirthdayByIdCard } from '@/utils/index'
import DictType from '@/utils/dict/DictType'
import AreaCascader from '@/components/Cascader/AreaCascader.vue'
import { findAllIndices } from '@/utils/index'
const initForm = {
  workOrganization:'',
  workPosition:'',
  professionalTitleGrade:'',
  socialService:'',
  researchField:'',
  researchDiscipline:'',
  scientificResearchAchievemen:'',
  honoraryAchievement:'',
  remark:''
}
export default {
  components: {  uploadImage, AreaCascader },
  dicts: [DictType.sys_nation_type,DictType.professional_title_grade,DictType.staff_account_status,DictType.sys_sex,DictType.political_status,DictType.educational_background],
  data(){
    return {
      currentIndex:0,
      activities:[{
        content: '基础信息',
        anchor: 'section1'
      }, {
        content: '专家资质',
        anchor: 'section2'
      },{
        content: '科研荣誉',
        anchor: 'section3'
      },],
      formState:Object.assign({}, initForm),
      loading:false,
      editId:this.$route.query.id,
      options,
      DictType,
      rules: {
        nickName: [
          { required: true, message: '专家姓名不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          { pattern: regex.mobile, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        identificationCard: [
          { validator: validateIdNo, trigger: 'blur', message: '请输入正确的身份证号' }
        ],
      },
      cityOptions: [],
      workExperience: [{
        startTime: '',
        endTime: '',
        workOrganization: ''
      }],
      normaleducation: [
        {
          educationalBackground: '',
          graduateSchool: '',
          profession: '',
          educationalBackgroundType: '1'

        }
      ],
      highestEducation: [
        {
          educationalBackground: '',
          graduateSchool: '',
          profession: '',
          educationalBackgroundType: '2'
        }
      ],
      indices:[]
    }
  },
  created() {
  },
  mounted() {
    if(this.editId) {
      this.getExpertDetailsFn(this.editId)
    }
    const elScrollbar = document.querySelector('.main-container .el-scrollbar__wrap');
    elScrollbar.addEventListener('scroll', this.scrollFn )
    this.scrollToTop()
  },
  watch:{
    /**
     * 身份证号截取出生日期
     * @param val
     */
    'formState.identificationCard': {
      handler(val) {
        if (val) {
          this.formState.birthDate = getBirthdayByIdCard(val)
        }
      }
    }
  },
  methods:{
    /**
     * 初始进入页面跳转到顶部
     */
    scrollToTop() {
      const elScrollbar = document.querySelector('.main-container .el-scrollbar__wrap');
      if (elScrollbar) {
        elScrollbar.scrollTop = 0;
      }
    },
    /**
     * 页面滚动事件
     */
    scrollFn() {
      const  jobDistance =  document.getElementById('section2')?.getBoundingClientRect()?.top
      const  honerDistance =  document.getElementById('section3')?.getBoundingClientRect()?.top
      if(honerDistance <= 20) {
        this.currentIndex = 2
      } else if(jobDistance <= 20 && honerDistance > 20) {
        this.currentIndex = 1
      } else {
        this.currentIndex = 0
      }
      },
    /**
     * 锚点跳转
     */
    handleSteps(val, index) {
      this.currentIndex = index
      const options = {
        behavior: 'smooth',
        inline: 'nearest'
      }
      document.getElementById(val['anchor']).scrollIntoView(options)
    },
    /**
     * 保存
     */
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if(valid){
         if( this.indices.length === 0){
           this.loading = true
           this.clearTrimRow()
           this.formState.workExperience = JSON.stringify(this.workExperience)
           this.formState.education = JSON.stringify([...this.normaleducation,...this.highestEducation])
           const params = {
             ...this.formState
           }
           const  fn = this.editId ? editExpert : addExpert
           fn(params).then(({code,data}) =>{
             if(code === 200){
               this.$message.success('保存成功')
               this.$tab.closeOpenPage({ path: '/system/addExpert' })
               this.$router.push({path:'/system/expert'})
             }else {
               this.$message.error('保存失败')
             }
           }).finally(()=>{
             this.loading = false
           })
         }
        }
      })
    },
    validateDate(voteRule, value, callback) {
      const condition = (item) => item.startTime >= item.endTime;
      this.indices = findAllIndices(this.workExperience.filter(item => item.endTime !== ''), condition)

    },
    handleClearTime(){
      this.validateDate()
    },
    /**
     * 编辑回显
     * @param val
     */
    getExpertDetailsFn(val){
      getExpertDetails(val).then(({data,code})=>{
        if(code === 200){
          this.formState = data
          this.handleEducation(JSON.parse(this.formState.education))
          this.handeleWorkExperience(JSON.parse(this.formState.workExperience))
          this.$nextTick(()=>{
            this.scrollToTop()
          })
        }
      })
    },
    /**
     * 取消
     */
    handleCancel() {
      this.$confirm('信息尚未保存，确认取消?', '提示', {
        confirmButtonText: '继续操作',
        cancelButtonText: '放弃保存',
        type: 'warning'
      }).then(() => {
      }).catch(() => {
        this.$tab.closeOpenPage({ path: '/system/addExpert' })
        this.$router.push({path:'/system/expert'})
      });
    },
    /**
     * 添加工作经历
     */
    handleAddWork(item,index) {
      const flag = !!item.startTime || !!item.endTime || !!item.workOrganization
      if(!flag){
        this.$set(item, 'status', true)
        return false
      }else {
        this.$set(item, 'status', false)
        this.workExperience.push({
          startTime: '',
          endTime: '',
          workOrganization:'',
        })
        return true
      }
    },
    /**
     * 删除工作经历
     */
    handleDeleteWork(index) {
      this.workExperience.splice(index, 1)
    },
    clearTrimRow(){
      if(this.workExperience.length > 1){
        this.workExperience = this.workExperience.filter(item=> !!item.startTime || !!item.endTime || !!item.workOrganization)
        this.workExperience.forEach(item => delete item.status)
      }
      this.workExperience.forEach(item => delete item.status)
    },
    /**
     * 处理回显
     */
    //处理学历
    handleEducation(valArr){
      this.normaleducation =[]
      this.highestEducation =[]
      if(valArr.length > 0  && valArr instanceof Array) {
        valArr.forEach(item=>{
          if(item.educationalBackgroundType === '1'){
            this.normaleducation.push(item)
          }else if(item.educationalBackgroundType === '2'){
            this.highestEducation.push(item)
          }
        })
      }
      if(this.normaleducation.length === 0) {
        this.normaleducation.push({
          educationalBackground: '',
          graduateSchool: '',
          profession: '',
          educationalBackgroundType: '1'
        })
      }
      if(this.highestEducation.length === 0) {
        this.highestEducation.push( {
          educationalBackground: '',
          graduateSchool: '',
          profession: '',
          educationalBackgroundType: '2'
        })
      }

    },
    //处理工作经验
    handeleWorkExperience(valArr){
      this.workExperience = valArr
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-timeline {
  height: 100vh;
  display: flex;
  flex-direction: column;
  position: fixed;
}
::v-deep .el-timeline-item {
  flex: 1;
}
::v-deep tt {
  transform: translateY(0%);
}
</style>
