<template>
   <section class="staffBoxFlex">
       <div class="staffTitle">
           <strong>详细信息</strong>
           <em>
               <i @click="edit" v-if="flag">编辑</i>
               <i @click="save" v-if="!flag">保存</i>
            </em>
       </div>
       <div class="staffContext staffOffice">
          <el-form ref="form" label-position="right" label-width="150px" :rules="dynamicRules" :model="formList">
              <el-row  :gutter="50" >
                  <el-col :span="12">
                      <el-form-item label="性别：" prop="sex">
                         <span v-if="flag">{{formList.sex=='Male'?'男':''}}{{formList.sex=='Female'?'女':''}}</span>
                         <el-select v-model="formList.sex" clearable v-if="!flag">
                             <el-option label="男" value="Male"></el-option>
                             <el-option label="女" value="Female"></el-option>
                         </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="出生日期："  prop="birthdate">
                        <span v-if="flag||userInfo.credential.credentialType=='IdCard'">{{formList.birthdate}}</span> 
                        <el-date-picker
                        v-model="formList.birthdate"
                        type="date"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        clearable
                        placeholder="选择日期"
                        v-if="!flag&&userInfo.credential.credentialType!=='IdCard'"
                        >
                        </el-date-picker>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="民族：" prop="nation">
                          <span v-if="flag">{{formList.nation}}</span>
                         <el-select v-model="formList.nation" clearable v-if="!flag">
                           <el-option v-for="(item,index) in nationArr" :key="index" :label="item.label" :value="item.label"></el-option> 
                         </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="文化程度：" prop="education">
                          <span v-if="flag">{{formList.education}}</span>
                         <el-select v-model="formList.education" clearable v-if="!flag">
                            <el-option v-for="(item,index) in educationArr" :key="index" :label="item.label" :value="item.label"></el-option>                           
                         </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="政治面貌：" prop="politicsStatus">
                         <span v-if="flag">{{formList.politicsStatus}}</span>
                         <el-select v-model="formList.politicsStatus" clearable v-if="!flag">
                             <el-option v-for="(item,index) in politicalStatusArr" :key="index" :label="item.label" :value="item.label"></el-option>                           
                         </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="户籍类型：" prop="householdType">
                          <span v-if="flag">{{formList.householdType}}</span>
                         <el-select v-model="formList.householdType" clearable v-if="!flag">
                             <el-option label="城镇" value="城镇"></el-option>
                              <el-option label="农村" value="农村"></el-option>
                         </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="身高（CM）：" prop="stature">
                          <span v-if="flag">{{formList.stature}}</span>
                         <el-input type="number" v-model="formList.stature" placeholder="请输入" clearable v-if="!flag"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="籍贯：" prop="nativePlace">
                          <span v-if="flag">{{formList.nativePlaceStr}}</span>
                         <el-cascader
                        :options="cityOptions"
                        :props="props"
                        v-model="formList.nativePlace"   
                        clearable   
                        v-if="!flag"              
                        ></el-cascader>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="兵役情况：" prop="militaryStatus">
                          <span v-if="flag">{{formList.militaryStatus}}</span>
                         <el-select v-model="formList.militaryStatus" clearable v-if="!flag">
                             <el-option label="未服" value="未服"></el-option>
                             <el-option label="服过" value="服过"></el-option>
                         </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="婚姻状况：" prop="maritalStatus">
                          <span v-if="flag">{{formList.maritalStatus}}</span>
                         <el-select v-model="formList.maritalStatus" clearable v-if="!flag">
                             <el-option label="未婚" value="未婚"></el-option>
                             <el-option label="已婚" value="已婚"></el-option>
                             <el-option label="离异" value="离异"></el-option>
                             <el-option label="丧偶" value="丧偶"></el-option>
                             <el-option label="其他" value="其他"></el-option>
                         </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="紧急联系人姓名：" prop="emergencyContact">
                          <span v-if="flag">{{formList.emergencyContact}}</span>
                         <el-input  v-model="formList.emergencyContact" placeholder="请输入" clearable v-if="!flag"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="紧急联系人电话：" prop="emergencyPhone">
                          <span v-if="flag">{{formList.emergencyPhone}}</span>
                         <el-input type="number" v-model="formList.emergencyPhone" placeholder="请输入" clearable v-if="!flag"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="驾照等级：" prop="licenseLevel">
                          <span v-if="flag">{{formList.licenseLevel}}</span>
                         <el-select v-model="formList.licenseLevel" clearable v-if="!flag">
                             <el-option label="无" value="无"></el-option>
                             <el-option label="A1" value="A1"></el-option>
                             <el-option label="A2" value="A2"></el-option>
                             <el-option label="A3" value="A3"></el-option>
                             <el-option label="B1" value="B1"></el-option>
                             <el-option label="B2" value="B2"></el-option>
                             <el-option label="C1" value="C1"></el-option>
                             <el-option label="C2" value="C2"></el-option>
                             <el-option label="C3" value="C3"></el-option>
                             <el-option label="C4" value="C4"></el-option>
                             <el-option label="C5" value="C5"></el-option>
                             <el-option label="C6" value="C6"></el-option>
                             <el-option label="D" value="D"></el-option>
                             <el-option label="E" value="E"></el-option>
                             <el-option label="F" value="F"></el-option>
                             <el-option label="M" value="M"></el-option>
                             <el-option label="N" value="N"></el-option>
                             <el-option label="P" value="P"></el-option>
                         </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12" v-if="envTypeFlag">
                      <el-form-item label="疾病史：" prop="diseasesHistory">
                          <span v-if="flag">{{formList.diseasesHistory}}</span>
                         <el-input  v-model="formList.diseasesHistory" placeholder="请输入" clearable v-if="!flag">
                         </el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12" v-if="envTypeFlag">
                      <el-form-item label="从业年限：" prop="workYear">
                          <span v-if="flag">{{formList.workYear}}</span>
                         <el-input type="number" v-model="formList.workYear" placeholder="请输入" clearable v-if="!flag">
                            <template slot="append">年</template>
                         </el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12" v-if="showExtend">
                      <el-form-item label="所属单位：" prop="unitKey">
                          <span v-if="flag">{{formList.unitKey}}</span>
                         <el-input @input="onChange" v-model="formList.unitKey" placeholder="请输入" clearable v-if="!flag">
                         </el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="24">
                      <el-form-item label="现住地址：" prop="placeOfNowStraddress">
                         <span v-if="flag">{{formList.placeOfNowStraddressString}}</span>
                         <el-cascader
                        :options="cityOptions"
                        v-model="formList.placeOfNowStrCity"
                        @change="changeCity" 
                        clearable   
                        v-if="!flag"              
                        ></el-cascader>
                        <el-input v-model="formList.placeOfNowStraddress" placeholder="请输入详细地址" clearable v-if="!flag"></el-input>

                      </el-form-item>
                  </el-col>
                  <el-col :span="12" v-if="showExtend">
                      <el-form-item label="兴趣爱好或擅长技能：" prop="hobbiesKey">
                          <span v-if="flag">{{formList.hobbiesKey}}</span>
                         <el-input @input="onChange" v-model="formList.hobbiesKey" placeholder="请输入" clearable v-if="!flag">
                         </el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12" v-if="showExtend && formList.politicsStatus === '中共党员'">
                      <el-form-item label="所属单位党组织名称：" prop="orgKey">
                          <span v-if="flag">{{formList.orgKey}}</span>
                         <el-input @input="onChange" v-model="formList.orgKey" placeholder="请输入" clearable v-if="!flag">
                         </el-input>
                      </el-form-item>
                  </el-col>
                  
                  <el-col :span="12" v-if="showExtend">
                      <el-form-item label="工作组：" prop="workTeamKey">
                          <span v-if="flag">{{formList.workTeamKey}}</span>
                         <el-select @change="onChange" v-model="formList.workTeamKey" clearable v-if="!flag">
                             <el-option label="情报信息收集" value="情报信息收集" checked disable></el-option>
                             <el-option label="治安巡逻防控" value="治安巡逻防控"></el-option>
                             <el-option label="安全防范管理" value="安全防范管理"></el-option>
                             <el-option label="基础信息采集" value="基础信息采集"></el-option>
                             <el-option label="矛盾纠纷化解" value="矛盾纠纷化解"></el-option>
                             <el-option label="重点人员帮教管控" value="重点人员帮教管控"></el-option>
                             <el-option label="法律教育宣传" value="法律教育宣传"></el-option>
                         </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col v-if="showExtend">
                      <el-form-item label="备注：" prop="remarkKey">
                          <span v-if="flag">{{formList.remarkKey}}</span>
                         <el-input @input="onChange" type="textarea" :rows="3" v-model="formList.remarkKey" placeholder="请输入内容" clearable v-if="!flag">
                         </el-input>
                      </el-form-item>
                  </el-col>
              </el-row>
          </el-form>
       </div>
   </section>
