<template>
  <div class="ct">
    <el-dialog
      title="创建子部门"
      :visible.sync="addDialog"
      width="58%"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-form :model="addForm" label-width="auto" ref="addStore" :rules="rules" v-loading="formLoading" :element-loading-text="loadText">
        <el-form-item label="部门名称:" prop="label">
          <el-input
            size="small"
            v-model="addForm.label"
            placeholder="请输入部门名称"
            style="width: 50%;"
          />
        </el-form-item>
        <el-form-item label="上级部门:" prop="parentId">
          <el-cascader v-model="addForm.parentId" :options="orgTree" :props="deptOption" :show-all-levels="false"  clearable style="width: 50%;" @change="handleDpetChange"></el-cascader>
        </el-form-item>
        <el-form-item label="门店名称:" prop="oyStallName">
           <el-input
            size="small"
            v-model="addForm.oyStallName"
            placeholder="请输入门店名称"
            style="width: 50%;"
          />
        </el-form-item>
        <el-form-item label="门店Id:" prop="oyStallCode">
           <el-input
            size="small"
            v-model="addForm.oyStallCode"
            placeholder="请输入门店Id"
            style="width: 50%;"
          />
        </el-form-item>
        <el-form-item label="门店会员id:" prop="oyStallMemberId" >
          <el-input
            size="small"
            v-model="addForm.oyStallMemberId"
            placeholder="门店会员id"
            style="width: 50%;"
          />
        </el-form-item>
        <el-form-item label="设置主管:" prop="clerkIds"  >
          <el-cascader :props="props" ref="direcRef" v-model="deptId" :disabled="ifDisabled" :options="parentDeptList" :show-all-levels="false"  filterable style="width: 30%;margin-right:15px;" @change="handleParentChange" ></el-cascader>
          <el-select v-model="addForm.clerkIds" filterable multiple placeholder="请选择" style="width: 30%;" clearble  @change="handleMemberChange" :loading="optionLoading" loading-text="数据加载中">
            <el-option
              v-for="item in peopleList"
              :key="item.id"
              :label="item.userName"
              :value="item.id"
             >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleAddCancel" size="small">取 消</el-button>
        <el-button type="primary" @click="handleAddFinish('addStore')" size="small">确 定</el-button>
      </span> 
    </el-dialog>
    <div></div>
  </div>
</template>

<script>
import { addGroup, getWxAllDeptList, getAllMemberList,getGroupById,getAllPeopleList,getOrgTree } from "@/api/in/mail";
import { log } from "util";

