<template>
  <div class="app-container">
    <el-container style="height: 100%; border: 1px solid #eee" v-loading="loading">
      <el-aside
        width="400px"
        style="
          background-color: transparent;
          border-right: 1px solid #eee;
          margin: 0;
          padding-top: 40px;
        "
      >
        <el-table
          ref="singleTable"
          :data="roleList"
          highlight-current-row
          @current-change="handleCurrentChange"
          :show-header="false"
          border
        >
          <el-table-column align="center" property="roleName" label="角色名称" />
          <template slot="append">
            <div
              @click="handleAddRole"
              style="
                height: 44px;
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
              "
            >
              <i class="el-icon-plus mr5" style="color: #1890ff"></i>
              <el-button type="text">新增角色</el-button>
            </div>
          </template>
        </el-table>
      </el-aside>

      <el-container>
        <el-header height="auto">
          <div class="sf-title mt10">角色信息</div>
          <el-table :data="currentRole ? [currentRole] : []" border>
            <el-table-column align="center" property="id" label="角色ID" />
            <el-table-column align="center" property="roleName" label="角色名称" />
            <el-table-column align="center" property="status" label="状态">
              <template slot-scope="scope">
                {{ ROLE_STATUS.getLabelByValue(scope.row.status) }}
              </template>
            </el-table-column>
            <el-table-column align="center" property="createTime" label="创建时间" />
            <el-table-column align="center" property="updateTime" label="最后编辑时间" />
            <el-table-column
              align="center"
              label="操作"
              class-name="small-padding fixed-width"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleEditRole(scope.row)">
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-header>

        <el-main>
          <div class="sf-title">分配功能权限</div>
          <el-table :data="tableData" border row-key="id" :span-method="mergeTable">
            <el-table-column align="center" property="moduleName" label="模块" />
            <el-table-column align="center" property="firstName" label="一级功能" />
            <el-table-column align="center" property="secondName" label="二级功能" />
          </el-table>
        </el-main>
      </el-container>
    </el-container>
    <CrudPopup ref="crud" />
  </div>
</template>