</template>
<script>
// import cityOptions from '@/assets/js/cityData.js'
import {employessBaseInfoApi,staffDetailInfoApi,sassdictListApi,cityOptionsListApi, staffExtendInfoApi} from "@/api/staffApi.js"
export default {
    data(){
        return{
            userInfo:{},
            formList:{},
            cityOptions:[],
            politicalStatusArr:[],
            educationArr:[],
            nationArr:[],
            sexArr:[],
            props:{
                label:'label',
                value:'label'
            },
            flag:true,
            vals:[],
            homeTemplateBoradType:localStorage.getItem('homeTemplateBoradType')||'',
            envTypeFlag: true,//字段默认显示
            showExtend: true,//是否显示扩展信息
            institutionalCode:localStorage.getItem('institutionalCode')||'',//机构类型
        }
    },
    computed:{
        isNoSecurityUser() {
            return this.institutionalCode && !(this.institutionalCode.startsWith('01') || this.institutionalCode.startsWith('02') || this.institutionalCode.startsWith('06'))
        },
        dynamicRules() {
            const isSec = this.isNoSecurityUser;
            return {
                sex:[{required: true, message: '必须填', trigger: "change" }],
                birthdate:[{required: true, message: '必须填', trigger: "change" }],
                nation:[{required: true, message: '必须填', trigger: "change" }],
                education:[{required: !isSec, message: '必须填', trigger: "change" }],
                politicsStatus:[{required: !isSec, message: '必须填', trigger: "change" }],
                stature:[{required: !isSec, message: '必须填', trigger: "change" }],
                nativePlace:[{required: true, message: '必须填', trigger: "change" }],
                militaryStatus:[{required: !isSec, message: '必须填', trigger: "change" }],
                maritalStatus:[{required: !isSec, message: '必须填', trigger: "change" }],
                emergencyContact:[{required: true, message: '必须填', trigger: "change" }],
                emergencyPhone:[{required: true, message: '必须填', trigger: "change" }],               
                placeOfNowStraddress: [{required: !isSec, validator:this.placeOfNow, trigger: "blur" }],        
            }
        }
    },
    mounted(){
       this.employessBaseInfo()
       this.sassdictList()//sass字典表
       this.cityOptionsList()
       this.EnvFlag()//环境判断字段
    },
    methods:{
        EnvFlag(){
            if(this.homeTemplateBoradType=='rtpayTemplate'){//rt环境
                this.envTypeFlag=false
            }
        },
        edit(){
          this.flag=false
        },
        onChange() {
            this.$forceUpdate()
        },
        getExtensionValue(key) {
            const item = this.formList.extensionList?.find(x => x.extensionKey === key);
            return item?.extensionValue || '';
        },
        placeOfNow(rule, value, callback) { 
            console.log(rule)
            console.log(this.formList.placeOfNowStrCity)
            if (!this.isNoSecurityUser) {
                if (!this.formList.placeOfNowStrCity || 
                    (this.formList.placeOfNowStrCity.length == 0 || 
                     this.formList.placeOfNowStrCity[0]=='')) {
                    callback(new Error('影响到相关证件的准确性，请务必填写'));
                } else if (!Boolean(this.formList.placeOfNowStraddress)) {
                    callback(new Error('影响到相关证件的准确性，请务必填写'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        },
        employessBaseInfo(){
            let obj=this.$parent.$parent.staffinfo
            let obj2={domainId:this.$route.query.domainId}
            console.log(this.formList.placeOfNow)
            employessBaseInfoApi(obj,obj2).then(response=>{
                if(response.status==200){
                    this.userInfo=response.data.userInfo
                    this.headPhoto=response.data.userInfo.headPhoto
                    this.formList=JSON.parse(JSON.stringify(response.data.userInfo))
                    if(!Array.isArray(this.formList.nativePlace)){
                      this.formList.nativePlace=this.formList.nativePlace&&this.formList.nativePlace.split(",")
                      this.formList.nativePlaceStr=this.formList.nativePlace&&this.formList.nativePlace.join(",")
                    }
                    if(this.formList.placeOfNow){
                        this.formList.placeOfNowStraddressString=this.formList.placeOfNow.province.name+''+this.formList.placeOfNow.city.name+''+this.formList.placeOfNow.district.name+''+(this.formList.placeOfNow.address?this.formList.placeOfNow.address:'')
                        this.formList.placeOfNowStrCity=[this.formList.placeOfNow.province.code,this.formList.placeOfNow.city.code,this.formList.placeOfNow.district.code]
                        this.$set(this.formList,'placeOfNowStraddress',this.formList.placeOfNow.address)
                        console.log(this.formList.placeOfNowStraddress)
                   }
                   if(this.formList.extensionList.length > 0){
                      this.formList.hobbiesKey = this.getExtensionValue('兴趣爱好或擅长技能');
                      this.formList.orgKey = this.getExtensionValue('所属单位党组织名称');
                      this.formList.unitKey = this.getExtensionValue('所属单位');
                      this.formList.workTeamKey = this.getExtensionValue('工作组');
                      this.formList.remarkKey = this.getExtensionValue('备注');
                    }
                    this.showExtend = this.formList.envRegionCode === "140500"
                }
            })
        },
        sassdictList(){
          sassdictListApi().then(response=>{
               if(response.status==200){
                   console.log(response.data)
                   this.politicalStatusArr=response.data.politicalStatus
                   this.educationArr=response.data.education
                   this.nationArr=response.data.nation
                   this.sexArr=response.data.sex
               }
          })
        },
        cityOptionsList(){
          cityOptionsListApi().then(response=>{
               if(response.status==200){
                   console.log(response.data)
                   this.cityOptions=response.data
               }
          })
        },
         changeCity(val){
            console.log(val)
            this.vals=this.getCascaderObj(val, this.cityOptions);
            console.log(this.vals)
            this.$refs.form.validateField(["placeOfNowStraddress"])//现住地址校验
        },
        getCascaderObj(val,opt) {
            return val.map(function (value) {
                for (var itm of opt) {
                    if (itm.value == value) { opt = itm.children; return itm; }
                }
                return null;
            });
        }, 
        save(){
            let obj=this.userInfo
            if(Array.isArray(this.formList.nativePlace)){
              let str=this.formList.nativePlace.join(",")
              this.$set(this.formList,'nativePlace',str)
            }
            console.log(this.formList.placeOfNow)
            // 地区未选择时给一个默认值
            if(this.vals.length == 0&&this.formList.placeOfNow){
                this.vals.push({value:this.formList.placeOfNow.province.code,label:this.formList.placeOfNow.province.name})
                this.vals.push({value:this.formList.placeOfNow.city.code,label:this.formList.placeOfNow.city.name})
                this.vals.push({value:this.formList.placeOfNow.district.code,label:this.formList.placeOfNow.district.name})
            }
            let extensionParam = [{extensionKey:'所属单位', extensionValue: this.formList.unitKey },
                { extensionKey: '所属单位党组织名称', extensionValue: this.formList.orgKey },
                { extensionKey:'兴趣爱好或擅长技能', extensionValue: this.formList.hobbiesKey },
                { extensionKey:'工作组', extensionValue: this.formList.workTeamKey },
                { extensionKey:'备注', extensionValue: this.formList.remarkKey }
            ]

            this.formList['extensionList'] = extensionParam
            console.log('refs.form', this.$refs.form)
            // 现住地址校验
            this.$refs.form.validate((valid) => {
                console.log(valid)
                if(valid){
                    let placeOfNow={
                        'address':this.formList.placeOfNowStraddress,
                        'province':{'code':this.vals.length&&this.vals[0].value||'','name':this.vals.length&&this.vals[0].label||''},
                        'city':{'code':this.vals.length&&this.vals[1].value||'','name':this.vals.length&&this.vals[1].label||''},
                        'district':{'code':this.vals.length&&this.vals[2].value||'','name':this.vals.length&&this.vals[2].label||''}
                    }
                    console.log(placeOfNow)
                    this.$set(this.formList,'placeOfNow',placeOfNow)
                    console.log('formList', this.formList)
                    if(!this.showExtend) {
                        staffDetailInfoApi(obj,this.formList).then(response=>{
                            if(response.status==200){
                                this.flag=true
                                this.employessBaseInfo()
                            }
                        })
                    } else {
                        Promise.all([
                            staffDetailInfoApi(obj, this.formList),
                            staffExtendInfoApi(obj.id, this.formList)
                        ]).then(([detailResponse, extendResponse]) => {
                            if (detailResponse.status === 200 && extendResponse.status === 200) {
                                this.flag = true;
                                this.employessBaseInfo();
                            } else {
                                console.error('API请求未全部成功', detailResponse, extendResponse);
                            }
                        }).catch(error => {
                            console.error('API请求出错', error);
                        });
                    } 
                }
            })
            
        }
    }
}
</script>
<style lang="scss">
 .staffBoxFlex{
     display: flex;
     flex-direction: column;
     .staffTitle{
         display: flex;
         justify-content: space-between;
         border-bottom: 1px solid #ebebeb;
         padding: 5px 0;
         margin-bottom: 10px;
         strong{
             color: #000;
             font-weight: normal;
         }
         em{
             margin-right:20px;
             i{color: #2e8ad7;margin-right:20px;cursor: pointer;}
         }
     }
     .staffOffice{
        .el-form-item__label{text-align: right;}
     }
     .el-form{
         .el-input{width: 200px;}
     }
 }   
</style>