<template>
<section>
  <el-dialog
    v-dialogDrag
    :title="title"
    :visible="dialogFormVisible"
    @close="cancelForm"
    :close-on-click-modal="false"
    class="el-dialog-single el-dialog-contract"
  >
    <el-form
      label-width="300px"
      :model="formList"
      :rules="rules"
      ref="ruleForm"
    > 

      <el-row>
        <el-col :span="24">
          <el-form-item label="选择用户：" prop="employeeId" v-if="OperType==0">
            <el-select v-model="formList.employeeId" filterable :filter-method="filterMethod" :disabled="disabledUser"  @change="selectUser" @remove-tag="removetag" placeholder="请输入或者选择" >
              <el-option
                v-for="item in tableDataEmployee"
                :key="item.id"
                :label="item.name+' ('+item.telephone+')'+' ('+item.departName+')'"
                :value="item.id">
              </el-option>
            </el-select> 
          </el-form-item>
          <el-form-item label="选择用户：" v-if="OperType!=0">        
            <el-input v-model="formList.employeeName" disabled ></el-input>           
          </el-form-item>
        </el-col>
      </el-row>


      <el-row v-if="flag">
        <el-col :span="24">
          <el-form-item label="合同名称：" prop="name">
            <el-input
              auto-complete="off"
              v-model="formList.name"
              placeholder="请输入合同名称"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row> 

      <el-row v-if="flag">
        <el-col :span="24">
          <el-form-item label="甲方名称：" prop="aName">
            <el-input
              auto-complete="off"
              v-model="formList.aName"
              placeholder="请输入甲方名称"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row v-if="flag">
        <el-col :span="24">
          <el-form-item label="乙方名称：" prop="bName">
            <el-input
              auto-complete="off"
              v-model="formList.bName"
              placeholder="请输入乙方名称"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

   

      <el-row v-if="flag">
        <el-col :span="24">
          <el-form-item label="合同开始日期：" prop="beginDate">
            <el-date-picker
             v-model="formList.beginDate"
             type="date"
             format="yyyy-MM-dd"
             value-format="yyyy-MM-dd"
             style="width:100%"
             clearable
             placeholder="选择日期">
           </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="flag">
        <el-col :span="24" class="elcolEndDate">
          <el-form-item label="合同结束日期：" prop="endDate">
            <el-date-picker
             v-model="formList.endDate"
             type="date"
             format="yyyy-MM-dd"
             value-format="yyyy-MM-dd"
             style="width:100%"
             clearable
             :disabled="formList.disabledEndDate"
             placeholder="选择日期">
           </el-date-picker>
          </el-form-item>
          <span class="checkbox"><el-checkbox v-model="formList.dateLimitless" @change="checkEndDate">为无期限合同</el-checkbox></span>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="电子合同文件：" prop="attachment">
              <el-upload
                class="upload-demo"
                action=""
                :http-request='uploadImg'
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-exceed="handleExceed"
                :file-list="fileList"
                :show-file-list='true'>
                <el-button size="small" icon="el-icon-upload2">上传文件</el-button>
              </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

     

      <el-row>
        <el-col :span="24">
          <el-form-item label="备注：" prop="note">
            <el-input
              type="textarea"
              auto-complete="off"
              v-model="formList.note"
              placeholder="请输入备注"
              clearable
            ></el-input>
          </el-form-item>
        </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>

  <MoveSuperDialog :showdialogMoveSuper.sync="showdialogMoveSuper" :getTreeDepartlist="getTreeDepartlist" @refurlist="refurlist" ref="popChildrenMoveSuper"></MoveSuperDialog>

