<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="employeelabel" prop="">
              <span v-for="(item, index) in multipleArr" :key="item.id">
                <em>{{ item.name }}</em>
                <b v-if="index !== multipleArr.length - 1">, </b>
              </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="应用角色权限：" prop="">
              <el-checkbox v-model="rolecheck" @change="RoleCheckAll"
                >全选</el-checkbox
              >
              <el-tree
                ref="tree"
                :data="AuthAppRoledata"
                show-checkbox
                node-key="id"
                :props="defaultProps"
              >
              </el-tree>
            </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"  @refurlist="refurlist" ref="popChildrenMoveSuper"></MoveSuperDialog> -->
  </section>
</template>
<script>
import selectTree from "@/components/SelectTree";
import MoveSuperDialog from "./MoveSuperDialog.vue";
import {
  myappsAuthListApi,
  AddAuthListApi,
  EmployIdGetRoleListApi,
  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"],
  watch: {
    showdialog() {
      this.dialogFormVisible = this.showdialog;
      this.defaulDataParent = [];
    },
  },
  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: "blur" }],
      },
      defaulDataParent: "", //上级部门默认回选数据
      defaulData: [],
      tableDataEmployee: [],
      resultArr: [], //选择用户下拉得到对应名称数组
      showdialogMoveSuper: false,
      fileList: [],
      disabledUser: false,
      multipleArr: [],
      AuthAppRoledata: [], //默认查询应用角色列表树
      defaultProps: {
        children: "responses",
        label: "name",
      },
      rolecheck: false,
      employeelabel:`要授权的${$SuperviseStr.employee}：`,
      PrevRoleIds:[],
      AuthAppRoledataAll:[]//显示所有应用列表以及二级角色列表
    };
  },
  methods: {
    getTableRow(data, type, flag) {
      this.multipleArr = data;
      let newRowData = JSON.parse(JSON.stringify(data)); //拷贝一份存储对象
      // this.formList = newRowData; //拷贝一份存储对象引用不同地址
      this.OperType = type;
      this.rolecheck = false;
      this.title = "授权";
      this.myappsAuthList(); //应用角色权限列表树
      this.$nextTick(() => {
        this.$refs.tree && this.$refs.tree.setCheckedKeys([]);
      });
      
      if (newRowData[0].id) {
        let obj2 = { domainId: this.$route.query.domainId };
        let roleIds = [];
        
        // 如果是单个员工编辑，获取其角色权限
        if (newRowData.length === 1) {
          EmployIdGetRoleListApi(newRowData[0].id, obj2).then((response) => {
            if (response.data) {
              if (response.data.apps.length) {
                response.data.apps.forEach((item) => {
                  if (item.roles.length) {
                    item.roles.forEach((its) => {
                      roleIds.push(its.id);
                    });
                  }
                });
                this.PrevRoleIds=roleIds//PrevRoleIds记住上次角色id
                this.$refs.tree.setCheckedKeys(roleIds); //newRowData[0].roleIds为数组多个id,
              }
            }
          });
        }
      }
    },
    myappsAuthList() {
      //应用角色权限列表树
      let obj2 = { domainId: this.$route.query.domainId }; //获取url域domainId
      myappsAuthListApi(obj2).then((response) => {
        if (response.status == 200) {          
          this.AuthAppRoledataAll=response.data
          let Array=response.data
          let ArrayResult=Array&&Array.filter(item=>{
            if(item.responses.length){
              item.responses.filter(its=>{
                 return its.show
              })
            }
            return item.show
          })
          this.AuthAppRoledata = ArrayResult;
        }
      });
    },
    RoleCheckAll() {
      if (this.rolecheck) {
        this.$refs.tree.setCheckedNodes(this.AuthAppRoledata);
      } else {
        this.$refs.tree.setCheckedNodes([]);
      }
    },
    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);
    },
    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", null);
        this.rules.endDate[0].required = false;
      } else {
        this.$set(this.formList, "disabledEndDate", false);
        this.rules.endDate[0].required = true;
      }
    },
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // console.log(this.$refs.tree.getCheckedNodes());
          // console.log(this.multipleArr)
          let employeeIds = [];
          this.multipleArr.forEach((item) => {
            employeeIds.push(item.id);
          });
          let roleIds = [];
          if (this.$refs.tree.getCheckedNodes().length) {
            this.$refs.tree.getCheckedNodes().forEach((item) => {
              if (item.dataType) {
                roleIds.push(item.id);
              }
            });
          } else {
            this.$message({ type: "warning", message: "请选择应用角色权限" });
            return;
          }
          let obj2 = { domainId: this.$route.query.domainId };
          // debugger
          console.log(this.PrevRoleIds)//获取所有选中的角色id

          let GetShowFalsePrevRoleIds=[];//获取隐藏选中的角色id
          this.PrevRoleIds.length&&this.PrevRoleIds.forEach(item=>{
            this.AuthAppRoledataAll.length&&this.AuthAppRoledataAll.forEach(its=>{
              its.responses.length&&its.responses.forEach(iks=>{
                   if(item==iks.id&&!iks.show){
                    GetShowFalsePrevRoleIds.push(item)
                   }
              })
            })
          })
          let roleIdsArr=roleIds.concat(GetShowFalsePrevRoleIds)

          console.log(roleIds)
          console.log(GetShowFalsePrevRoleIds)
          console.log(roleIdsArr)
          AddAuthListApi(employeeIds, roleIdsArr, 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.$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>
