<template>
  <Popup ref="popup" title="角色信息" width="800px" @closed="dialogClosed">
    <el-form :model="form" :rules="rules" ref="form" label-width="80px">
      <el-form-item label="角色名称" prop="roleName" placeholder="请输入角色名称">
        <el-input v-model="form.roleName" :maxlength="32"></el-input>
      </el-form-item>
      <el-form-item label="角色ID" prop="roleId">
        <el-input v-model="form.roleId" disabled placeholder="系统将自动生成"></el-input>
      </el-form-item>
      <el-form-item label="角色状态" prop="status" required>
        <el-switch
          :value="form.status === ROLE_STATUS.getValueByName('enabled')"
          @change="
            form.status = $event
              ? ROLE_STATUS.getValueByName('enabled')
              : ROLE_STATUS.getValueByName('disabled')
          "
        />
      </el-form-item>
      <el-form-item label="角色权限" prop="menuIdList">
        <div class="tree-menus" v-loading="loading">
          <div class="tree-menu-item">
            <div class="header">随访中心</div>
            <div class="tree-menu-item-content">
              <el-tree
                ref="tree"
                :default-checked-keys="form.doctorWorkChecks"
                :data="treeData"
                show-checkbox
                node-key="id"
                @check="(_, val) => handleSelectMenuChange(val, 'doctorWorkChecks')"
                :props="{ children: 'children', label: 'menuName',  }"
                default-expand-all
              ></el-tree>
              <!-- isLeaf: true -->
            </div>
          </div>
          <div class="tree-menu-item">
            <div class="header">营销中心-管理层</div>
            <div class="tree-menu-item-content">
              <el-tree
                ref="tree2"
                :default-checked-keys="form.saleManageChecks"
                :data="treeData2"
                show-checkbox
                node-key="id"
                @check="(_, val) => handleSelectMenuChange(val, 'saleManageChecks')"
                :props="{ children: 'children', label: 'menuName', isLeaf: true }"
                default-expand-all
              ></el-tree>
            </div>
          </div>
          <div class="tree-menu-item">
            <div class="header">营销中心-执行层</div>
            <div class="tree-menu-item-content">
              <el-tree
                ref="tree3"
                :default-checked-keys="form.saleProcessChecks"
                :data="treeData3"
                show-checkbox
                node-key="id"
                @check="(_, val) => handleSelectMenuChange(val, 'saleProcessChecks')"
                :props="{ children: 'children', label: 'menuName', isLeaf: true }"
                default-expand-all
              ></el-tree>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </Popup>
</template>

