<template>
  <div class="page-wrapper systerm-add">
    <div class="page-container">
      <a-collapse
        v-model="activeName"
        :bordered="false"
        expand-icon-position="right"
        class="header"
      >
        <a-collapse-panel key="a" :header="$t('BASE_INFO')">
          <a-form-model ref="addForm" :model="addForm">
            <a-row>
              <a-col :span="8">
                <a-form-model-item
                  prop="roleCode"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :rules="{
                    max: 32,
                    message: $t('PLACEENTER') + 32 + $t('LENGTH_TIP'),
                    trigger: 'blur',
                  }"
                  :label="$t('ROLE_CODE')"
                >
                  <a-input v-model="addForm.roleCode" allow-clear />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="roleName"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :rules="{
                    required: true,
                    message: $t('PLACEENTER'),
                    trigger: 'blur',
                  }"
                  :label="$t('ROLE_NAME')"
                >
                  <a-input v-model="addForm.roleName" allow-clear />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="roleCategory"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :label="$t('ROLE_CATEGORY')"
                >
                  <a-select
                    v-model="addForm.roleCategory"
                    :placeholder="$t('PLACESELECT')"
                  >
                    <a-select-option
                      v-for="item in roleCategoryArr"
                      :key="item.value"
                      :value="item.value"
                      >{{ item.label }}</a-select-option
                    >
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col>
                <a-form-model-item
                  :label-col="{ span: 2 }"
                  :wrapper-col="{ span: 22 }"
                  :label="$t('REMARK')"
                  prop="remark"
                >
                  <a-input v-model="addForm.remark" type="textarea" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-collapse-panel>
      </a-collapse>
      <a-collapse
        v-model="activeNameB"
        :bordered="false"
        expand-icon-position="right"
        class="collapse-header-divide functionPermissionsContainer"
      >
        <a-collapse-panel key="b" :header="$t('RIGHT_INFO')">
          <div class="permission-tab">
            <span
              class="permission-tab-item"
              :class="[permissionType === 'MENU' && 'active']"
              @click="() => handlePermission('MENU')"
            >
              {{ $t("MENU_PERMISSIONS") }}
            </span>
            <!-- <span
              class="permission-tab-item"
              :class="[permissionType === 'BUTTON' && 'active']"
              @click="() => handlePermission('BUTTON')"
            >
              {{ $t("BUTTON_PERMISSIONS") }}
            </span> -->
          </div>
          <!-- 菜单权限 -->
          <a-tabs
            v-if="paneData.length > 0"
            v-show="permissionType === 'MENU'"
            tab-position="left"
          >
            <a-tab-pane
              v-for="(item, index) in paneData"
              :key="item.clientName"
              :tab="item.clientName"
              :force-render="true"
            >
              <a-tree
                :ref="'functionTree' + index"
                :key="item.clientName"
                node-key="code"
                class="functionTree"
                checkable
                :tree-data="item.menuData"
                :checked-keys="leafMenuIds[index] || []"
                @check="
                  (checkedKeys, info) =>
                    handleTreeChecked(checkedKeys, info, index)
                "
              >
              </a-tree>
            </a-tab-pane>
          </a-tabs>
          <!-- 按钮权限 -->
          <!-- <a-tabs
            v-if="buttonPermissionPaneData.length > 0"
            v-show="permissionType === 'BUTTON'"
            class="button-permission-pane"
            tab-position="left"
          >
            <a-tab-pane
              v-for="(item, index) in buttonPermissionPaneData"
              :key="item.clientName"
              :tab="item.clientName"
              :force-render="true"
            >
              <a-checkbox
                class="all-selected"
                :checked="item.checked"
                :indeterminate="item.indeterminate"
                @change="
                  (e) => handleCheckedPlatform(e.target.checked, index, item)
                "
              >
                {{ $t("ALL") }}
              </a-checkbox>

              <a-collapse :bordered="false">
                <template #expandIcon="props">
                  <a-icon
                    type="caret-right"
                    :rotate="props.isActive ? 90 : 0"
                  />
                </template>
                <a-collapse-panel
                  v-for="module in item.menuData"
                  :key="module.code"
                  :force-render="true"
                >
                  <div slot="extra" @click.stop>
                    <a-checkbox
                      :checked="module.checked"
                      :indeterminate="module.indeterminate"
                      @change="
                        (e) =>
                          handleCheckedModule(e.target.checked, index, module)
                      "
                    >
                      {{ module.title }}
                    </a-checkbox>
                  </div>
                  <span
                    v-for="button in module.children"
                    :key="button.code"
                    class="button-item"
                  >
                    <a-checkbox
                      :checked="button.checked"
                      :indeterminate="button.indeterminate"
                      @change="
                        (e) =>
                          handleCheckedButton(e.target.checked, index, button)
                      "
                    >
                      {{ button.title }}
                    </a-checkbox>
                  </span>
                </a-collapse-panel>
              </a-collapse>
            </a-tab-pane>
          </a-tabs> -->
        </a-collapse-panel>
      </a-collapse>
    </div>
    <div class="page-bottom-op">
      <a-button type="primary" @click="confirm">
        <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
      </a-button>
      <a-button @click="cancel">
        <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
      </a-button>
    </div>
  </div>
