<template>
  <el-dialog
    v-dialogDrag
    :title="title"
    :visible="dialogFormVisible"
    @close="cancelForm"
    :close-on-click-modal="false"
    class="el-dialog-single el-dialog-employeeIn"
  >

   <!-- 备注区域 -->
    <!-- <section class="remarkBox">
        <div class="remarkInfo">
            <i class="el-icon-warning-outline el-icon-flag"></i>
            <span>
             提示：只能邀请到自己可管理的驻勤点下。<br/>
           </span>
        </div>
    </section> -->

    <el-form
      label-width="200px"
      :model="formList"
      :rules="rules"
      ref="ruleForm"
    >
       <el-row>
        <el-col :span="24">
          <el-form-item label="驻勤点：" prop="attendSiteId">
            <el-select v-model="formList.attendSiteId" placeholder="请选择驻勤点" @change="dutySelectChange" clearable>
              <el-option :label="item.attendSiteName" :value="item.id"  v-for="(item,index) in dutylist" :key="index"></el-option>        
            </el-select>
          </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="endTime">
            <el-date-picker
             v-model="formList.endTime"
             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>
        <el-col :span="24">
          <el-button type="primary" @click="qrCodeBtn">生成邀请链接及二维码</el-button>
        </el-col>
      </el-row>
      
      <div class="linehr"></div>
      <el-row v-if="qrcodeShow">
        <el-col :span="12">
           <div id="qrCode" ref="qrCodeDiv"></div>
        </el-col>
        <el-col :span="12">
          <span class="qrbtnCopy">
           <el-button @click="downloadQrcode">下载二维码图片</el-button>
           <el-button class="copyText" @click="CopyclipboardUrl">复制邀请链接</el-button>
          </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 selectTree from "@/components/SelectTree";