<script>
import Popup from "@/components/Popup";
import { saveRole } from "@/api/userManage/role";
import { getRoleMenuList, geMenuTreeList } from "@/api/userManage/menu";
import { ROLE_STATUS } from "@/enums/index";
import { to } from "await-to-js";
export default {
  components: {
    Popup,
  },
  data() {
    return {
      ROLE_STATUS,
      loading: false,
      form: this.getFormDefaultValue(),
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { max: 32, message: "长度不能超过32个字符", trigger: "blur" },
        ],
        menuIdList: [
          {
            validator: (rule, value, callback) => {
              if (
                this.form.doctorWorkChecks?.length >= 0 ||
                this.form.saleManageChecks?.length >= 0 ||
                this.form.saleProcessChecks?.length >= 0
              ) {
                return callback();
              }
              callback(new Error("请选择角色权限"));
            },
          },
        ],
      },
      treeData: [],
      treeData2: [],
      treeData3: [],
      loading: false,
    };
  },
  methods: {
    loadAllMenuList() {
      return geMenuTreeList().then((res) => {
        this.treeData = res.data?.doctorWork || [];
        this.treeData2 = res.data?.saleManage || [];
        this.treeData3 = res.data?.saleProcess || [];
      });
    },
    async loadMenuIdList(roleId) {
      await this.loadAllMenuList();
      if (!roleId) {
        return
      }
      this.loading = true;
      const [err, res] = await to(getRoleMenuList({ roleId }));
      if (!err) {
        this.form.doctorWorkChecks = res?.data?.doctorWork || [];
        this.form.saleManageChecks = res?.data?.saleManage || [];
        this.form.saleProcessChecks = res?.data?.saleProcess || [];
      }
      this.form.doctorWorkChecks = this.form.doctorWorkChecks.filter(item => this.treeData.findIndex(item2 => item2.id === item) < 0)

      console.log('this.form.doctorWorkChecks=', this.form.doctorWorkChecks)
      this.form.saleManageChecks = this.form.saleManageChecks.filter(item => this.treeData2.findIndex(item2 => item2.id === item) < 0)

      this.form.saleProcessChecks = this.form.saleProcessChecks.filter(item => this.treeData3.findIndex(item2 => item2.id === item) < 0)
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.form.doctorWorkChecks);
        this.$refs.tree2.setCheckedKeys(this.form.saleManageChecks);
        this.$refs.tree3.setCheckedKeys(this.form.saleProcessChecks);
      });
      this.loading = false;
    },
    handleSelectMenuChange({ checkedKeys, halfCheckedKeys }, property) {
      console.log("property=", property, checkedKeys);
      this.form[property] = checkedKeys;
      this.$nextTick(() => {
        this.$refs.form?.validateField("menuIdList");
      });
    },
    getFormDefaultValue() {
      return {
        roleName: "",
        status: ROLE_STATUS.getValueByName("enabled"),
        menuIdList: [],
        doctorWorkChecks: [],
        saleManageChecks: [],
        saleProcessChecks: [],
      };
    },
    async open(params) {
      console.log("params=", params);
      await this.$nextTick();
      this.$refs.popup.open(params);
      if (params) {
        for (const key of Object.keys(this.form)) {
          this.form[key] = params[key];
        }
        this.form.roleId = params.id;
        this.loadMenuIdList(params.id);
      }
      this.promise = {};
      return new Promise((resolve, reject) => {
        this.promise.resolve = resolve;
        this.promise.reject = reject;
      });
    },
    handleCancel() {
      this.$refs.popup.close();
    },
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            const { menuIdList, doctorWorkChecks = [], saleManageChecks = [], saleProcessChecks = [], ...params } = this.form;
              await this.$nextTick();
              const halfChecks1 = this.$refs.tree.getHalfCheckedKeys();
              const halfChecks2 = this.$refs.tree2.getHalfCheckedKeys();
              const halfChecks3 = this.$refs.tree3.getHalfCheckedKeys();
            const res = await saveRole({
              menuIdList: [...doctorWorkChecks, ...saleManageChecks, ...saleProcessChecks, ...halfChecks1, ...halfChecks2, ...halfChecks3],
              ...params,
            });
            if (this.form.roleId) {
              this.$message.success("修改成功");
            } else {
              this.$message.success("新增成功");
            }
            this.$refs.popup.close();
            this.promise.resolve(res.data);
          } finally {
            this.loading = false;
          }
        } else {
          // 表单校验失败
          return false;
        }
      });
    },
    dialogClosed() {
      this.$refs.tree.setCheckedKeys([]);
      this.$refs.tree2.setCheckedKeys([]);
      this.$refs.tree3.setCheckedKeys([]);
      this.form = this.getFormDefaultValue();
      this.$nextTick(() => {
        this.$refs.form.clearValidate("menuIdList");
      });
      // this.promise.reject();
    },
  },
};
</script>
<style lang="scss" scoped>
.tree-menus {
  display: flex;
  border: 1px solid #dfe4ed;
  border-radius: 4px;

  .tree-menu-item {
    flex: 1;
    .header {
      overflow-y: auto;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 40px;
      border-right: 1px solid #dfe4ed;
      border-bottom: 1px solid #dfe4ed;
    }
    .header:last-child {
      border-right: none;
    }
    .tree-menu-item-content {
      overflow-y: auto;
      height: 200px;
      border-right: 1px solid #dfe4ed;
    }
    .tree-menu-item-content:last-child {
      border-right: none;
    }
  }
}
</style>
