<template>
  <el-dialog
    v-dialogDrag
    :title="title"
    :visible="dialogFormVisible"
    @close="cancelForm"
    :close-on-click-modal="false"
    class="el-dialog-single"
  >
    <el-form
      label-width="90px"
      :model="formList"
      :rules="rules"
      ref="ruleForm"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="姓名：" prop="name">
            <el-input
              type="text"
              v-model.trim="formList.name"
              placeholder="请输入姓名"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item :label="tellable" prop="telephone">
            <el-input
              type="text"
              v-model.trim="formList.telephone"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item :label="departlabel" prop="departId" >
              <selectTree
                ref="selectTreeParent"
                @getValue="checkChangeParent"
                @selectClickT="selectClickT"
                :curValue="defaulDataParent"
                :data="getTreeDepartlist"     
                :obj="{                  
                    id: 'id',
                    label: 'name',
                    children: 'children',
                }"
                checkStrictly 
                clearable	
                filterable	
                collapseTags	
                ></selectTree>            
          </el-form-item>
        </el-col>
      </el-row>


      <el-row>
        <el-col :span="24">
          <el-form-item label="职业类型：" prop="occupationType">
            <el-select v-model="formList.occupationType" placeholder="请选择职业类型" clearable :disabled="occupationTypeDisabled">
              <el-option v-for="(item,index) in occupationTypeArr" :label="item.label" :value="item.value" :key="index"></el-option>            
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="institutionalCode=='0601'">
        <el-col :span="24">
          <el-form-item label="岗位：" prop="position">
            <el-select v-model="formList.position" placeholder="请选择" clearable>
              <el-option v-for="(item,index) in positionArr" :label="item.label" :value="item.value" :key="index"></el-option>            
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-else-if="institutionalCode.startsWith('04')||institutionalCode.startsWith('07')">
        <el-col :span="24">
          <el-form-item label="岗位：" prop="position" >
            <el-select v-model="formList.position" placeholder="请选择" disabled clearable>
              <el-option v-for="(item,index) in positionArr" :label="item.label" :value="item.value" :key="index"></el-option>            
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item :label="`${$SuperviseStr.entry}日期`" prop="hiredDate">
            <el-date-picker
             v-model.trim="formList.hiredDate"
             type="date"
             format="yyyy-MM-dd"
             value-format="yyyy-MM-dd"
             style="width:100%"
             clearable
             :disabled="disabledhiredDate"
             placeholder="选择日期">
           </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="证件类型：" prop="type">
            <el-select v-model.trim="formList.type" placeholder="请选择证件类型" clearable :disabled="typeDisabled">
              <el-option
              v-for="item in credentialTypesoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="证件号码：" prop="number">
            <el-input
              auto-complete="off"
              v-model.trim="formList.number"
              placeholder="请输入证件号码"
              clearable
            ></el-input>
          </el-form-item>
          <span v-if="formList.type=='PoliceNo'&&institutionalCode=='0601'" class="tipspoliceNo" >请以"BJRK"开头加上编号,如：BJRK20231205</span>
          <!-- <span v-else-if="formList.type=='PoliceNo'&&(institutionalCode.endsWith('07')||institutionalCode.endsWith('08')||institutionalCode.endsWith('09'))" class="tipspoliceNo" >请以"BJRK"开头加上编号,如：BJRK20231205</span> -->
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm()">确 定</el-button>
      <el-button @click="cancelForm()">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import _ from "lodash"
