<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="ruleForm" :model="formList" :rules="rules" label-position="right" label-width="100px">
            <el-row  :gutter="50" v-if="institutionalCode=='0601'">
                  <el-col :span="12">
                      <el-form-item :label="departlabel" prop="departId">                 
                         <selectTree
                            ref="selectTreeParent"
                            @getValue="checkChangeParent"
                            :curValue="defaulDataParent"
                            :data="getTreeDepartlist"     
                            :obj="{                  
                                id: 'id',
                                label: 'name',
                                children: 'children',
                            }"
                            checkStrictly 
                            clearable	
                            filterable	
                            multiple
                            collapseTags
                            v-if='!flag'	
                          ></selectTree>  
                        <el-tooltip :content="departName" placement="top" v-if='flag'>
                          <span class="departNameClass">{{departName}}</span>
                        </el-tooltip>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="职业类型：">
                         <span>
                             {{formList.occupationType=='Normal'?'一般职员':''}}
                             {{formList.occupationType=='SecurityGuard'?'保安员':''}}
                             {{formList.occupationType=='Police'?'警官':''}}
                         </span>                  
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="上级：" prop="superiorId">
                         <span v-if="flag">{{formList.superiorName}}</span>
                         <el-select v-model="formList.superiorId" filterable :filter-method="filterMethod"  @change="selectUser" placeholder="请选择" clearable v-if="!flag">
                            <el-option
                                v-for="item in tableDataEmployee"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                         </el-select>   
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="岗位：" prop="position">
                         <span>{{formList.position}}</span>
                         <!-- <span v-if="!flag"><el-input v-model="formList.position" placeholder="请输入"/></span> -->
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item :label="`${$SuperviseStr.entry}时间：`" prop="hiredDate">
                         <span v-if="flag">{{formList.hiredDate}}</span>
                         <span v-if="!flag">
                             <el-date-picker
                            v-model="formList.hiredDate"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            clearable
                            @change="hiredDateChange"
                            placeholder="选择日期"  
                            :disabled='disabledhiredDate'                          
                            >
                            </el-date-picker>
                         </span>
                      </el-form-item>
                  </el-col>                  
                  <el-col :span="12">
                      <el-form-item label="司龄：" prop="siling">
                         <span>{{formList.siling}}</span>
                      </el-form-item>
                  </el-col>
              </el-row>
              <el-row  :gutter="50" v-else-if="institutionalCode.endsWith('07')||institutionalCode.endsWith('08')||institutionalCode.endsWith('09')">
                  <el-col :span="12">
                      <el-form-item :label="departlabel" prop="departId">                 
                         <selectTree
                            ref="selectTreeParent"
                            @getValue="checkChangeParent"
                            :curValue="defaulDataParent"
                            :data="getTreeDepartlist"     
                            :obj="{                  
                                id: 'id',
                                label: 'name',
                                children: 'children',
                            }"
                            checkStrictly 
                            clearable	
                            filterable	
                            multiple
                            collapseTags
                            v-if='!flag'	
                          ></selectTree>  
                        <el-tooltip :content="departName" placement="top" v-if='flag'>
                          <span class="departNameClass">{{departName}}</span>
                        </el-tooltip>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="职业类型：">
                         <span>
                             {{formList.occupationType=='Normal'?'一般职员':''}}
                             {{formList.occupationType=='SecurityGuard'?'保安员':''}}
                             {{formList.occupationType=='Police'?'警官':''}}
                         </span>                  
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="上级：" prop="superiorId">
                         <span v-if="flag">{{formList.superiorName}}</span>
                         <el-select v-model="formList.superiorId" filterable :filter-method="filterMethod"  @change="selectUser" placeholder="请选择" clearable v-if="!flag">
                            <el-option
                                v-for="item in tableDataEmployee"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                         </el-select>   
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="职位：" prop="position">
                         <span v-if="flag">{{formList.position}}</span>
                         <span v-if="!flag"><el-input v-model="formList.position" placeholder="请输入"/></span>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item :label="`${$SuperviseStr.entry}时间：`" prop="hiredDate">
                         <span v-if="flag">{{formList.hiredDate}}</span>
                         <span v-if="!flag">
                             <el-date-picker
                            v-model="formList.hiredDate"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            clearable
                            @change="hiredDateChange"
                            placeholder="选择日期"  
                            :disabled='disabledhiredDate'                          
                            >
                            </el-date-picker>
                         </span>
                      </el-form-item>
                  </el-col>                  
                  <el-col :span="12">
                      <el-form-item label="司龄：" prop="siling">
                         <span>{{formList.siling}}</span>
                      </el-form-item>
                  </el-col>
              </el-row>
              <el-row  :gutter="50" v-else>
                  <el-col :span="12">
                      <el-form-item :label="departlabel" prop="departId">                 
                         <selectTree
                            ref="selectTreeParent"
                            @getValue="checkChangeParent"
                            :curValue="defaulDataParent"
                            :data="getTreeDepartlist"     
                            :obj="{                  
                                id: 'id',
                                label: 'name',
                                children: 'children',
                            }"
                            checkStrictly 
                            clearable	
                            filterable	
                            multiple
                            collapseTags
                            v-if='!flag'	
                          ></selectTree>  
                        <el-tooltip :content="departName" placement="top" v-if='flag'>
                          <span class="departNameClass">{{departName}}</span>
                        </el-tooltip>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="职业类型：">
                         <span>
                             {{formList.occupationType=='Normal'?'一般职员':''}}
                             {{formList.occupationType=='SecurityGuard'?'保安员':''}}
                             {{formList.occupationType=='Police'?'警官':''}}
                         </span>                  
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="上级：" prop="superiorId">
                         <span v-if="flag">{{formList.superiorName}}</span>
                         <el-select v-model="formList.superiorId" filterable :filter-method="filterMethod"  @change="selectUser" placeholder="请选择" clearable v-if="!flag">
                            <el-option
                                v-for="item in tableDataEmployee"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                         </el-select>   
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="职位：" prop="position">
                         <span v-if="flag">{{formList.position}}</span>
                         <span v-if="!flag"><el-input v-model="formList.position" placeholder="请输入"/></span>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item :label="`${$SuperviseStr.entry}时间：`" prop="hiredDate">
                         <span v-if="flag">{{formList.hiredDate}}</span>
                         <span v-if="!flag">
                             <el-date-picker
                            v-model="formList.hiredDate"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            clearable
                            @change="hiredDateChange"
                            placeholder="选择日期"  
                            :disabled='disabledhiredDate'                          
                            >
                            </el-date-picker>
                         </span>
                      </el-form-item>
                  </el-col>                  
                  <el-col :span="12">
                      <el-form-item label="司龄：" prop="siling">
                         <span>{{formList.siling}}</span>
                      </el-form-item>
                  </el-col>

                  <el-col :span="12">
                      <el-form-item label="员工状态：" prop="personStatus">
                         <span v-if="flag">{{formList.personStatus=='FullTime'?'全职':''}}{{formList.personStatus=='PartTime'?'兼职':''}}{{formList.personStatus=='Probation'?'试用':''}}{{formList.personStatus=='Internship'?'实习':''}}</span>
                         <el-select v-model="formList.personStatus" clearable v-if="!flag">
                             <el-option label="全职" value="FullTime"></el-option>
                             <el-option label="兼职" value="PartTime"></el-option>
                             <el-option label="试用" value="Probation"></el-option>
                             <el-option label="实习" value="Internship"></el-option>
                         </el-select>
                      </el-form-item>
                  </el-col>

                  <el-col :span="12">
                      <el-form-item label="试用期：" prop="probation">
                         <span v-if="flag"><em v-if="formList.probation">{{formList.probation}}个月</em></span>
                         <el-input type="number" placeholder="请输入" v-model.number="formList.probation"  v-if="!flag">
                            <template slot="append">个月</template>
                        </el-input>
                      </el-form-item>
                  </el-col>

                  <el-col :span="12">
                      <el-form-item label="原定转正日期：" prop="planPositiveDate">
                         <span v-if="flag">{{formList.planPositiveDate}}</span>
                         <span v-if="!flag">
                             <el-date-picker
                            v-model="formList.planPositiveDate"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            clearable
                            placeholder="选择日期"                            
                            >
                            </el-date-picker>
                         </span>
                      </el-form-item>
                  </el-col>     

                  <el-col :span="12">
                      <el-form-item label="转正日期：" prop="positiveDate">
                         <span v-if="flag">{{formList.positiveDate}}</span>
                         <span v-if="!flag">
                             <el-date-picker
                            v-model="formList.positiveDate"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            clearable
                            placeholder="选择日期">
                            </el-date-picker>
                         </span>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="面谈记录：" prop="interview">
                         <span v-if="flag"><em v-if="formList.interview"><b v-for="(item,index) in formList.interviewArr" :key='index' @click='download(item)'>{{item.name}}</b></em></span>
                         <el-upload
                            class="upload-demo"
                            ref='upload'
                            action=""
                            :http-request='uploadImg'
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :before-remove="beforeRemove"
                            :on-exceed="handleExceed"
                            :file-list="formList.fileList"
                            :limit='1'
                            v-if="!flag"
                            >
                            <el-button size="small" :disabled='disabled'>上传文件</el-button>
                        </el-upload>
                      </el-form-item>
                  </el-col>

                  <el-col :span="12">
                      <el-form-item label="薪资：" prop="salary">
                        <span v-if="flag"><em v-if="formList.salary">{{formList.salary}}元</em></span>
                         <el-input type="number" placeholder="请输入" v-model.number="formList.salary"  v-if="!flag">
                            <template slot="append">元</template>
                        </el-input>
                      </el-form-item>
                  </el-col>
              </el-row>
          </el-form>
       </div>
   </section>