</template>

<script>
import { Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: {
    Icon,
  },
  data() {
    return {
      activeName: "a",
      activeNameB: "b",
      treeData: [],
      checked: false,
      paneData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      addForm: {
        menuIds: [],
        remark: "",
        roleCategory: "",
        roleCode: "",
        roleName: "",
      },
      // 菜单多颗树 选中的节点（半选和全选）每棵树的集合
      menuIds: [],
      // 菜单多颗树 所有叶子节点 code 的集合
      leafMenuIds: [],
      roleCategoryArr: [],
      permissionType: "MENU",
      // buttonPermissionPaneData: [],
    };
  },
  mounted() {
    this.initModuleTree();
  },
  methods: {
    // 初始化页面中的权限数据
    initModuleTree() {
      this.getDictByCode("DIC:CORE:SYS_ROLE_TYPE").then((res) => {
        this.roleCategoryArr = res.data.data;
      });
      const { id } = this.$route.query;
      if (id) {
        Promise.all([
          // 根据用户id获取data回显
          this.$axios.get(
            `${ApiConstant.PREFIX_CORE}/api/sys/role/get-by-id/${id}`
          ),
          // 获取菜单权限列表
          this.$axios.get(
            `${ApiConstant.PREFIX_CORE}/api/sys/menu/list-user-module-menu-tree`
          ),
        ]).then(([roleRes, response]) => {
          this.addForm = {
            ...roleRes.data.data,
            roleCode: "",
            roleName: "",
          };
          // 处理菜单数据
          const menuFn = (data, res = []) => {
            data.forEach((item) => {
              if (item?.menuData?.length) {
                res.push({
                  ...item,
                  menuData: [],
                });
                menuFn(item.menuData, res[res.length - 1].menuData);
              } else if (item?.children?.length) {
                res.push({
                  ...item,
                  key: item.code,
                  value: item.code,
                  title: this.$t(item.label),
                  children: [],
                });
                menuFn(item.children, res[res.length - 1].children);
              } else {
                res.push({
                  ...item,
                  key: item.code,
                  value: item.code,
                  title: this.$t(item.label),
                });
              }
            });
            return res;
          };
          this.paneData = menuFn(response.data.data);
          // 处理角色之前选中菜单权限数据
          this.paneData.forEach((e) => {
            const [leafArr, arr] = this.getSelectedData(
              e.menuData,
              this.addForm.menuIds
            );
            this.menuIds.push(arr);
            this.leafMenuIds.push(leafArr);
          });
          // // 处理按钮数据
          // const buttonFn = (data, res = [], parentCodes = [], level = 0) => {
          //   // eslint-disable-next-line no-param-reassign
          //   level += 1;
          //   data.forEach((item, index) => {
          //     if (item.menuData && item.menuData.length) {
          //       res[index] = {
          //         clientType: item.clientType,
          //         clientName: item.clientName,
          //         title: item.clientName,
          //         menuData: [],
          //       };
          //       item.menuData &&
          //         item.menuData.length &&
          //         buttonFn(
          //           item.menuData,
          //           res[index].menuData,
          //           parentCodes,
          //           level
          //         );
          //     } else if (level === 2) {
          //       res.push({
          //         code: item.code,
          //         label: item.label,
          //         title: this.$t(item.label),
          //         children: [],
          //       });
          //       item.children &&
          //         item.children.length &&
          //         buttonFn(
          //           item.children,
          //           res[res.length - 1].children,
          //           [item.code],
          //           level
          //         );
          //     } else if (item.children && item.children.length) {
          //       if (!parentCodes.includes(item.code)) {
          //         parentCodes.push(item.code);
          //       }
          //       buttonFn(item.children, res, parentCodes, level);
          //     } else if (item.menuType === "BUTTON") {
          //       const i = res.findIndex((e) => e.label === item.label);
          //       if (i > -1) {
          //         res[i].children.push({
          //           code: item.code,
          //           label: item.label,
          //           title: this.$t(item.label),
          //         });
          //         res[i].parentCodes = parentCodes;
          //       } else {
          //         res.push({
          //           label: item.label,
          //           title: this.$t(item.label),
          //           parentCodes,
          //           children: [
          //             {
          //               code: item.code,
          //               label: item.label,
          //               title: this.$t(item.label),
          //             },
          //           ],
          //         });
          //       }
          //     }
          //   });
          //   return res;
          // };
          // const data = buttonFn(response.data.data);
          // this.buttonPermissionPaneData = data.map((platform, index) => {
          //   // eslint-disable-next-line no-param-reassign
          //   platform.menuData = platform.menuData.filter((module) =>
          //     Boolean(module.children && module.children.length)
          //   );
          //   return platform;
          // });
          // // 按钮权限选中数据
          // this.buttonPermissionPaneData.forEach((item, index) => {
          //   this.handleChecked(index);
          // });
        });
      } else {
        // 获取菜单权限列表
        this.$axios
          .get(
            `${ApiConstant.PREFIX_CORE}/api/sys/menu/list-user-module-menu-tree`
          )
          .then((response) => {
            // 处理菜单数据
            const menuFn = (data, res = []) => {
              data.forEach((item) => {
                if (item?.menuData?.length) {
                  res.push({
                    ...item,
                    menuData: [],
                  });
                  menuFn(item.menuData, res[res.length - 1].menuData);
                } else if (item?.children?.length) {
                  res.push({
                    ...item,
                    key: item.code,
                    value: item.code,
                    title: this.$t(item.label),
                    children: [],
                  });
                  menuFn(item.children, res[res.length - 1].children);
                } else {
                  res.push({
                    ...item,
                    key: item.code,
                    value: item.code,
                    title: this.$t(item.label),
                  });
                }
              });
              return res;
            };
            this.paneData = menuFn(response.data.data);
            // // 处理按钮数据
            // const buttonFn = (data, res = [], parentCodes = [], level = 0) => {
            //   // eslint-disable-next-line no-param-reassign
            //   level += 1;
            //   data.forEach((item, index) => {
            //     if (item.menuData && item.menuData.length) {
            //       res[index] = {
            //         clientType: item.clientType,
            //         clientName: item.clientName,
            //         title: item.clientName,
            //         menuData: [],
            //       };
            //       item.menuData &&
            //         item.menuData.length &&
            //         buttonFn(
            //           item.menuData,
            //           res[index].menuData,
            //           parentCodes,
            //           level
            //         );
            //     } else if (level === 2) {
            //       res.push({
            //         code: item.code,
            //         label: item.label,
            //         title: this.$t(item.label),
            //         children: [],
            //       });
            //       item.children &&
            //         item.children.length &&
            //         buttonFn(
            //           item.children,
            //           res[res.length - 1].children,
            //           [item.code],
            //           level
            //         );
            //     } else if (item.children && item.children.length) {
            //       if (!parentCodes.includes(item.code)) {
            //         parentCodes.push(item.code);
            //       }
            //       buttonFn(item.children, res, parentCodes, level);
            //     } else if (item.menuType === "BUTTON") {
            //       const i = res.findIndex((e) => e.label === item.label);
            //       if (i > -1) {
            //         res[i].children.push({
            //           code: item.code,
            //           label: item.label,
            //           title: this.$t(item.label),
            //         });
            //         res[i].parentCodes = parentCodes;
            //       } else {
            //         res.push({
            //           label: item.label,
            //           title: this.$t(item.label),
            //           parentCodes,
            //           children: [
            //             {
            //               code: item.code,
            //               label: item.label,
            //               title: this.$t(item.label),
            //             },
            //           ],
            //         });
            //       }
            //     }
            //   });
            //   return res;
            // };
            // const data = buttonFn(response.data.data);
            // this.buttonPermissionPaneData = data.map((platform) => {
            //   // eslint-disable-next-line no-param-reassign
            //   platform.menuData = platform.menuData.filter((module) =>
            //     Boolean(module.children && module.children.length)
            //   );
            //   return platform;
            // });
          });
      }
    },
    // 权限信息 tab切换
    handlePermission(type) {
      this.permissionType = type;
    },
    // 单颗树选中全数据 得到 树选中叶子节点和选中所有节点)
    getSelectedData(data, selected, leafArr = [], arr = []) {
      data.forEach((item) => {
        selected.includes(item.code) && arr.push(item.code);
        // eslint-disable-next-line
        item.key = item.code;
        // eslint-disable-next-line
        item.value = item.code;
        // eslint-disable-next-line
        item.title = this.$t(item.label);
        if (item?.children?.length) {
          this.getSelectedData(item.children, selected, leafArr, arr);
        } else if (selected.includes(item.code)) {
          leafArr.push(item.code);
        }
      });
      return [leafArr, arr];
    },
    // 菜单权限tree点击
    handleTreeChecked(checkedKeys, info, index) {
      // 设置选中(全选和半选)数据
      this.$set(
        this.menuIds,
        index,
        [].concat(checkedKeys).concat(info?.halfCheckedKeys || [])
      );
      // 页面菜单权限树结构的选中数据(只有叶子节点code)
      const [leafArr] = this.getSelectedData(
        this.paneData[index].menuData,
        this.menuIds[index]
      );
      this.$set(this.leafMenuIds, index, leafArr);

      // this.handleChecked(index);
    },
    // 处理按钮权限选中状态
    // handleChecked(index) {
    //   const platform = this.buttonPermissionPaneData[index];
    //   // 根据选中数据 处理按钮权限中的选中状态
    //   platform.menuData.forEach((module) => {
    //     module?.children.forEach((button) => {
    //       const all = button.children?.every((item) =>
    //         this.menuIds[index].includes(item.code)
    //       );
    //       const some = button.children?.some((item) =>
    //         this.menuIds[index].includes(item.code)
    //       );

    //       if (all) {
    //         this.$set(button, "indeterminate", false);
    //         this.$set(button, "checked", true);
    //       } else if (some && !all) {
    //         this.$set(button, "indeterminate", true);
    //         this.$set(button, "checked", false);
    //       } else if (!some) {
    //         this.$set(button, "indeterminate", false);
    //         this.$set(button, "checked", false);
    //       }
    //     });

    //     const all = module.children?.every((item) => item.checked);
    //     const some = module.children?.some((item) => item.checked);
    //     if (!some) {
    //       const i = this.menuIds[index].findIndex((e) => e === module.code);
    //       i > -1 && this.menuIds[index].splice(i, 1);
    //     }
    //     this.$set(module, "checked", all);
    //     this.$set(
    //       module,
    //       "indeterminate",
    //       all
    //         ? false
    //         : module.children?.some((item) => item.checked) ||
    //             module.children?.some((item) => item.indeterminate)
    //     );
    //   });
    //   const all = platform.menuData?.every((item) => item.checked);
    //   this.$set(platform, "checked", all);
    //   this.$set(
    //     platform,
    //     "indeterminate",
    //     all
    //       ? false
    //       : platform.menuData?.some((item) => item.checked) ||
    //           platform.menuData?.some((item) => item.indeterminate)
    //   );
    // },
    // // 按钮全选 全选
    // handleCheckedPlatform(value, index, platform) {
    //   this.$set(platform, "checked", value);
    //   this.$set(platform, "indeterminate", false);
    //   platform.menuData.forEach((module) => {
    //     this.handleCheckedModule(value, index, module);
    //   });
    // },
    // // 按钮权限 模块点击
    // handleCheckedModule(value, index, module) {
    //   this.$set(module, "checked", value);
    //   this.$set(module, "indeterminate", false);
    //   module.children.forEach((button) => {
    //     this.handleCheckedButton(value, index, button);
    //   });
    // },
    // // 按钮权限 按钮点击
    // handleCheckedButton(value, index, button) {
    //   this.$set(button, "checked", value);
    //   this.$set(button, "indeterminate", false);
    //   // 处理按钮权限
    //   const list = button.children.map((item) => item.code) || [];
    //   // 处理按钮的层级菜单
    //   const levelList = button.parentCodes || [];

    //   if (typeof this.leafMenuIds[index] === "undefined") {
    //     this.$set(this.leafMenuIds, index, value ? [].concat(list) : []);
    //   } else {
    //     list.forEach((code) => {
    //       if (this.leafMenuIds[index].includes(code)) {
    //         if (!value) {
    //           const indexOfLeafCode = this.leafMenuIds[index].findIndex(
    //             (e) => e === code
    //           );
    //           indexOfLeafCode > -1 &&
    //             this.leafMenuIds[index].splice(indexOfLeafCode, 1);
    //         }
    //       } else if (value) {
    //         this.leafMenuIds[index].push(code);
    //       }
    //     });
    //   }
    //   if (typeof this.menuIds[index] === "undefined") {
    //     this.$set(
    //       this.menuIds,
    //       index,
    //       value ? [].concat(list).concat(levelList) : []
    //     );
    //   } else {
    //     list.forEach((code) => {
    //       if (this.menuIds[index].includes(code)) {
    //         if (!value) {
    //           const indexOfCode = this.menuIds[index].findIndex(
    //             (e) => e === code
    //           );
    //           indexOfCode > -1 && this.menuIds[index].splice(indexOfCode, 1);
    //         }
    //       } else if (value) {
    //         this.menuIds[index].push(code);
    //       }
    //     });
    //     levelList.forEach((code) => {
    //       value &&
    //         !this.menuIds[index].includes(code) &&
    //         this.menuIds[index].push(code);
    //     });
    //   }

    //   this.handleChecked(index);
    // },
    cancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: { path: "/upms/system/setting/role" },
        vm: this,
      });
    },
    confirm() {
      const params = { ...this.addForm };
      params.menuIds = [];
      this.menuIds.forEach((item) => {
        params.menuIds.push(...item);
      });
      params.id = null;
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$axios
            .post(`${ApiConstant.PREFIX_CORE}/api/sys/role`, params)
            .then((res) => {
              this.$message.success(this.$t("ADD_SUCCESS"));
              this.$store.dispatch("tagsView/jumpBeforeView", {
                to: { path: "/upms/system/setting/role" },
                vm: this,
              });
            });
        } else {
          this.$message.error(this.$t("REQUIRED_INFO"));
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import (optional, once) "@/theme/index.less";
.systerm-add {
  .permission-tab {
    border-bottom: 1px solid @border-color;
    &-item {
      position: relative;
      display: inline-block;
      height: 34px;
      cursor: pointer;
      &::after {
        content: "";
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 2px;
        background: transparent;
      }
      &:hover,
      &.active {
        color: @primary-color;
      }
    }
    .permission-tab-item + .permission-tab-item {
      margin-left: 20px;
    }
    .permission-tab-item.active::after {
      background: @primary-color;
    }
  }
  /deep/.ant-tabs {
    &-content {
      padding: 10px 15px 0;
    }
    &-bar {
      padding-top: 10px;
    }
    &-nav .ant-tabs-tab {
      text-align: left;
      &.ant-tabs-tab-active {
        background: @primary-1;
      }
    }
    &.button-permission-pane {
      .all-selected {
        padding-left: 28px;
      }
      .ant-collapse {
        &-header {
          padding: 4px 0 4px 28px;
        }
        &-arrow {
          color: @text-color;
          font-size: 12px;
        }
        &-content {
          padding-left: 28px;
          .button-item {
            display: inline-block;
            width: 164px;
            margin-bottom: 6px;
          }
        }
        &-extra {
          float: none;
        }
      }
    }
  }
}
</style>
