<!--
 * @Description:
 * @Version: 1.0
 * @Author: Drama
 * @Date: 2022-09-14 11:09:43
 * @LastEditors: Drama
 * @LastEditTime: 2022-10-18 15:13:58
 * @FilePath: /haoban-3/src/views/enterprise/guide-setting-new.vue
 * Copyright (C) 2022 huzhenhong. All rights reserved.
-->
<template>
  <div class="app-detail-wrap">
    <div class="border-box p-t-30 p-l-26 p-r-211">
      <el-form class="rule-form" ref="ruleForm" v-model="roleForm" label-width="100px">
        <el-form-item label="应用权限" required>
          <div class="dis-f">
            <div class="title-wrap border-box border-radio-2">
              <div class="border-box tag-wrap F-S-14 F-C-BLACK dis-center border-radio-2 cursor-pointer" v-for="(item, index) in titleList" :key="index" :class="[activeNum == index ? 'checked-status' : '', item.isEmpty ? 'empted-status' : '']" @click="chooseType(index)">{{ item.title }}</div>
            </div>
            <div v-if="isShowErrorTip" class="error-tip border-box border-radio-2">
              <i class="el-icon-warning"></i>
              <div class="F-C-BLACK F-S-12 m-l-9">当前有未填项</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="" prop="" class="">
          <vue-gic-auth-tree class="auth-tree" openAuthRelated default-expand-all :data="treeData" show-checkbox ref="tree" node-key="menuCode" :default-checked-keys="withoutParents" :props="defaultProps"></vue-gic-auth-tree>
        </el-form-item>
      </el-form>
    </div>
    <!-- save按钮 -->
    <div class="fixed-save-btn border-box" v-if="$getButtonLimit($buttonCode.saveGoodsSet)">
      <el-button :limit-code="$buttonCode.saveGoodsSet" type="primary" :loading="loading" @click="submit" :disabled="$store.state.wxEnterpriseType">保存</el-button>
    </div>
  </div>
</template>

<script>
import { deepClone, arrToTree, getArrDifference, getDelOrAddDate } from '@/utils';
import { getRequest, postJsonRequest } from '@/api/api';
import { _debounce } from '@/common/js/public';