</template>
<script>
import {StaffDepartmentListApi,employessBaseInfoApi,employeeTableListApi,staffOfficeInfoApi,commonFileUploadApi} from "@/api/staffApi.js"
import selectTree from "@/components/SelectTree";
import {getNowFormatDate,diffDate} from "@/utils/global.js"
export default {
    inject:['permissions'],
    computed:{
        permissionsStr(){
            return this.permissions()
        }
    },
    data(){
        return{
            // userInfo:{},
            // officeInfo:{},
            tableDataEmployee:[],
            formList:{},
            params:{//搜索条件
                pageIndex:1,
                pageSize:999999,
                keyword:'',             
                total:0
            },
            defaulDataParent:'',//上级部门默认回选数据
            getTreeDepartlist:[],
            rules: {
                 departId: [{required: true, message: `请选择所属${$SuperviseStr.depart}`, trigger: "blur" }],        
                 hiredDate: [{required: true, message: `请选择${$SuperviseStr.entry}时间`, trigger: "blur" }],        
            },
            flag:true,
            departlabel:`所属${$SuperviseStr.depart}：`,
            depCheckboxDisabled:true,//默认查看为禁用复选框
            departName:'',
            path:'',
            disabled:false,
            disabledhiredDate:false,
            institutionalCode:localStorage.getItem('institutionalCode'),//机构类型
        }
    },
    components:{
        selectTree, //注册组件
    },
    mounted(){
      this.tableDatalist()//部门列表
    //   this.employessBaseInfo()
      this.employeeTableList()
    },
    methods:{
        selectClickT(val){            
            if(this.flag){
               this.depCheckboxDisabled=true
            }else{
               this.depCheckboxDisabled=false 
            }
            this.sortTableDataT(val)
            this.getTreeDepartlist=val
        }, 
        sortTableDataT(arr){//查看状态禁用复选框，编辑状态启用复选框--递归排序
            if(arr.length){
                arr.forEach(item=>{
                    item.siling=""
                    item.displayOrderNumber=item.displayOrder                    
                    item.disabled=this.depCheckboxDisabled //true禁用复选框，false启用
                    if(item.children.length){
                        this.sortTableDataT(item.children)
                    }                    
                })
            }          
            console.log(this.getTreeDepartlist)
        },
        edit(){
          this.flag=false
          if(this.permissionsStr&&this.permissionsStr.indexOf('hiredDatedLimited')>-1){//北京地区限制编辑入职时间
                this.disabledhiredDate=true              
          }else{
                this.disabledhiredDate=false
          }
         //this.$set(this.formList,"superiorId",null)
        },
        tableDatalist(){//部门列表-表格列表
            let obj={domainId:this.$route.query.domainId}//获取url域domainId
            StaffDepartmentListApi(obj).then(response=>{
               if(response.data){
                 this.getTreeDepartlist=response.data
                 this.sortTableData(this.getTreeDepartlist)
                 this.employessBaseInfo()//查询多部门--先查询部门在查询信息列表，不然会出现部门显示id字段
                 
               }
            })
        },
        sortTableData(arr){//递归排序
            if(arr.length){
                arr.forEach(item=>{
                    item.siling=""
                    item.displayOrderNumber=item.displayOrder
                    if(item.children.length){
                        this.sortTableData(item.children)
                    }                    
                })
            }
            console.log(this.getTreeDepartlist)
        },
        checkChangeParent(key, data) {//selectTree组件-复选框选中的数据
            console.log(key)
            console.log(data)
            this.$set(this.formList,"departId",key)
            console.log(this.formList.departId)
       },
       hiredDateChange(){
        if(this.formList.hiredDate>getNowFormatDate()){
            this.$message({type:'warning',message:`${$SuperviseStr.entry}时间不能大于当前时间`})
            this.formList.hiredDate=""
            return
        }   
        if(this.formList.hiredDate){
              this.formList.siling=diffDate(this.formList.hiredDate,getNowFormatDate())
              this.$forceUpdate();
          }
       },
       employessBaseInfo(){
            let obj=this.$parent.$parent.staffinfo
            let obj2={domainId:this.$route.query.domainId}
            employessBaseInfoApi(obj,obj2).then(response=>{
                if(response.status==200){
                    this.formList=JSON.parse(JSON.stringify(response.data))
                    this.formList.siling=diffDate(this.formList.hiredDate,getNowFormatDate())
                    let arr=[]
                    let departName=''
                    if(response.data.departs.length){
                        response.data.departs.forEach(its=>{
                            arr.push(its.departId)
                            departName+=its.departName+','
                        })
                    }
                    if(this.formList.interview){
                        this.formList.interviewArr=JSON.parse(this.formList.interview)
                        this.formList.fileList=this.formList.interviewArr
                        this.disabled=true
                    }
                    this.departName=departName&&departName.substring(0,departName.length-1)
                    this.defaulDataParent=arr                   
                }
            })
        },
        employeeTableList(){//列表表格-查询结果
            let obj2={domainId:this.$route.query.domainId}
            employeeTableListApi(this.params,obj2).then(response=>{
                if(response.data.data){
                    this.tableDataEmployee=response.data.data
                    this.params.total=response.data.total
                }
            })
        }, 
        filterMethod(val){//输入框过滤搜索
            console.log(val)//输入框关键词名称
            this.params.keyword=val
            let obj2={domainId:this.$route.query.domainId}
            employeeTableListApi(this.params,obj2).then(response=>{
                if(response.data.data){
                    this.tableDataEmployee=response.data.data
                    this.params.total=response.data.total
                }
            })
        },  
        selectUser(val){//查询下拉框id对应的名称数组
            console.log(val)
            console.log(this.tableDataEmployee)           
        },
        uploadImg(e){//文件上传  
            console.log(e)
            console.log(this.formList.fileList) 
            if(this.formList.fileList&&this.formList.fileList.length){
                this.$message({type:'warning',message:'重新上传请先删除旧文件'})
                return
            }    
            else if(__network__){
                this.obsFile(e)//obs文件上传
                return
            }else{
                this.InFileUpload(e)//内网文件上传   
            } 
        }, 
        obsFile(e) {//obs文件上传
            console.log(e)
            let imgSize = Number(e.file.size / 1024 / 1024);
            if (imgSize > 100) {
                this.$message.error('上传文件大小不能超过 100MB!');
                this.$refs.upload.clearFiles()
                return
            }
            var that = this;
            var domainId = this.$route.query.domainId || "default"//保存本地企业id
            // var objectKey="uploads/"+domainId+"/"+new Date().getFullYear()+"/"+new Date().getTime()+e.file.name	
            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 md = m + '-' + d
            var objectKey = `uploads/${y}/${md}/${domainId}/${now.getTime()}/${e.file.name}`

            var obs = new ObsClient({
                access_key_id: ak,
                secret_access_key: sk,
                server: urlserver,
                timeout: 60 * 5,
            });
            obs.putObject({
                Bucket: BucketName,
                Key: objectKey,
                SourceFile: e.file //获取file文件
            }).then(function (result) {
                console.log(result)

                if (result.CommonMsg.Status < 300) {
                    that.$message({ type: 'success', message: "上传成功" })
                    console.log('Create object:' + objectKey + ' successfully!\n');
                    var httpurl = `https://${BucketName}.${urlserver}/${objectKey}`
                    httpurl = convertCdnPath(httpurl);
                    that.path = httpurl
                    that.formList.fileList = [{ name: e.file.name, url: httpurl }]
                    if (that.path) {//上传文件成功启用
                        that.disabled = true
                    }
                }
            });
        },
        InFileUpload(e){//内网文件上传  
            console.log(e.file)
            let imgSize = Number(e.file.size / 1024 / 1024);
            if(imgSize>100){
                this.$message.error('上传文件大小不能超过 100MB!');
                this.$refs.upload.clearFiles()
                return
            }
            let fd=new FormData()
            fd.append("file",e.file)   
            commonFileUploadApi(fd).then(response=>{
                let blobReader = new Response(response).json();
                blobReader.then((res) => {
                console.log(res.data)
                if(res.data){
                    this.path=window.location.origin+"/obpm"+res.data
                    this.formList.fileList=[{name:e.file.name,url:this.path}]
                    this.disabled=true
                }
                })
            })
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);            
        },
        handlePreview(file) {
           console.log(file);
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制只能上传一个文件,如要重新上传,先删除旧文件`);
        },
        beforeRemove(file, fileList) {
            console.log(file)
            console.log(fileList)
            let p=new Promise((resolve,reject)=>{
                  this.$confirm(`确定移除 ${ file.name }？`).then(()=>{
                  this.formList.fileList=[]
                  this.disabled=false
                  resolve(true)
                }).catch(()=>{
                    this.disabled=true
                    reject(false)
                })
            })
            return p
        },       
        download(item){
           if(item.url){
               window.open(item.url)
           }
        },
        save(){
            console.log(this.formList)
            let obj=this.$parent.$parent.staffinfo
            let obj2={domainId:this.$route.query.domainId}
            this.$refs.ruleForm.validate((valid) => {
             if (valid) {
                staffOfficeInfoApi(obj,obj2,this.formList).then(response=>{
                    if(response.status==200){
                      this.flag=true
                      this.employessBaseInfo()
                      this.employeeTableList()
                    }
                })
             }
            })
        }
    }
}
</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;}
     }
     .departNameClass{width: 90%; white-space: nowrap;overflow: hidden;text-overflow: ellipsis;display: block;}
 }   
</style>