export default {
  props: {
    addDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
     // 检查名称
    const checkLabel = (rule, value, callback) => {
		  let labelReg = /^[\u4e00-\u9fa5A-Za-z0-9\-\_]*$/;
		  if (value == "") {
		    callback(new Error("请输入部门名称"));
		  } else if (!labelReg.test(value)) {//引入methods中封装的检查手机格式的方法
		    callback(new Error("只可以输入中文、字母、数字和减号!"));
		  } else {
		    callback();
		  }
    }
    // 限制id 
      const idNumber = (rule, value, callback) => {
		  let idReg = /^\+?(0|[1-9][0-9]*)$/
		  if (!idReg.test(value)) {
		    callback(new Error("只可以输入正整数"))
		  } else {
		    callback();
		  }
    }
    const memberNumber = (rule, value, callback) => {
		  let idReg = /^\+?(0|[1-9][0-9]*)$/
		  if (!idReg.test(value) && value != '') {
		    callback(new Error("只可以输入正整数"))
		  } else {
		    callback();
		  }
    }
    return {
      clerkIds: [],
      loadText: '加载中',
      treeData: [],
      group_name: "",
      shop_code: "",
      showTree: false,
      formLoading: false,
      params: {
        d_name: "",
        d_parentId: "",
        code: ""
      },
      checked: false,
      ////
      addForm: {
        label: '',
        parentId: '',
        oyStallName: '',
        oyStallMemberId: '',
        oyStallCode: '',
        clerkIds: [],
        oydeptId: ''
      },
      detail: 2,
      ifDisabled: false,
      deptId: '',
      // 上级部门
      parentDeptList: [],
      peopleList: [],
      orgTree: [],
      optionLoading: false,
      rules: {
        label: [
          { required: true, message: "请输入部门名称", trigger: "blur" },
          { max: 50, message: "长度在50个字符以内", trigger: "blur" }
        ],
        parentId: [{ required: true, message: "请选择上级部门", trigger: "change" }],
        oyStallCode: [{  required: true, validator: idNumber, trigger: "blur" }],
        oyStallMemberId: [{  required: false, validator: memberNumber, trigger: "blur" }],
        clerkIds: [{  required: true, message: "主管不能为空", trigger: "change" }]
      },
      deptOption: {
          value: 'id',
          children: 'children',
          lazy: true,
          emitPath: false,
          checkStrictly: true,
          lazyLoad (node, resolve) {
            const { level } = node;
            setTimeout(() => {
              const nodes = Array.from(level)
                .map(item => ({
                  value: level.id,
                  label: level.label,
                  leaf: level >= 2
                }))
              // 通过调用resolve将子节点数据返回,通知组件数据加载完成
              resolve(nodes);
            }, 1000);
          }
      },
      props: {
        value: 'id',
        children: 'children',
        lazy: true,
        emitPath: false,
        checkStrictly: true,
        lazyLoad (node, resolve) {
          const { level } = node;
          setTimeout(() => {
            const nodes = Array.from(level)
              .map(item => ({
                value: level.id,
                label: level.label,
                leaf: level >= 2
              }))
            // 通过调用resolve将子节点数据返回,通知组件数据加载完成
            resolve(nodes);
          }, 1000);
        }     
      }
    }
  },
  created() {
    this.formLoading = true
    this.getOrgTree()
    this.getDeptList()
  },
  methods: {
    handleDpetChange(val) {
      console.log(val,'val')   
    },
    getOrgTree() {
      getOrgTree().then(res => {
        this.orgTree = [res.data.organizations]
        this.formLoading = false
      });
    },
    handleParentChange(val) { 
      this.addForm.oydeptId = val
      this.optionLoading = true     
      this.clerkIds = []
      this.addForm.clerkIds = []
      this.getGroupMember(val)         
    },
    getDeptList() {
      getWxAllDeptList()
        .then(res => {
          console.log(res,'全部部门')
          this.parentDeptList = res.data
        })
        .catch(err => {
          console.log(err)
        });
    },
    handleAddCancel() {
      this.$emit("handleAddCancel")
    },
    handleAddFinish(formName) {
      this.formLoading = true
      this.loadText = "处理中"
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addForm.clerkIds = this.addForm.clerkIds + ""
          // let data = Object.assign(this.addForm,{ clerkIdss })
          // delete data.clerkIds
          addGroup(this.addForm).then(res => {
            if(res.result == "success") {
              if(res.data.isSuccessful == 0) {    
                this.addForm.clerkIds = this.clerkIds 
                this.$message.error("门店id不能重复")
                this.formLoading = false
              }else{
                this.$emit("handleAddFinish")
                this.formLoading = false
              }
            }else {
              this.addForm.clerkIds = this.clerkIds 
              this.$message.error(res.errorMsg)
              this.formLoading = false
            }
            
          })
        } else {
          return false;
        }
        })    
    },
    // 获取所有人员
    getGroupMember(id) {
      this.ifDisabled = true
      getAllPeopleList({ id }).then(res => {   
        this.peopleList = res.data       
        this.optionLoading = false
        this.ifDisabled = false
      })
    },
    handleMemberChange(val) {    
      this.clerkIds = val 
      // if(val.length == 0) {
      //   this.addForm.clerkIds = ''
      // }else {
      //   this.addForm.clerkIds = '验证用'
      // }
    }
  },
  watch: {
    deptId() {
      if (this.$refs.direcRef) {
        this.$refs.direcRef.dropDownVisible = false; //监听值发生变化就关闭它
      }
    }
  }
};
</script>

<style scoped>
.tree >>> .is-leaf + .el-checkbox .el-checkbox__inner {
  display: inline-block;
}
.tree >>> .el-checkbox .el-checkbox__inner {
  display: none;
}

.choose {
  padding: 16px;
  font-size: 16px;
  font-weight: bold;
  color: rgba(56, 56, 56, 1);
  box-sizing: border-box;
}
.title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  /* border-bottom: 1px solid #f8f8f8; */
  padding-bottom: 10px;
}
.transfer-footer {
  margin-left: 20px;
  padding: 6px 5px;
}
.ct >>> .el-dialog__header {
  border-bottom: 1px solid #f8f8f8;
}
.ct >>> .el-dialog__body {
  padding: 20px 40px;
}
.ct >>> .el-transfer-panel {
  width: 250px;
}
.circle {
  width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 50%;
  border: 1px solid rgba(208, 2, 27, 1);
  position: relative;
}
.circle >>> .icon {
  width: 28px;
  height: 28px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.br {
  border-top: 1px solid #f8f8f8;
  border-bottom: 1px solid #f8f8f8;
  padding: 24px 0;
}
.config_item {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.config_name:before {
  content: "* ";
  color: red;
}
.config_name {
  width: 80px;
  text-align: center;
  margin-right: 10px;
}
.config_value {
  width: 230px;
}
.father_group {
  margin: 10px 0;
  width: 228px;
  height: 38px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  position: relative;
}
.arrow_down {
  width: 0;
  height: 0;
  border-width: 5px;
  border-style: solid;
  border-color: #ccc transparent transparent transparent;
  position: absolute;
  right: 10px;
  top: 20px;
}
.arrow_up {
  width: 0;
  height: 0;
  border-width: 5px;
  border-style: solid;
  border-color: transparent transparent #ccc transparent;
  position: absolute;
  right: 10px;
  top: 15px;
}
.tree_data {
  margin-left: 90px;
}
.father_name_text {
  line-height: 38px;
  padding-left: 15px;
}
.tips {
  width: 100%;
  text-align: center;
  color: red;
  margin: 5px 0;
}
</style>