import selectTree from "@/components/SelectTree";
import { AddUserEmplyeeApi } from "@/api/staffApi.js"
export function validatePhone(rule,value,callback){//校验手机号
  setTimeout(() => {
     if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(value)) {
      callback(new Error('请输入正确的手机号'))
    } else {
      callback()
    }
  }, 500);
}
export default {
  inject:['permissions'],
  computed:{
    permissionsStr(){
        return this.permissions()
    },
    isNoSecurityUser() {
      return this.institutionalCode && !(this.institutionalCode.startsWith('01') || this.institutionalCode.startsWith('02') || this.institutionalCode.startsWith('06'))
    }
  },
  props: ["showdialog", 'deptDataList'],
  watch: {
    showdialog() {
      this.dialogFormVisible = this.showdialog;
      this.defaulDataParent=[]
      if(this.showdialog){
         let now=new Date()
         let y=now.getFullYear()
         let m=now.getMonth()+1<10?'0'+(now.getMonth()+1):now.getMonth()+1
         let d=now.getDate()<10?'0'+now.getDate():now.getDate()
         let nowDate=y+'-'+m+'-'+d
         console.log(nowDate)         
         this.$nextTick(()=>{
           this.$set(this.formList,'hiredDate',nowDate) //入职日期默认选择当天
           console.log(this.permissionsStr)
            if(this.permissionsStr&&this.permissionsStr.indexOf('hiredDatedLimited')>-1){//北京地区限制编辑入职时间
              this.disabledhiredDate=true              
            }else{
              this.disabledhiredDate=false
            }
         })
      }
    },
    "formList.departId"(){
      if(this.formList.departId){
        this.$refs.ruleForm.clearValidate(['departId'])//清除验证
      }
    },
    'formList.number'(){
        this.$nextTick(()=>{
          this.formList.number=this.formList.number&&this.formList.number.toUpperCase()
        })
    },
    'formList.position'(){
      this.$nextTick(()=>{
        console.log(this.formList.position)
         if(this.formList.position=='社会力量'){
            this.formList.type='IdCard'
         }else if(this.formList.position=='民警'){
            this.formList.type='PoliceNo'
         }
      })
    },
    deptDataList(v) {
      this.getTreeDepartlist = v
    }
  },
  components: {
    selectTree //注册组件
  },
  data() {
    return {     
      title: `添加${$SuperviseStr.employee}`,
      dialogFormVisible: this.showdialog,
      OperType: 0, //0 新增  1修改
      formList: {
        name:'',
        telephone:'',
        departId:'',
        occupationType:'',
        hiredDate:'',
        type:'',
        number:'',
        position:''
      },
      rules: {
        name: [{required: true, message: "请输入姓名", trigger: "blur" }],
        telephone:[{required: true, message: "请输入手机号", trigger: "blur"},{ validator: validatePhone, trigger:"blur"}],
        departId:[{required: true, message: `请选择所属${$SuperviseStr.depart}`, trigger: "blur"}],
        occupationType:[{required: true, message: "请选择职业类型", trigger: "change"}],
        hiredDate:[{required: true, message: "请选择入职日期", trigger: "blur"}],
        type:[{required: true, message: "请选择证件类型", trigger: "change"}],
        number:[{required: true, message: "请输入证件号码", trigger: "blur"}],
        position:[{required: true, message: "请选择", trigger: "blur"}],
      },
      defaulDataParent:'',//上级部门默认回选数据
      defaulData:[],
      occupationTypeArr:[],
      departlabel:`所属${$SuperviseStr.depart}：`,
      getTreeDepartlist:[],
      homeTemplateBoradType:localStorage.getItem('homeTemplateBoradType')||'',
      tellable:'手机号：',
      disabledhiredDate:false,
      credentialTypesoptions:[//证件类型
          {value:"IdCard",label:"居民身份证/户口簿"},
          {value:"IdCardOfXiangGang",label:"香港特区护照/身份证明"},
          {value:"IdCardOfAoMen",label:"澳门特区护照/身份证明"},
          {value:"IdCardOfTaiwan",label:"台湾居民来往大陆通行证"},
          {value:"Passport",label:"外国护照"},
          {value:"Arms",label:"退伍军人证"},
          {value:"PoliceNo",label:"警号"},
      ],
      credentialTypesoptions_Inst:[//证件类型
          {value:"IdCard",label:"居民身份证/户口簿"},
          {value:"IdCardOfXiangGang",label:"香港特区护照/身份证明"},
          {value:"IdCardOfAoMen",label:"澳门特区护照/身份证明"},
          {value:"IdCardOfTaiwan",label:"台湾居民来往大陆通行证"},
          {value:"Passport",label:"外国护照"},              
      ],
      institutionalCode:localStorage.getItem('institutionalCode')||'',//机构类型
      positionArr:[],
      occupationTypeDisabled:false,
      typeDisabled:false
    };
  },
  mounted(){
    //  if(localStorage.getItem('institutionalCode')=='省级保安监管机构'||localStorage.getItem('institutionalCode')=='市级保安监管机构'||localStorage.getItem('institutionalCode')=='省级保安协会'||localStorage.getItem('institutionalCode')=='市级保安协会'){
    //      this.occupationTypeArr=[{label:'一般职员',value:'Normal'},{label:'保安员',value:'SecurityGuard'},{label:'警官',value:'Police'}]
    //  }
     if(this.homeTemplateBoradType=='rtpayTemplate'){
         this.occupationTypeArr=[{label:'一般职员',value:'Normal'}]
         this.tellable='账号：'
         this.rules.telephone[0].message='请输入账号'
         this.rules.telephone[1].validator=''
         this.rules.type[0].required=false
         this.rules.number[0].required=false
     }else if(localStorage.getItem('appidSupervise')&&JSON.parse(localStorage.getItem('appidSupervise')).appId=='__d1qEDy3wYq8VF5KvUoE'){//监控端--机构用户管理
         this.occupationTypeArr=[{label:'一般职员',value:'Normal'},{label:'保安员',value:'SecurityGuard'},{label:'警官',value:'Police'}]
         this.tellable='手机号：'
         this.rules.telephone[0].message='请输入手机号'
        //  this.rules.telephone[1].validator=''     
     }else if (this.isNoSecurityUser) {
        this.occupationTypeArr=[{label:'一般职员',value:'Normal'}]
        this.occupationTypeDisabled=true
        this.$set(this.formList,'occupationType','Normal')
         
     }
     else{
         this.occupationTypeArr=[{label:'一般职员',value:'Normal'},{label:'保安员',value:'SecurityGuard'}]
     }
     
     this.EnvFlag()//环境判断字段
  },
  methods: {   
    EnvFlag(){      
      switch(this.institutionalCode){
            case '0102'://保安服务公司          
            this.credentialTypesoptions=this.credentialTypesoptions_Inst
            break;         
            case '0103'://保安培训单位,保安培训机构          
            this.credentialTypesoptions=this.credentialTypesoptions_Inst
            break;
            case '0104'://自行招用保安员单位         
            this.credentialTypesoptions=this.credentialTypesoptions_Inst
            break;  
            case '0601':
            this.occupationTypeDisabled=true  
            this.formList.occupationType='Normal'
            this.typeDisabled=true
            this.positionArr=[
              {value:"社会力量",label:"社会力量"},
              {value:"民警",label:"民警"}
            ]
            break;            
            default:
            if(this.institutionalCode.startsWith('04')){
              this.occupationTypeDisabled=true  
              this.formList.occupationType='Normal'
              this.typeDisabled=true
              this.positionArr=[
                {value:"保卫管理员",label:"保卫管理员"}
              ]
              this.formList.position='保卫管理员'
              this.formList.type='IdCard'
            }
            else if(this.institutionalCode.startsWith('02')){
                this.occupationTypeDisabled=true;
                this.formList.occupationType='Normal';
            }
            else if(this.institutionalCode.startsWith('07')){
              this.occupationTypeDisabled=true  
              this.formList.occupationType='Normal'
              this.typeDisabled=true
              this.positionArr=[
                {value:"保卫管理员",label:"保卫管理员"}
              ]
              this.formList.position='保卫管理员'
              this.formList.type='IdCard'
            }
            else if(this.institutionalCode.endsWith('07')||this.institutionalCode.endsWith('08')||this.institutionalCode.endsWith('09')){
              this.occupationTypeDisabled=true  
              this.formList.occupationType='Normal'
              this.typeDisabled=true
              this.formList.type='PoliceNo'
            }  
      }
    },
    selectClickT(val){
       this.getTreeDepartlist=val
    },  
    getTableRow(data, type) {       
      let newRowData = JSON.parse(JSON.stringify(data)); //拷贝一份存储对象
      this.formList = newRowData; //拷贝一份存储对象引用不同地址
      this.OperType = type;  
      this.getTreeData(this.getTreeDepartlist)
    },
    checkChangeParent(key, data) {//selectTree组件-复选框选中的数据
        console.log(key)
        console.log(data)
        this.$set(this.formList,"departId",key)
        console.log(this.formList.departId)
    },
    checkChange(key, data) {//selectTree组件-复选框选中的数据
        // console.log(key)
        // console.log(data)
        // this.$set(this.formList,"allowedDepartIds",key)
    },
    getTreeData(arr){//递归遍历部门
        arr.forEach(item=>{
             item.label=item.name;
             item.value=item.id;
             if(item.children&&item.children.length<1){
                 item.children=undefined
             }else if(item.children&&item.children.length>0){
               this.getTreeData(item.children)  
             }
         })
    },   
     //_.debounce防止重复点击
    submitForm:_.debounce(function(){  
      
        //逻辑代码
      let credential={
        number:this.formList.number,
        type:this.formList.type
      }
      this.$set(this.formList,'credential',credential)
      
      let obj2={domainId:this.$route.query.domainId}     
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {          
            AddUserEmplyeeApi(this.formList,obj2).then((response) => {
              //新增
              if(response.status==200) {
                let newobj = JSON.parse(JSON.stringify(this.formList));
                this.$emit("refurlist", newobj); //确定后发送$emit绑定父数据
                this.cancelForm();
              }
            }).catch((error) => {
              console.log('errorerrorerrorerror', error);
              if(error.code==1000601) { //提醒确认入职
                  this.$confirm('该人员为从业异常人员，是否确认录用！', "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  }).then(() => {
                    this.formList.abnormalPersonnelConfirm = true
                    AddUserEmplyeeApi(this.formList,obj2).then((response) => {
                      if (response.status==200) {
                        let newobj = JSON.parse(JSON.stringify(this.formList));
                        this.$emit("refurlist", newobj); //确定后发送$emit绑定父数据
                        this.cancelForm();
                      }
                    })
                  });
                } else if (error.code==1000602) { //限制入职
                  this.$confirm('该人员不符合担任保安员，无法录入系统！', "提示", {
                    cancelButtonText: "取消",
                    type: "warning",
                    showCancelButton: true,
                    showConfirmButton: false
                  })
                } 
            });                 
        } else {
          return false;
        }
      });
    },1000,{'leading':true,'trailing':false}),    
    cancelForm() {
      //取消关闭
      this.$emit("update:showdialog", false);
      this.$nextTick(function () {
        this.$refs.ruleForm.resetFields(); //重置输入框提示
      });
    },
  },
};
</script>
<style lang="scss">
// .el-dialog-single{
//   .el-form-item{
//     display: flex;
//     flex-direction: column;
//     .el-form-item__content{margin-left:20px!important;}
//   }
// }
.elradioLineheight{
    margin-top:5px; 
  .el-radio{display: block; line-height: 30px;}
}
.tipspoliceNo{
  display: flex;
  color: red;
  margin-top: 0px;
  margin-left: 20px;
}
</style>