</section>  
</template>
<script>
import _ from "lodash"
import selectTree from "@/components/SelectTree";
import MoveSuperDialog from './MoveSuperDialog.vue'
import { employeeTableListApi,AddContractApi,EditContractApi,commonFileUploadApi } from "@/api/staffApi.js"
export function validatePhone(rule,value,callback){//校验手机号
  setTimeout(() => {
     if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(value)) {
      callback(new Error('请输入正确的手机号'))
    } else {
      callback()
    }
  }, 500);
}
export default {
  props: ["showdialog", "getTreeDepartlist"],
  watch: {
    showdialog() {
      this.dialogFormVisible = this.showdialog;
      this.defaulDataParent=[]
    },
    "formList.attachment"(){
       if(this.formList.attachment){
            this.$nextTick(()=>{
            this.$refs.ruleForm.clearValidate(['attachment']); //清空提示
            })
       }
    }
  },
  components: {
    selectTree, //注册组件
    MoveSuperDialog
  },
  data() {
    return {     
      title: "",
      dialogFormVisible: this.showdialog,
      OperType: 0, //0 新增  1修改
      formList: {},
      params:{//搜索条件
        pageIndex:1,
        pageSize:10,
        keyword:'',             
        total:0
      },
      rules: {
        employeeId: [{required: true, message: "请选择用户", trigger: "change" }],
        name:[{required: true, message: "请输入合同名称", trigger: "blur"}],
        aName:[{required: true, message: "请输入甲方名称", trigger: "blur"}],
        bName:[{required: true, message: "请输入乙方名称", trigger: "blur"}],
        beginDate:[{required: true, message: "请选择合同开始日期", trigger: "blur"}],
        endDate:[{required: true, message: "请选择合同结束日期", trigger: "blur"}],
        attachment:[{required: true, message: "请上传电子合同文件", trigger: "blur"}],
      },
      defaulDataParent:'',//上级部门默认回选数据
      defaulData:[],
      tableDataEmployee:[],
      resultArr:[],//选择用户下拉得到对应名称数组
      showdialogMoveSuper:false,
      fileList:[],
      disabledUser:false,
      flag:true,
    };
  },
  methods: {     
    getTableRow(data, type,flag) {       
      let newRowData = JSON.parse(JSON.stringify(data)); //拷贝一份存储对象
      this.formList = newRowData; //拷贝一份存储对象引用不同地址
      this.OperType = type;  
      if(this.OperType===0){
         this.title="添加合同"
         this.disabledUser=false
         this.flag=true
         this.fileList=[]
         this.$set(this.formList,'aName',localStorage.getItem("domainName")||"")
         this.$set(this.formList,"dateLimitless",false)
         this.$set(this.formList,"disabledEndDate",false) 
      }else if(flag==2){//2代表上传
         this.title="上传合同"
         this.disabledUser=true
         this.flag=false
         this.fileList=[]
         this.formList.attachment=""
          if(this.formList.beginDateDesc){
           this.$set(this.formList,"beginDate",this.formList.beginDateDesc)
         }

         if(this.formList.endDateDesc){
           this.$set(this.formList,"endDate",this.formList.endDateDesc)
         }

         if(this.formList.attachment){       
            let obj={}
            obj.name=this.formList.fileName
            obj.url=this.formList.attachment
            this.fileList=[obj]
         }

         if(this.formList.dateLimitless==true){//编辑如果为无期限合同 禁用结束时间
             this.$set(this.formList,"disabledEndDate",true)
             this.$set(this.formList,"endDate","9999-12-31")
             this.rules.endDate[0].required=false
         }else{
           this.$set(this.formList,"dateLimitless",false)
           this.rules.endDate[0].required=true
         }
      }else{
         this.title="编辑合同"
         this.disabledUser=true
         this.flag=true
         if(this.formList.beginDateDesc){
           this.$set(this.formList,"beginDate",this.formList.beginDateDesc)
         }

         if(this.formList.endDateDesc){
           this.$set(this.formList,"endDate",this.formList.endDateDesc)
         }

         if(this.formList.attachment){
            let obj={}
            obj.name=this.formList.fileName
            obj.url=this.formList.attachment
            this.fileList=[obj]
         }

         if(this.formList.dateLimitless==true){//编辑如果为无期限合同 禁用结束时间
             this.$set(this.formList,"disabledEndDate",true)
             this.$set(this.formList,"endDate","9999-12-31")
             this.rules.endDate[0].required=false
         }else{
           this.$set(this.formList,"dateLimitless",false)
           this.rules.endDate[0].required=true
         }
      }
      this.getTreeData(this.getTreeDepartlist)
      this.employeeTableList()//员工列表
    },    
    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)  
             }
         })
    },   
    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)
        let resultArr=[]
        resultArr=this.tableDataEmployee.filter(item=>{
           return val.indexOf(item.id)>-1
        })
        resultArr.forEach(its=>{
          this.resultArr.push(its)
        })
        let resultArr2=this.resultArr.filter(item=>{
           return val.indexOf(item.id)>-1
        })
        this.resultArr=resultArr2
        this.resultArr=[...new Set(this.resultArr)]
         console.log(this.resultArr)
        this.$set(this.formList,"name",this.resultArr[0].name+"的劳动合同")
        this.$set(this.formList,"bName",this.resultArr[0].name)        
    },
    
    removetag(val){
      console.log(val)
      this.resultArr.forEach(item=>{
        if(item.id==val){
          this.resultArr.splice(item,1)
        }
      })
       console.log(this.resultArr)
    },
    uploadImg(e){//文件上传
       if(__network__){
           this.obsFile(e)//obs文件上传
			     return
		   }else{
         this.InFileUpload(e)//内网文件上传   
       }
    }, 
    obsFile(e){//obs文件上传
	    console.log(e)
		  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.$set(that.formList,"attachment",httpurl)	
          let obj={}
          obj.name=e.file.name
          obj.url=httpurl
          that.fileList=[obj]
          if(that.path){//上传文件成功启用
            that.disabled=false
          }
				}
			});
	  },
    InFileUpload(e){//内网文件上传  
      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.disabled=false
          }
        })
      })
    },
    handleRemove(file, fileList) {
        console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    checkEndDate(val){//为无期限合同
       if(val){
         this.$set(this.formList,"disabledEndDate",true)
         this.$set(this.formList,"endDate","9999-12-31")
         this.rules.endDate[0].required=false
       }else{
         this.$set(this.formList,"disabledEndDate",false)
         this.rules.endDate[0].required=true
       }
    },    
    //_.debounce防止重复点击
    submitForm:_.debounce(function(){ 
      //逻辑代码
      console.log(this.formList)      
      if(this.rules.endDate[0].required==true){
          if(this.formList.endDate<this.formList.beginDate){
              this.$message({type:'warning',message:"合同结束日期不能小于合同开始日期"})
              return
          }
      }
      let obj2={domainId:this.$route.query.domainId}     
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {        
          if (this.OperType == 0) {
            AddContractApi(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 {
            EditContractApi(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 {
          return false;
        }
      });
    },1000,{'leading':true,'trailing':false}),
    cancelForm() {
      //取消关闭
      this.$emit("update:showdialog", false);
      this.$nextTick(function () {
        this.$refs.ruleForm.resetFields(); //重置输入框提示
      });
    },
    refurlist(){

    }
  },
};
</script>
<style lang="scss">
.el-dialog-contract{
  .elcolEndDate{
     position: relative;
     .checkbox{
       position: absolute;
       top: 10px;
       right: 0;
     }
  }
}
</style>