export default {
  name: 'GuideSetting',
  data() {
    return {
      roleForm: {},
      titleList: [
        { title: '导购', isEmpty: false },
        { title: '店长', isEmpty: false },
        { title: '区经/督导', isEmpty: false }
      ],
      activeNum: 0,
      defaultProps: {
        children: 'menuBOList',
        label: 'menuName'
      },
      withoutParents: [], //不包含父节点
      treeData: [],
      treeData_0: [],
      treeData_1: [],
      treeData_2: [],
      withoutParents_0: [],
      withoutParents_1: [],
      withoutParents_2: [],
      saveWithoutParents_0: [], // 用于保存
      saveWithoutParents_1: [],
      saveWithoutParents_2: [],
      curMenuCode_0: [], // 拷贝当前节点了的按钮
      curMenuCode_1: [],
      curMenuCode_2: [],
      roleId_0: '',
      roleId_1: '',
      roleId_2: '',
      copyMenu_0: [],
      copyMenu_1: [],
      copyMenu_2: [],
      loading: false,
      isShowErrorTip: false
    };
  },
  computed: {},
  async mounted() {
    await this.getMenuRoleList(0);
    await this.getMenuRoleList(1);
    await this.getMenuRoleList(2);
  },
  methods: {
    chooseType(index) {
      this.isShowErrorTip = false;
      this.treeData = deepClone(this['copyMenu_' + index]);
      this.titleList.forEach(item => {
        item.isEmpty = false;
      });
      // let isChooseList = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());
      let isChooseList = this.$refs.tree.getCheckedKeys(); // 不包含半选
      let isChooseList_ = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys()); // 包含半选

      // 切换tab时 缓存上个tag选择的节点
      this['withoutParents_' + this.activeNum] = [...isChooseList];
      // 缓存保存加上半选的数据
      this['saveWithoutParents_' + this.activeNum] = [...isChooseList_];
      this.activeNum = index;
      // this.treeData = deepClone(this.copyMenu);
      this.withoutParents = this['withoutParents_' + this.activeNum];
    },
    // 获取类型选择菜单
    getQueryMenuList(clerkType) {
      let params = {
        clerkType
      };
      getRequest('/haoban-manage3-web/role/queryMenuByClerkType', params).then(res => {
        if (res.data.code == 0) {
          if (res.data.result) {
            this['roleId_' + clerkType] = res.data.result.roleId;
            let filterCodes = []; // 筛选出不含父节点menuCode的数据
            let flagCodes = [];
            // TODO: 删除半选
            let menuCodes = deepClone(res.data.result.menuCodes);
            let menuList = deepClone(res.data.result.menuList);
            menuList = menuList.filter(item => item.menuType != 2);
            menuList.forEach(item => {
              item.ownerShipArr = item.ownerShip.split('|');
            });
            menuList = menuList.filter(item => item.ownerShipArr.includes(String(clerkType)));
            menuList.forEach(item => {
              if (menuCodes.includes(item.parentCode)) {
                flagCodes.push(item.parentCode);
              }
            });
            flagCodes = Array.from(new Set(flagCodes));
            filterCodes = menuCodes.filter(v => flagCodes.every(val => val != v));
            this['curMenuCode_' + clerkType] = [...res.data.result.menuCodes]; // 保存当前类别选中状态，保存的时候用用于记录操作的区别
            // this['withoutParents_' + clerkType] = [...res.data.result.menuCodes];
            this['withoutParents_' + clerkType] = [...filterCodes];
            this['saveWithoutParents_' + clerkType] = [...menuCodes];
            if (clerkType == 0) {
              // 当前导购选中
              // this.withoutParents = [...res.data.result.menuCodes];
              this.withoutParents = [...filterCodes];
            }
          } else {
            this['withoutParents_' + clerkType] = [];
          }
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 获取菜单列表
    async getMenuRoleList(clerkType) {
      let query = {
        clerkType
      };
      await getRequest('/haoban-manage3-web/role/getHaobanMenuTreeList', query).then(res => {
        if (res.data.code == 0) {
          if (res.data.result) {
            let resData = res.data;
            let arr = resData.result;
            arr.forEach(item => {
              if (item.menuType == 0) {
                item.parentCode = 0;
              }
              if (item.menuBOList.length) {
                item.menuBOList = item.menuBOList.filter(data => data.menuType != 2);
                item.menuBOList.forEach(v => {
                  if (v.menuBOList.length) {
                    v.menuBOList = v.menuBOList.filter(f => f.menuType != 2);
                  }
                });
              }
            });
            let result = deepClone(arrToTree(arr, 0, { idName: 'menuCode', parentIdName: 'parentCode', childName: 'menuBOList' }));
            // result.forEach(item => {
            //   item.fold = false;
            //   item.menuBOList.forEach(el => {
            //     el.menuBOList = el.menuBOList ? el.menuBOList : [];
            //     if (el.menuBOList.length > 0) {
            //       el.foldBool = 1;
            //     }
            //   });
            //   item.rightId = item.menuCode;
            // });
            // 添加处理字段
            result.forEach(item => {
              // 一级
              item.ownerShipArr = item.ownerShip.split('|');
              if (item.menuBOList.length) {
                // 二级
                item.menuBOList.forEach(item_2 => {
                  item_2.ownerShipArr = item_2.ownerShip.split('|');
                  if (item_2.menuBOList.length) {
                    // 三级
                    item_2.menuBOList.forEach(item_3 => {
                      item_3.ownerShipArr = item_3.ownerShip.split('|');
                    });
                  }
                });
              }
            });
            let dealArr = deepClone(result);
            let dealTreeData = this.filterTreeData(dealArr, String(clerkType));

            dealTreeData.forEach(item => {
              item.fold = false;
              item.childList = item.menuBOList; // 构造childList
              item.rightType = '0';
              item.rightId = item.menuCode;
              if (item.menuBOList.length) {
                // 二级
                item.menuBOList.forEach(el => {
                  el.menuBOList = el.menuBOList ? el.menuBOList : [];
                  el.childList = el.menuBOList;
                  el.rightType = el.menuType == 3 ? '0' : '5';
                  if (el.menuBOList.length > 0) {
                    el.foldBool = 1;
                    el.menuBOList.forEach(item_3 => {
                      item_3.childList = item_3.menuBOList;
                      item_3.rightType = item_3.menuType == 1 ? '5' : '0';
                    });
                  }
                });
              }
            });
            this['treeData_' + clerkType] = deepClone(dealTreeData);
            if (clerkType == 0) {
              this.treeData = deepClone(this.treeData_0);
            }
            this['copyMenu_' + clerkType] = deepClone(this['treeData_' + clerkType]);
            this.getQueryMenuList(clerkType);
          } else {
            this['treeData_' + clerkType] = [];
            this.treeData = [];
          }
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 递归过滤
    filterTreeData(column, text) {
      let newColumn = column.filter(item => item.ownerShipArr.includes(text));
      newColumn.forEach(x => x.menuBOList && (x.menuBOList = this.filterTreeData(x.menuBOList, text)));
      return newColumn;
    },
    // 保存
    submit: _debounce(function() {
      let currentChooseList = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());
      this['withoutParents_' + this.activeNum] = [...currentChooseList];
      this['saveWithoutParents_' + this.activeNum] = [...currentChooseList];

      let errFlag_0 = this.withoutParents_0.length ? true : false;
      let errFlag_1 = this.withoutParents_1.length ? true : false;
      let errFlag_2 = this.withoutParents_2.length ? true : false;
      // let delMenu_0 = getArrDifference(this.curMenuCode_0, this.withoutParents_0);
      // let delMenu_1 = getArrDifference(this.curMenuCode_1, this.withoutParents_1);
      // let delMenu_2 = getArrDifference(this.curMenuCode_2, this.withoutParents_2);
      let delMenu_0 = getArrDifference(this.curMenuCode_0, this.saveWithoutParents_0);
      let delMenu_1 = getArrDifference(this.curMenuCode_1, this.saveWithoutParents_1);
      let delMenu_2 = getArrDifference(this.curMenuCode_2, this.saveWithoutParents_2);

      let addMenu_0 = getDelOrAddDate(this.saveWithoutParents_0, this.curMenuCode_0);
      let addMenu_1 = getDelOrAddDate(this.saveWithoutParents_1, this.curMenuCode_1);
      let addMenu_2 = getDelOrAddDate(this.saveWithoutParents_2, this.curMenuCode_2);

      if (!errFlag_0 || !errFlag_1 || !errFlag_2) {
        this.$set(this.titleList[0], 'isEmpty', !errFlag_0);
        this.$set(this.titleList[1], 'isEmpty', !errFlag_1);
        this.$set(this.titleList[2], 'isEmpty', !errFlag_2);
        this.isShowErrorTip = true;
        return;
      }
      let para = {
        clerkMenus: {
          roleId: this.roleId_0,
          clerkType: 0, // 导购
          // menuCodes: [...this.withoutParents_0], // 权限id
          menuCodes: [...this.saveWithoutParents_0], // 权限id
          delMenuCodes: delMenu_0, // 删除的code
          addMenuCodes: addMenu_0 // 新增的code
        },
        manegeClerkMenus: {
          roleId: this.roleId_1,
          clerkType: 1, // 店长
          // menuCodes: [...this.withoutParents_1],
          menuCodes: [...this.saveWithoutParents_1],
          delMenuCodes: delMenu_1,
          addMenuCodes: addMenu_1
        },
        managerMenus: {
          roleId: this.roleId_2,
          clerkType: 2, // 区经
          // menuCodes: [...this.withoutParents_2],
          menuCodes: [...this.saveWithoutParents_2],
          delMenuCodes: delMenu_2,
          addMenuCodes: addMenu_2
        }
      };
      postJsonRequest('/haoban-manage3-web/role/edit', para).then(async res => {
        let data = res.data;
        if (data.code == 0) {
          this.$message.success(res.data.message);
          this.activeNum = 0;
          this.treeData = [];
          this.withoutParents = [];
          // 重置校验
          this.$set(this.titleList[0], 'isEmpty', false);
          this.$set(this.titleList[1], 'isEmpty', false);
          this.$set(this.titleList[2], 'isEmpty', false);
          this.isShowErrorTip = false;
          await this.getMenuRoleList(0);
          await this.getMenuRoleList(1);
          await this.getMenuRoleList(2);
        } else {
          this.$message.warning(data.message);
        }
      });
    }, 500)
  }
};
</script>
<style lang="scss">
.auth-tree .iconfont.auth-expanded {
  font-family: 'element-icons' !important;
}
.auth-tree .el-tree-node__expand-icon.auth-tree-arrow {
  font-family: 'element-icons' !important;
}
</style>
<style lang="less" scoped>
.rule-form {
  padding-bottom: 60px;
}
.el-icon-warning {
  width: 12px;
  font-size: 12px;
  color: #fa8c16;
}

.m-l-9 {
  margin-left: 9px;
}

.p-l-26 {
  padding-left: 26px;
}

.p-r-211 {
  padding-right: 211px;
}

.F-S-14 {
  font-size: 14px;
}

.F-S-12 {
  font-size: 12px;
}

.F-C-BLACK {
  color: #303133;
}

.border-radio-2 {
  border-radius: 2px;
}

.dis-f {
  display: flex;
}

.p-t-30 {
  padding-top: 30px;
}

.damolish .el-button {
  padding: 8px 26px;
}

.dis-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.app-detail-wrap {
  height: 100%;
  background: #fff;
  .title-wrap {
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 4px 13px 4px 4px;
    width: 201px;
    height: 32px;
    /* transform: translateY(-5px); */
    border: 1px solid #dcdfe6;
    background: #ffffff;
    .tag-wrap {
      padding: 0px 10px;
      height: 24px;
    }
    .checked-status {
      background: #ebeffe;
      color: #2f54eb;
    }

    .empted-status {
      color: #f5222d;
      background: rgba(245, 34, 45, 0.11);
    }
  }
  .error-tip {
    display: flex;
    align-items: center;
    width: 129px;
    padding: 4px 0px 4px 17px;
    height: 32px;
    margin-left: 8px;
    background: #fcf6f1;
  }
  .right-config {
    font-size: 14px;
    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 50px;
      box-sizing: border-box;
      padding: 15px 20px 15px 30px;
      color: #303133;
      border: 1px solid #e4e7ed;
      p {
        font-weight: 600;
      }
    }
  }
}
/*  权限设置 */
.account-limit-wrap {
  font-size: 0px;
  .limit-item {
    display: flex;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-bottom: 10px;
    .fl-item {
      flex: 0 0 225px;
      width: 225px;
      background: rgb(246, 246, 246);
      border-right: 1px solid #dcdfe6;
      font-size: 16px;
      font-weight: 500;
      display: flex;
      justify-content: center;
      align-items: center;
      .opr-icon {
        color: #919191;
        font-size: 13px;
        padding: 6px 3px 3px;
        margin-right: 12px;
        cursor: pointer;
      }
    }
    .fr-item {
      flex: 1;
      width: 100%;
      color: #595959;
      .item-title {
        height: 45px;
        line-height: 45px;
        padding-left: 20px;
        font-weight: 500;
        background: rgb(246, 246, 246);
      }
    }
  }
}
.expend {
  height: auto;
}
.right-wrap_ {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.fixed-save-btn {
  position: fixed;
  display: flex;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  align-items: center;
  justify-content: center;
  bottom: 0;
  width: calc(100% - 206px);
  height: 56px;
  background: #ffffff;
  box-shadow: 1px -2px 8px 0px rgba(220, 223, 230, 0.6);
  z-index: 100;
}
</style>
