<template>
  <div class="detail-wrap">
    <el-form ref="editForm" :model="role">
      <div class="d-header clearfix">
        <div class="fl">
          <i class="el-icon-info" />
          {{ dataId ? $t1("查看用户角色") : $t1("新增用户角色") }}
        </div>
        <div class="fr">
          <el-button
            type="primary"
            plain
            class="button-sty"
            @click="$baseReload()"
            icon="el-icon-refresh-right"
          >
            {{ $t1("重置") }}
          </el-button>
          <el-button
            type="primary"
            class="button-sty"
            icon="el-icon-check"
            @click="saveData"
            >{{ $t1("保存") }}
          </el-button>
        </div>
      </div>
      <baseTabs>
        <baseTabPane :label="$t1('基本信息')">
          <template #default>
            <table class="table-detail">
              <tbody>
                <tr>
                  <th>
                    <em class="f-red">*</em>
                    {{ $t1("用户角色") }}
                  </th>
                  <td>
                    <el-form-item
                      prop="name"
                      :rules="[{ required: true, trigger: 'blur' }]"
                      v-if="!role.systems"
                    >
                      <el-input
                        type="text"
                        autocomplete="off"
                        v-model="role.name"
                        clearable
                      />
                    </el-form-item>
                    <template v-else>
                      {{ role.name }}
                    </template>
                  </td>
                  <th>{{ $t1("角色编码") }}</th>
                  <td>
                    <el-form-item
                      prop="code"
                      :rules="[{ required: false, trigger: 'blur' }]"
                      v-if="!dataId"
                    >
                      <el-input
                        type="text"
                        autocomplete="off"
                        v-model="role.code"
                        clearable
                      />
                    </el-form-item>
                    <template v-else>
                      {{ role.code }}
                    </template>
                  </td>
                  <th>{{ $t1("角色描述") }}</th>
                  <td>
                    <el-form-item
                      prop="description"
                      :rules="[{ required: false, trigger: 'blur' }]"
                    >
                      <el-input
                        type="text"
                        autocomplete="off"
                        v-model="role.description"
                        clearable
                      />
                    </el-form-item>
                  </td>
                  <th>{{ $t1("是否内置") }}</th>
                  <td>
                    <template v-if="role.systems">
                      {{ $t1("是") }}
                    </template>
                    <template v-else>
                      {{ $t1("否") }}
                    </template>
                  </td>
                </tr>
                <tr>
                  <th>{{ $t1("创建人") }}</th>
                  <td>{{ role.createBy }}</td>
                  <th>{{ $t1("创建时间") }}</th>
                  <td>{{ role.createDate }}</td>
                  <th>{{ $t1("更新人") }}</th>
                  <td>{{ role.modifyBy }}</td>
                  <th>{{ $t1("更新时间") }}</th>
                  <td>{{ role.modifyDate }}</td>
                </tr>
              </tbody>
            </table>
          </template>
        </baseTabPane>
        <baseTabPane :label="$t1('菜单信息')">
          <template #default>
            <div class="role-box">
              <div class="item" v-for="item in basicMenus" :key="item.id">
                <div class="t">
                  {{ item.menuName }}
                  <i
                    class="fr"
                    @click="$set(item, 'visibleRole', !item.visibleRole)"
                    :class="!item.visibleRole ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                  ></i>
                </div>
                <div class="c" :class="{ hide: item.visibleRole }">
                  <div v-for="subItem in item.children" :key="subItem.id">
                    <div class="c-2nd">
                      <el-checkbox
                        :label="subItem.menuName"
                        v-model="subItem.hasAuth"
                        @change="selectAll(subItem)"
                      ></el-checkbox>
                    </div>
                    <div class="c-3rd">
                      <div
                        class="c-item"
                        v-for="(thrItem, index3) in subItem.children"
                        :key="thrItem.id"
                      >
                        <div class="name">
                          <el-checkbox
                            :label="thrItem.menuName"
                            v-model="thrItem.hasAuth"
                            @change="cancelSelect(subItem, index3)"
                          ></el-checkbox>
                        </div>
                        <div class="c-4th">
                          <el-checkbox
                            v-for="(fourthItem, index4) in thrItem.children"
                            :key="fourthItem.id"
                            :label="fourthItem.menuName"
                            v-model="fourthItem.hasAuth"
                            @change="changeBtnSelect(subItem, index3, index4)"
                          ></el-checkbox>
                          <authConfig
                            v-if="thrItem.checkPermission"
                            :formData="thrItem"
                          ></authConfig>
                        </div>
                      </div>
                      <authConfig
                        v-if="subItem.checkPermission"
                        :formData="subItem"
                      ></authConfig>
                    </div>
                  </div>
                </div>
              </div>
              <div class="item">
                <div class="t">
                  {{ $t1("首页设置") }}
                  <i
                    class="fr"
                    @click="visibleHome = !visibleHome"
                    :class="!visibleHome ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                  ></i>
                </div>
                <div class="c" :class="{ hide: visibleHome }">
                  <div>
                    <div class="c-3rd">
                      <div class="c-item">
                        <el-checkbox
                          v-for="homeItem in homeMenus"
                          :key="homeItem.id"
                          :label="homeItem.menuName"
                          v-model="homeItem.hasAuth"
                          @change="$forceUpdate()"
                        ></el-checkbox>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </baseTabPane>
        <baseTabPane :label="$t1('移动端菜单信息')">
          <template #default>
            <div class="role-box">
              <div class="item" v-for="(item, index) in allMobileMenus" :key="index">
                <div class="t">
                  {{ item.menuName }}
                  <i
                    class="fr"
                    @click="$set(item, 'visibleRole', !item.visibleRole)"
                    :class="!item.visibleRole ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                  ></i>
                </div>
                <div class="c" :class="{ hide: item.visibleRole }">
                  <div>
                    <div class="c-2nd" style="width: 100%">
                      <el-checkbox
                        v-for="(subItem, index2) in item.children"
                        :key="index2"
                        :label="subItem.menuName"
                        v-model="subItem.hasAuth"
                        @change="selectAll(subItem)"
                      ></el-checkbox>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </baseTabPane>
      </baseTabs>
    </el-form>
  </div>