<script>
import ApiButton from "@/components/ApiButton/index.vue";
import CrudPopup from "../roleList/components/CrudPopup/index.vue";
import { getRoleAllList } 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 {
  name: "RoleDetail",
  components: {
    ApiButton,
    CrudPopup,
  },
  data() {
    return {
      ROLE_STATUS,
      loading: false,
      roleList: [],
      currentRole: null,
      doctorWorkPers: [],
      saleManagePers: [],
      saleProcessPers: [],
      doctorWorkMenus: [],
      saleManageMenus: [],
      saleProcessMenus: [],
      tableData: [],
      treeData: [],
    };
  },
  created() {
    this.init();
  },
  watch: {
    currentRole(val) {
      if (val?.id) {
        this.loadMenuIdList(val.id);
      }
    },
  },
  methods: {
    async init() {
      this.loading = true;
      Promise.all([this.loadRoleList(), this.loadTreeList()]).finally(() => {
        this.loading = false;
      });
    },
    loadRoleList() {
      return getRoleAllList().then((res) => {
        console.log("getRoleAllList=", res);
        this.roleList = res.data;
        let selectRole;
        if (this.currentRole) {
          selectRole = this.roleList.find((item) => item.id === this.currentRole.id);
        }
        this.$nextTick(() => {
          this.$refs.singleTable.setCurrentRow(selectRole || res.data[0]);
        });
      });
    },
    loadTreeList() {
      return geMenuTreeList().then((res) => {
        this.doctorWorkMenus = res?.data?.doctorWork || [];
        this.saleManageMenus = res?.data?.saleManage || [];
        this.saleProcessMenus = res?.data?.saleProcess || [];
      });
    },
    async loadMenuIdList() {
      const [err, res] = await to(getRoleMenuList({ roleId: this.currentRole.id }));
      if (!err) {
        this.doctorWorkPers = res?.data?.doctorWork || [];
        this.saleManagePers = res?.data?.saleManage || [];
        this.saleProcessPers = res?.data?.saleProcess || [];
        this.tableData = this.packageTableData();
      } else {
        this.doctorWorkPers = [];
        this.saleManagePers = [];
        this.saleProcessPers = [];
        this.permissionTableData = [];
        this.tableData = [];
      }
      console.log("getRoleMenuList=", res);
    },
    handleCurrentChange(item) {
      this.currentRole = item;
    },
    // 新增角色
    handleAddRole() {
      this.$refs.crud.open({}).then((res) => {
        this.currentRole = res;
        this.loadRoleList();
      });
    },
    // 编辑角色
    handleEditRole() {
      this.$refs.crud
        .open({
          ...this.currentRole,
        })
        .then(this.loadRoleList);
    },
    packageTableData: (() => {
      let tableData = [];
      let doctorWorkData = [];
      let saleManageData = [];
      let saleProcessData = [];
      return function () {
        tableData = [];
        doctorWorkData = [];
        saleManageData = [];
        saleProcessData = [];
        if (this.doctorWorkMenus?.length > 0) {
          this.doctorWorkMenus?.forEach((item) => {
            let sChildren = [];
            const { children = [], menuName: firstName, ...otherItem } = item;
            (children || []).forEach((item2, index2) => {
              const { menuName: secondName, id } = item2;
              if (!this.doctorWorkPers.includes(id)) {
                return;
              }
              let pushItem = {
                id,
                firstName,
                secondName,
              };
              sChildren.push(pushItem);
            });
            if (sChildren?.length > 0) {
              sChildren[0].rowspan2 = sChildren.length;
            }
            doctorWorkData = [...doctorWorkData, ...sChildren];
          });
        }
        if (doctorWorkData.length > 0) {
          doctorWorkData[0].rowspan = doctorWorkData.length;
          doctorWorkData[0].moduleName = "随访中心";
        }

        if (this.saleManageMenus?.length > 0) {
          this.saleManageMenus.forEach((item) => {
            let sChildren = [];
            const { children = [], menuName: firstName, ...otherItem } = item;
            (children || []).forEach((item2, index2) => {
              const { menuName: secondName, id } = item2;
              if (!this.saleManagePers.includes(id)) {
                return;
              }
              let pushItem = {
                id,
                firstName,
                secondName,
              };
              sChildren.push(pushItem);
            });
            if (sChildren?.length > 0) {
              sChildren[0].rowspan2 = sChildren.length;
            }
            saleManageData = [...saleManageData, ...sChildren];
          });
        }
        if (saleManageData.length > 0) {
          saleManageData[0].rowspan = saleManageData.length;
          saleManageData[0].moduleName = "营销中心-管理层";
        }

        if (this.saleProcessMenus?.length > 0) {
          this.saleProcessMenus.forEach((item) => {
            let sChildren = [];
            const { children = [], menuName: firstName, ...otherItem } = item;
            (children || []).forEach((item2, index2) => {
              const { menuName: secondName, id } = item2;
              if (!this.saleProcessPers.includes(id)) {
                return;
              }
              let pushItem = {
                id,
                firstName,
                secondName,
              };
              sChildren.push(pushItem);
            });
            if (sChildren?.length > 0) {
              sChildren[0].rowspan2 = sChildren.length;
            }
            saleProcessData = [...saleProcessData, ...sChildren];
          });
        }
        if (saleProcessData.length > 0) {
          saleProcessData[0].rowspan = saleManageData.length;
          saleProcessData[0].moduleName = "营销中心-执行层";
        }
        tableData = [...doctorWorkData, ...saleManageData, ...saleProcessData];
        return tableData;
      };
    })(),
    mergeTable({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        return {
          rowspan: row.rowspan ? row.rowspan : 0,
          colspan: 1,
        };
      } else if (columnIndex === 1) {
        return {
          rowspan: row.rowspan2 ? row.rowspan2 : 0,
          colspan: 1,
        };
      } else {
        return {
          rowspan: 1,
          colspan: 1,
        };
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  height: 100%;
}
</style>
