<template>
  <div>
    <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
      <el-tab-pane label="管理员管理范围" name="org" lazy>
        <dg-tree
          ref="tree"
          show-checkbox
          lazy
          :load="loadNode"
          node-key="id"
          :props="defaultProps"
          translate-data="translateData"
          check-strictly
          @check="checkClick"
        />
      </el-tab-pane>
    </el-tabs>
    <div v-footer>
      <dg-button @click="handleCancel">取消</dg-button>
      <dg-button type="primary" @click="handleSaveOrg">保存</dg-button>
    </div>
  </div>
</template>

<script>
import * as adminApi from '@/api/admin-manage';
import { mapGetters } from 'vuex';
export default {
  name: 'adminManageEditor',
  props: {
    id: String,
    defaultProps: {
      default() {
        return {
          value: 'id',
          label: 'name',
          isLeaf(data) {
            return data.isParent !== true;
          }
        };
      }
    },
    menuProps: {
      default() {
        return {
          value: 'value',
          label: 'label',
          // isLeaf(data) {
          //     return data.isParent !== true;
          // },
          children: 'children'
        };
      }
    },
    defaultExpandedKeys: {
      type: Array,
      default: () => []
    },
    defaultCheckedKeys: {
      type: Array,
      default: () => []
    },
    defaultHalfCheckedKeys: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: ''
    }
  },
  data() {
    const halfCheckKeys = [...this.defaultHalfCheckedKeys];
    const checksKeys = [...this.defaultCheckedKeys];
    return {
      activeName: 'org',
      translateData: [],
      halfCheckKeys,
      checksKeys,
      orgParams: {
        id: '',
        userId: '',
        mtType: this.type == 'create' ? 'TEMP' : 'APP'
      },
      menuParams: {
        type: this.type == 'create' ? 'TEMP' : '',
        userId: ''
      },
      allMenu: [],
      tempNoChecks: [], //用户手动取消勾选
      tempChecks: [], // 用户手动勾选
      halfCheckList: [], //半选
      parentStatus: null
    };
  },
  methods: {
    handleCancel() {
      this.$emit('close');
    },
    handleClick(tab) {
      if (tab.name == 'menu') {
        this.getSelfMenu();
      }
    },
    loadNode(node, resolve) {
      const that = this;
      this.orgParams.userId = this.id;
      const params = {
        ...this.orgParams,
        id: node.key ? node.key : ''
      };
      that.getTree(params, resolve);
    },
    // 管理范围
    getTree(params, resolve) {
      const that = this;
      let node, parentNode;

      return adminApi.orgRange(params).then((res) => {
        // 渲染树节点
        resolve(res || []);
        if (res.length) {
          that.$nextTick(() => {
            res.forEach((item) => {
              node = that.$refs.tree.getNode(item.id);
              parentNode = item.pid ? that.$refs.tree.getNode(item.pid) : null;
              // 父节点存在
              if (parentNode) {
                // 父节点勾选
                if (parentNode.checked) {
                  if (that.tempChecks.indexOf(item.pid) > -1) {
                    node.checked = true;
                    node.indeterminate = false;
                    that.tempChecks.push(item.id);
                  } else {
                    if (item.checked == '2') {
                      node.checked = true;
                      node.indeterminate = false;
                    } else if (item.checked == '0') {
                      node.checked = false;
                      node.indeterminate = false;
                    } else if (item.checked == '1') {
                      node.checked = false;
                      node.indeterminate = true;
                    }
                  }
                } else if (!parentNode.checked) {
                  if (that.tempNoChecks.indexOf(item.pid) > -1) {
                    that.tempNoChecks.push(item.id);
                    node.checked = false;
                    node.indeterminate = false;
                  } else {
                    if (item.checked == '2') {
                      node.checked = true;
                      node.indeterminate = false;
                    } else if (item.checked == '0') {
                      node.checked = false;
                      node.indeterminate = false;
                    } else if (item.checked == '1') {
                      node.checked = false;
                      node.indeterminate = true;
                    }
                  }
                }
              } else {
                if (item.checked == '2') {
                  node.checked = true;
                  node.indeterminate = false;
                } else if (item.checked == '0') {
                  node.checked = false;
                  node.indeterminate = false;
                } else if (item.checked == '1') {
                  node.checked = false;
                  node.indeterminate = true;
                }
              }
            });
          });
        }
      });
    },
    // 复选框被点击时
    checkClick(data, node) {
      // tempNoChecks -- 记录用户手动取消勾选  tempChecks--记录用户手动勾选
      let currentNode = this.$refs.tree.getNode(data);
      let parentNode = data.pid ? this.$refs.tree.getNode(data.pid) : null;
      const that = this;
      const setChecked = (node, isChecked) => {
        let childs = node.childNodes;
        if (childs && childs.length > 0) {
          childs.forEach((child) => {
            child.checked = isChecked;
            child.indeterminate = false;
            setChecked(child, isChecked);
          });
        }

        if (isChecked) {
          if (that.tempChecks.indexOf(data.id) == -1) {
            that.tempChecks.push(data.id);
          }
        }
        if (!isChecked) {
          if (that.tempNoChecks.indexOf(data.id) == -1) {
            that.tempNoChecks.push(data.id);
          }
        }
      };

      // 手动设置 全选和全不选
      if (currentNode.checked) {
        setChecked(currentNode, true);
      } else {
        setChecked(currentNode, false);
        if (parentNode && parentNode.checked) {
          // 递归设置半选
          this.setHalfCheckedNodes(parentNode);
        }
      }
    },

    getCheckedKeys(leafOnly = false, includeHalfChecked = false) {
      return this.$refs.tree.getCheckedKeys(leafOnly, includeHalfChecked);
    },
    getHalfCheckedKeys() {
      return this.$refs.tree.getHalfCheckedKeys();
    },
    setCheckedNodes(keys, leafOnly = false) {
      keys.forEach((item) => {
        this.$refs.tree.setChecked(item, true, leafOnly);
      });
    },
    // 递归获取顶级节点
    getTopParentNode(key) {
      const that = this;
      let topParent = null;
      const currentNode = this.$refs.tree.getNode(key);
      topParent = currentNode.data.pid ? this.$refs.tree.getNode(currentNode.data.pid) : null;
      if (currentNode && topParent) {
        that.getTopParentNode(topParent);
      }
      return topParent || currentNode;
    },

    // 递归设置半选
    setHalfCheckedNodes(key) {
      const that = this;
      const node = this.$refs.tree.getNode(key);
      const indeterminateFunc = (node) => {
        if (node && node.parent && node.parent.checked) {
          node.parent.indeterminate = true;
          node.parent.checked = false;
          indeterminateFunc(node.parent);
        }
      };
      if (node) {
        node.indeterminate = true;
        node.checked = false;
        indeterminateFunc(node);
      }
    },
    setHalfNoCheckedNodes(key) {
      const that = this;
      const node = this.$refs.tree.getNode(key);
      const noindeterminateFunc = (node) => {
        if (node && node.parent && !node.parent.checked) {
          node.parent.indeterminate = false;
          noindeterminateFunc(node.parent);
        }
      };
      if (node) {
        node.indeterminate = false;
        // that.halfCheckKeys = that.halfCheckKeys.filter((item) => item != key);
        noindeterminateFunc(node);
      }
    },

    getAllMenu() {
      const that = this;
      const { id } = this.user;
      adminApi.getAllMenu(id).then((res) => {
        that.allMenu = res;
      });
    },
    // 菜单范围
    getSelfMenu() {
      const that = this;
      let params = {
        ...this.menuParams,
        userId: this.id
      };
      let node;
      adminApi.menuRange(params).then((res) => {
        that.$nextTick(() => {
          res.forEach((key) => {
            node = that.$refs.menuTree.getNode(key);
            if (node && node.isLeaf) {
              that.$refs.menuTree.setChecked(key, true);
            }
          });
        });
      });
    },
    handleSaveOrg() {
      // const { halfCheckKeys, checksKeys } = this;
      const that = this;
      const resultChecks = [];
      const checks = this.getCheckedKeys(); //全勾选状态
      const halfChecks = this.getHalfCheckedKeys(); //半勾选状态
      let params = {};
      let orgIds = '';
      if (!checks.length && !halfChecks.length) {
        that.$message('未勾选管理范围', 'error');
        return;
      } else {
        if (checks.length) {
          checks.forEach((item) => {
            // debugger;
            let topParent = that.getTopParentNode(item);
            if (topParent.checked) {
              if (resultChecks.indexOf(topParent.data.id) === -1) {
                resultChecks.push(topParent.data.id);
              }
            } else {
              resultChecks.push(item);
            }
          });
          // console.log(resultChecks);
          resultChecks.forEach((aaa) => {
            orgIds += aaa + ':2' + ',';
          });
        }
        if (halfChecks.length) {
          halfChecks.forEach((item) => {
            orgIds += item + ':1' + ',';
          });
        }
        orgIds = orgIds.substr(0, orgIds.length - 1);
      }
      params['orgIds'] = orgIds;
      params['type'] = this.type == 'create' ? 'TEMP' : '';
      params['userId'] = this.id;

      // 区别修改或新增
      const apiName = this.type === 'create' ? 'saveOrgRange' : 'saveAppRange';

      adminApi[apiName](params).then((res) => {
        that.success();
        // that.$emit("success", true); // 不必刷新表格
        that.$emit('oneSaveOrg', true);
      }).catch(error => {
         that.$message.warning(error);
      });
    },
    success(message = '操作成功!') {
      const that = this;
      that.$message.success(message);
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  created() {}
};
</script>