import {AddDutyApi,dutyListApi } from "@/api/staffApi.js"
import QRCode from 'qrcodejs2';
import Clipboard from 'clipboard'
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: ["showdialogDuty", 'deptDataList'],
  watch: {
    showdialogDuty() {
      this.dialogFormVisible = this.showdialogDuty;
      this.defaulDataParent=[]
    },
    "formList.departId"(){
      if(this.formList.departId){
        this.$refs.ruleForm.clearValidate(['departId'])//清除验证
      }
    },
    deptDataList(v) {
      this.getTreeDepartlist = v
    }
  },
  components: {
    selectTree //注册组件
  },
  data() {
    return {     
      title: "邀请驻勤人员",
      dialogFormVisible: this.showdialogDuty,
      OperType: 0, //0 新增  1修改
      formList: {
        attendSiteId:'',
        departId:'',
        endTime:''
      },
      rules: {       
        attendSiteId:[{required: true, message: "请选择驻勤点", trigger: "blur"}],
        departId:[{required: true, message: `请选择入职${$SuperviseStr.depart}`, trigger: "blur"}],
        endTime:[{required: true, message: "请选择链接有效截止日期", trigger: "blur"}],  
      },
      defaulDataParent:'',//上级部门默认回选数据
      defaulData:[],
      qrcodeShow:false,
      shareUrl:'',
      dutylist:[],
      departlabel:`入职${$SuperviseStr.depart}：`,
      getTreeDepartlist:[],
    };
  },
  methods: {   
    selectClickT(val){
       this.getTreeDepartlist=val
    },   
    getTableRow(data, type) {       
      let newRowData = JSON.parse(JSON.stringify(data)); //拷贝一份存储对象
      this.formList = newRowData; //拷贝一份存储对象引用不同地址
      this.OperType = type; 
      this.dutyList()//获取驻勤点列表
      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)
    },
    dutyList(){//查询驻勤列表
        let obj2={domainId:this.$route.query.domainId} 
        dutyListApi(obj2).then(response=>{
            if(response.status==200){
              console.log(response)
              this.dutylist=response.data
              // this.dutylist.forEach(item=>{
              //   item.value=item.id
              //   item.label=item.attendSiteName
              // })
              // console.log(this.dutylist)
            }
        })
    },
    dutySelectChange(){
       this.dutylist.forEach(item=>{
           if(item.id==this.formList.attendSiteId){
             this.formList.attendSiteName=item.attendSiteName
           }
       })
    },
    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)  
             }
         })
    },  
    async qrCodeBtn(){//点击生成二维码-请求接口返回url
       //api接口位置
     let  orgData=new Promise((resolve,reject)=>{
         let obj2={domainId:this.$route.query.domainId}     
         this.$refs.ruleForm.validate((valid) => {
            if (valid) { 
           return  AddDutyApi(this.formList,obj2).then((response) => {
                  //新增
                  if (response.status==200) {
                    if(response.data){
                      console.log(1)
                      resolve(response.data)                      
                    }
                  }
                });
            }
          })
       })
      
      orgData.then(res=>{
         if(res){
            this.qrcodeShow=true  
            if(parent.location.origin){
              this.shareUrl=parent.location.origin+'/static/signon/staffMobile/#/duty?inviteDepartId='+res
            }
            this.$nextTick(()=>{
                document.getElementById("qrCode").innerHTML=""  
                new QRCode(this.$refs.qrCodeDiv,{
                  text:this.shareUrl,
                  width:200,
                  height:200,
                  colorDark: "#333333", //二维码颜色
                  colorLight: "#ffffff", //二维码背景色
                  correctLevel: QRCode.CorrectLevel.L//容错率，L/M/H
                })
            })
         }
      })
      
       
    },   
    downloadQrcode(){//下载二维码图片
       var img = document.querySelectorAll('#qrCode img')
        for(var i = 0; i < img.length; i++){
            var url = img[i].src
            var a = document.createElement("a");
            var event = new MouseEvent("click"); // 创建一个单击事件
            a.href = url;
            a.download = 'qr.png'// 图片名称
            a.dispatchEvent(event); // 触发a的单击事件
        }    
    },
    CopyclipboardUrl(){//复制邀请链接
      console.log(this.shareUrl)
      let link=this.shareUrl
      this.$nextTick(()=>{
          let clipboard=new Clipboard('.copyText', {
              text: function () {
                return link
              }
            });
            clipboard.on("success", e => {
                this.$message({
                  type: "success",
                  message: "复制成功，请到微信打开!"
                });
                clipboard.destroy(); // 释放内存
          });
          clipboard.on("error", e => {
              this.$message({
                type: "warning",
                message: "该浏览器不支持自动复制!"
              }); // 不支持复制
              clipboard.destroy(); // 释放内存
          });
      });
    },
    submitForm() {  
      // let credential={
      //   number:this.formList.number,
      //   type:this.formList.type
      // }
      // this.formList.credential=credential
      // console.log(this.formList)
      // 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();
      //         }
      //       });          
      //   } else {
      //     return false;
      //   }
      // });
    },
    cancelForm() {
      this.qrcodeShow=false
      //取消关闭
      this.$emit("update:showdialogDuty", false);
      this.$nextTick(function () {
        this.$refs.ruleForm.resetFields(); //重置输入框提示
      });
    },
  },
};
</script>
<style lang="scss">
.el-dialog-employeeIn{
  .remarkBox{
        text-align: left;margin:0 20px;
        .remarkInfo{
            background: #fafafa;              
            color: #666666;
            border: 1px solid #ebeef5;
            border-radius: 4px;
            line-height: 30px;
            padding: 10px;
            display: flex;
            .el-icon-flag{margin-top:9px;color: #ffc108;margin-right:10px;}
        } 
    }
  .linehr{border-bottom: 1px dotted #ccc; width: 90%;margin: 10px auto;}  
  .qrbtnCopy{
    display: flex;
    flex-direction: column;
    button{
      margin:0;
      margin-bottom: 10px;
    }
  }
}
.elradioLineheight{
    margin-top:5px; 
  .el-radio{display: block; line-height: 30px;}
}
</style>