</template>

<script>
import authConfig from "./authConfig.vue";
export default {
  name: "roleEdit",
  props: ["_dataId"],
  components: {
    authConfig,
  },
  data() {
    return {
      tabIndex: 0,
      isEdit: false,
      dataId: "",
      role: {
        menus: [],
        mobileMenuIds: [],
        menuRolePermDTOs: [],
        menuRolePermOrgDTOs: [],
      },
      allMenus: [],
      allMobileMenus: [],
      showCompanyDialog: false,
      cParam: { selectMulti: false },
      visibleHome: false,
    };
  },
  computed: {
    basicMenus() {
      return this.allMenus.filter((menu) => menu.type != 2);
    },
    homeMenus() {
      return this.allMenus.filter((menu) => menu.type == 2);
    },
  },
  created() {
    if (this._dataId) this.dataId = this._dataId;
  },
  mounted() {
    var that = this;
    this.getData();
  },
  methods: {
    getData() {
      if (this.dataId) {
        this.isEdit = true;
        this.$commonHttp({
          url: USER_PREFIX + `/role/get`,
          method: `post`,
          data: {
            id: this.dataId,
          },
          isLoading: true,
          modalStrictly: true,
          success: (res) => {
            let role = res.objx || {};
            this.getPermissionData((rows, orgRows) => {
              role.menuRolePermDTOs = rows;
              role.menuRolePermOrgDTOs = orgRows;
              this.role = role;
              this.initMenuData();
            });
          },
        });
      } else {
        this.initMenuData();
      }
    },
    getPermissionData(callback) {
      this.$http({
        url: USER_PREFIX + `/menu_role_perm/listPerms`,
        method: `post`,
        data: {
          id: this.dataId,
        },
        isLoading: true,
        modalStrictly: true,
        success: (res) => {
          let rows = res.objx || [];
          this.getListPermOrgs((orgRows) => {
            callback(rows, orgRows);
          });
        },
      });
    },
    getListPermOrgs(callback) {
      this.$http({
        url: USER_PREFIX + `/menu_role_perm/listPermOrgs`,
        method: `post`,
        data: {
          id: this.dataId,
        },
        isLoading: true,
        modalStrictly: true,
        success: (res) => {
          let rows = res.objx || [];
          callback(rows);
        },
      });
    },
    saveData() {
      this.$refs.editForm.$baseValidate((valid) => {
        if (valid) {
          this.$baseConfirm(this.$t1("您确定要保存吗？")).then(() => {
            var url = USER_PREFIX + (this.isEdit ? `/role/update` : `/role/save`);
            let formData = this.role;
            formData.menuIds = this.getMenuFormData();
            formData.mobileMenuIds = this.getMobileMenuFormData();

            //处理权限数据
            this.handleDataBeforeSubmit();

            this.$http({
              url: url,
              method: `post`,
              data: formData,
              isLoading: true,
              success: (res) => {
                this.$message({
                  message: res.content,
                  type: "success",
                  duration: 500,
                  onClose: (t) => {
                    if (this.isEdit) {
                      this.$baseReload();
                    } else {
                      this.$baseReload({
                        updateParam: {
                          _dataId: res.objx,
                        },
                      });
                    }
                  },
                });
              },
            });
          });
        }
      });
    },
    initMenuData(menus) {
      this.$http({
        url: USER_PREFIX + "/menu/getAll",
        method: "POST",
        isLoading: true,
        modalStrictly: true,
        success: (res) => {
          let menus = res.objx || [];
          this.handleRoles(menus, this.role.menuIds || []);
          this.allMenus = menus;
        },
      });
      this.$http({
        url: USER_PREFIX + "/mobile_menu/getAll",
        method: "POST",
        isLoading: true,
        modalStrictly: true,
        success: (res) => {
          let menus = res.objx || [];
          this.handleMobileRoles(menus, this.role.mobileMenuIds || []);
          this.allMobileMenus = menus;
        },
      });
    },
    selectAll(subItem) {
      //subItem.hasAuth = !subItem.hasAuth;
      let res = subItem.hasAuth;
      if (subItem.children) {
        subItem.children.forEach(function (thrItem) {
          thrItem.hasAuth = res;
          if (thrItem.children) {
            thrItem.children.forEach(function (fourthItem) {
              fourthItem.hasAuth = res;
            });
          }
        });
      }
      this.$forceUpdate();
    },
    cancelSelect(subItem, index3) {
      let citem = subItem.children[index3];
      // citem.hasAuth = !citem.hasAuth;
      let res = citem.hasAuth;
      let isCheckSubItem = false;
      subItem.children.forEach(function (thrItem) {
        if (thrItem.hasAuth) {
          isCheckSubItem = true;
        }
      });
      if (citem.type !== 1) {
        subItem.hasAuth = isCheckSubItem;
      } else {
        if (isCheckSubItem) subItem.hasAuth = true;
      }

      if (citem.children) {
        citem.children.forEach(function (fourthItem) {
          fourthItem.hasAuth = res;
        });
      }
      this.$forceUpdate();
    },
    changeBtnSelect(subItem, index3, index4) {
      let citem = subItem.children[index3].children[index4];
      // citem.hasAuth = !citem.hasAuth;
      let res = citem.hasAuth;
      let isCheckthrItem = false;
      subItem.children[index3].children.forEach(function (fourthItem) {
        if (fourthItem.hasAuth) {
          isCheckthrItem = true;
        }
      });

      let isCheckSubItem = false;
      subItem.children.forEach(function (thrItem) {
        if (thrItem.hasAuth) {
          isCheckSubItem = true;
        }
      });
      subItem.hasAuth = isCheckSubItem;
      this.$forceUpdate();
    },
    getMenuFormData(item, menuRolePermDTOs, menuRolePermOrgDTOs) {
      let selectIds = [];
      let menus = this.allMenus;
      menus.forEach(function (item) {
        if (item.type != 2 || item.hasAuth) {
          selectIds.push(item.id);
        }
        if (item.children) {
          item.children.forEach(function (subItem) {
            if (subItem.hasAuth) {
              selectIds.push(subItem.id);
            }
            if (subItem.children) {
              subItem.children.forEach(function (thrItem) {
                if (thrItem.hasAuth) {
                  selectIds.push(thrItem.id);
                }
                if (thrItem.children) {
                  thrItem.children.forEach(function (fourthItem) {
                    if (fourthItem.hasAuth) {
                      selectIds.push(fourthItem.id);
                    }
                  });
                }
              });
            }
          });
        }
      });
      return selectIds;
    },
    handlePermission(item, menuRolePermDTOs, menuRolePermOrgDTOs) {
      if (item.checkPermission) {
        if (item.permissions) {
          menuRolePermDTOs.push({
            menus: item.id,
            permissions: item.permissions,
          });

          if (item.permissions === 2 && item.menuRolePermOrgDTOs.length) {
            menuRolePermOrgDTOs.push(...item.menuRolePermOrgDTOs);
          }
        }
      }
    },
    handleDataBeforeSubmit() {
      let menuRolePermDTOs = [];
      let menuRolePermOrgDTOs = [];
      let that = this;
      let menus = this.allMenus;
      menus.forEach(function (item) {
        that.handlePermission(item, menuRolePermDTOs, menuRolePermOrgDTOs);
        if (item.children) {
          item.children.forEach(function (subItem) {
            that.handlePermission(subItem, menuRolePermDTOs, menuRolePermOrgDTOs);
            if (subItem.children) {
              subItem.children.forEach(function (thrItem) {
                that.handlePermission(thrItem, menuRolePermDTOs, menuRolePermOrgDTOs);
              });
            }
          });
        }
      });
      this.role.menuRolePermDTOs = menuRolePermDTOs;
      this.role.menuRolePermOrgDTOs = menuRolePermOrgDTOs;
    },
    getMobileMenuFormData() {
      let selectIds = [];
      let menus = this.allMobileMenus;
      menus.forEach(function (item) {
        if (item.type != 2 || item.hasAuth) {
          selectIds.push(item.id);
        }
        if (item.children) {
          item.children.forEach(function (subItem) {
            if (subItem.hasAuth) {
              selectIds.push(subItem.id);
            }
            if (subItem.children) {
              subItem.children.forEach(function (thrItem) {
                if (thrItem.hasAuth) {
                  selectIds.push(thrItem.id);
                }
                if (thrItem.children) {
                  thrItem.children.forEach(function (fourthItem) {
                    if (fourthItem.hasAuth) {
                      selectIds.push(fourthItem.id);
                    }
                  });
                }
              });
            }
          });
        }
      });
      return selectIds;
    },
    handleRoles(rows, menuIds) {
      let menuRolePermDTOs = this.role.menuRolePermDTOs || [];
      let menuRolePermOrgDTOs = this.role.menuRolePermOrgDTOs || [];
      let newRows = [];
      for (let i = 0; i < rows.length; i++) {
        let row = rows[i];
        let permissions = null;
        let permOrgDTOs = [];
        if (row.checkPermission) {
          menuRolePermDTOs.find((item) => {
            if (item.menus == row.id) {
              permissions = item.permissions;
              return true;
            }
            return false;
          });

          menuRolePermOrgDTOs.forEach((item) => {
            if (item.menus == row.id) {
              permOrgDTOs.push(item);
            }
          });
        }

        row.permissions = permissions;
        row.menuRolePermOrgDTOs = permOrgDTOs;
        if (menuIds.includes(row.id)) {
          row.hasAuth = true;
        } else {
          row.hasAuth = false;
        }
        newRows.push(row);
        if (row.children) {
          let cRows = this.handleRoles(row.children, menuIds);
          if (cRows) {
            newRows = newRows.concat(cRows);
          }
        }
      }
      return newRows;
    },
    handleMobileRoles(rows, menuIds) {
      let newRows = [];
      for (let i = 0; i < rows.length; i++) {
        let row = rows[i];
        if (menuIds.includes(row.id)) {
          row.hasAuth = true;
        } else {
          row.hasAuth = false;
        }
        newRows.push(row);
        if (row.children) {
          let cRows = this.handleMobileRoles(row.children, menuIds);
          if (cRows) {
            newRows = newRows.concat(cRows);
          }
        }
      }
      return newRows;
    },
  },
};
</script>
