<template>
  <div>
    <el-drawer
      title="设置模块权限"
      :visible.sync="visible"
      direction="rtl"
      size="72%"
      append-to-body
      @close="$emit('update:isShow',false)">
      <div style="padding: 10px;"
           v-loading="loading"
           element-loading-text="拼命加载中"
           element-loading-spinner="el-icon-loading"
           element-loading-background="rgba(0, 0, 0, 0.8)">
        <el-tabs type="border-card" v-model="activeName">
          <el-tab-pane label="权限菜单" name="menu">
            <vxe-toolbar>
              <template #buttons>
                <el-button icon="el-icon-plus" type="primary" size="small" @click="isShowAddMenu = true">新增</el-button>
                <el-button icon="el-icon-search" type="primary" plain size="small" @click="getMenu">搜索</el-button>
              </template>
            </vxe-toolbar>
            <vxe-table
              style="margin-top: 10px;"
              ref="menuTable"
              keep-source
              :row-config="{ useKey: 'id', isHover: true }"
              :column-config="{ resizable: true }"
              :edit-rules="validMenuRules"
              :edit-config="{ trigger: 'manual', mode: 'row', showStatus: true, autoClear: false }"
              :tree-config="{ rowField: 'id', parentField: 'pid' }"
              :data="menus">
              <vxe-column type="seq" width="58" align="center"></vxe-column>
              <vxe-column field="name" tree-node width="160" title="菜单" :edit-render="{ name: 'input', attrs: { type: 'text'} }"></vxe-column>
              <vxe-column field="path" title="路由地址" min-width="140" :edit-render="{ name: 'input', attrs: { type: 'text'} }">
                <template #default="{ row }">
                  <template v-if="/#/g.test(row.path)">
                    <SvgIcon icon-class="folder" class-name="icon-folder"></SvgIcon>
                  </template>
                  <template v-else>
                    <span>{{ row.path }}</span>
                  </template>
                </template>
              </vxe-column>
              <vxe-column field="api_profix" min-width="140" title="api前缀" :edit-render="{ name: 'input', attrs: { type: 'text'} }">
                <template #default="{ row }">
                  <template v-if="/#/g.test(row.api_profix)">
                    <SvgIcon icon-class="folder" class-name="icon-folder"></SvgIcon>
                  </template>
                  <template v-else>
                    <span>{{ row.api_profix }}</span>
                  </template>
                </template>
              </vxe-column>
              <vxe-column field="visible" width="100" align="center" title="是否显示" :edit-render="{ name: 'select', options: [{ value: 1, label: '显示' },{ value: 0, label: '隐藏' }] }"></vxe-column>
              <vxe-column field="icon" width="160" align="center" title="图标" :edit-render="{ name: 'input', attrs: { type: 'text'} }">
                <template #default="{ row }">
                  <Icon :icon="row.icon"></Icon>
                </template>
              </vxe-column>
              <vxe-column field="sortnumber" width="80" title="排序" align="center" :edit-render="{ name: 'input', attrs: { type: 'number' } }"></vxe-column>
              <vxe-column field="operate" title="操作" min-width="240">
                <template #default="{ row }">
                  <template v-if="isActiveStatus(row,'menuTable')">
                    <el-button size="small" type="primary" @click="saveMenuRowEvent(row)">保存</el-button>
                    <el-button size="small" type="primary" plain @click="cancelRowEvent(row,'menuTable')">取消</el-button>
                  </template>
                  <template v-else>
                    <el-button size="small" type="success" @click="$refs['ModuleAuthAddMenu'].setPid(row.id),isShowAddMenu = true">子菜单</el-button>
                    <el-button size="small" type="warning" @click="editRowEvent(row,'menuTable')">编辑</el-button>
                    <el-button size="small" type="danger" @click="destroyMenuRowEvent(row)">删除</el-button>
                  </template>
                </template>
              </vxe-column>
            </vxe-table>
          </el-tab-pane>
          <el-tab-pane label="角色管理" name="role">
            <vxe-toolbar>
              <template #buttons>
                <el-button icon="el-icon-plus" type="primary" size="small" @click="isShowAddRole = true">新增</el-button>
                <el-button icon="el-icon-search" type="primary" plain size="small" @click="getRole">搜索</el-button>
              </template>
            </vxe-toolbar>
            <vxe-table
              stripe
              style="margin-top: 10px;"
              ref="roleTable"
              keep-source
              show-overflow
              :column-config="{ resizable: true }"
              :edit-rules="validRoleRules"
              :edit-config="{ trigger: 'manual', mode: 'row', showStatus: true, isHover: true, autoClear: false }"
              :data="roles">
              <vxe-column type="seq" width="58" align="center"></vxe-column>
              <vxe-column field="name" width="160" title="角色" :edit-render="{ name: 'input', attrs: { type: 'text'} }"></vxe-column>
              <vxe-column field="permissions" title="权限菜单" show-overflow="tooltip">
                <template #default="{ row }">
                  <div>
                    <el-tag v-for="item in row.permissions" :key="item.id">{{ item.name }}</el-tag>
                  </div>
                </template>
              </vxe-column>
              <vxe-column field="sortnumber" width="80" title="排序" align="center" :edit-render="{ name: 'input', attrs: { type: 'number' } }"></vxe-column>
              <vxe-column field="operate" title="操作" min-width="220">
                <template #default="{ row }">
                  <template v-if="isActiveStatus(row,'roleTable')">
                    <el-button size="small" type="primary" @click="saveRoleRowEvent(row)">保存</el-button>
                    <el-button size="small" type="primary" plain @click="cancelRowEvent(row,'roleTable')">取消</el-button>
                  </template>
                  <template v-else>
                    <el-button size="small" type="success" @click="bindPermission(row)">授权</el-button>
                    <el-button size="small" type="warning" @click="editRowEvent(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="destroyRoleRowEvent(row,'roleTable')">删除</el-button>
                  </template>
                </template>
              </vxe-column>
            </vxe-table>

            <p class="total" type="primary">共 {{ roleTotal }} 条数据</p>
          </el-tab-pane>
          <el-tab-pane label="用户授权" name="permission">
            <vxe-table
              stripe
              style="margin-top: 10px;"
              ref="table"
              :loading="loading"
              keep-source
              show-overflow
              :column-config="{ resizable: true }"
              :edit-config="{ trigger: 'manual', mode: 'row', showStatus: true, isHover: true, autoClear: false }"
              :data="users">
              <vxe-column type="seq" width="58" align="center"></vxe-column>
              <vxe-column field="name" width="140" title="姓名" :edit-render="{ name: 'input', attrs: { type: 'text'} }"></vxe-column>
              <vxe-column field="username" width="160" title="用户名" :edit-render="{ name: 'input', attrs: { type: 'text'} }"></vxe-column>
              <vxe-column field="module_roles" title="角色" min-width="200" show-overflow="tooltip">
                <template #default="{ row }">
                  <div>
                    <el-tag v-for="item in row.module_roles" :key="item.id">{{ item.name }}</el-tag>
                  </div>
                </template>
              </vxe-column>
              <vxe-column field="sortnumber" width="80" title="排序" align="center" :edit-render="{ name: 'input', attrs: { type: 'number' } }"></vxe-column>
              <vxe-column field="operate" title="操作" min-width="240">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="bindRole(row)">绑定角色</el-button>
                </template>
              </vxe-column>
            </vxe-table>

          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>

    <ModuleAuthAddMenu ref="ModuleAuthAddMenu" :is-show.sync="isShowAddMenu" :list="menus" :module-id="moduleId" @refresh="getMenu"></ModuleAuthAddMenu>
    <ModuleAuthAddRole ref="ModuleAuthAddRole" :is-show.sync="isShowAddRole" :module-id="moduleId" @refresh="getRole"></ModuleAuthAddRole>
    <ModuleAuthBindPermissions ref="ModuleAuthBindPermissions" :is-show.sync="isShowBindPermissions" :module-id="moduleId" @refresh="getRole"></ModuleAuthBindPermissions>
    <ModuleAuthBindRole ref="ModuleAuthBindRole" :is-show.sync="isShowBindRoles" :module-id="moduleId" @refresh="getUsers"></ModuleAuthBindRole>
  </div>
</template>

<script>
import SvgIcon from '@/components/SvgIcon/index.vue'
import ModuleAuthAddMenu from './ModuleAuthAddMenu.vue'
import ModuleAuthAddRole from './ModuleAuthAddRole.vue'
import Icon from "@/layout/components/Navbar/Icon.vue"
import ModuleAuthBindPermissions from './ModuleAuthBindPermissions.vue'
import ModuleAuthBindRole from './ModuleAuthBindRole.vue'
import { menu, menuSave, menuDestroy, role, roleDestroy, roleSave, grant } from '@/api/module'
import { deepCopy } from '@/utils'
export default {
  components: {
    Icon,
    ModuleAuthBindPermissions,
    ModuleAuthAddMenu,
    ModuleAuthAddRole,
    ModuleAuthBindRole,
    SvgIcon
  },
  props: {
    isShow: {
      type: Boolean,
      default: false,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      activeName: "menu",
      moduleId: "",
      visible: false,

      isShowAddMenu: false,
      menus: [],
      validMenuRules: {
        name: [
          { required: true, message: "请输入名称" }
        ],
        path: [
          { required: true, message: "请输入路由路径" },
        ],
        api_profix: [
          { required: true, message: "请输入api前缀" }
        ]
      },
      menuForm: {
        id: "",
        module_id: "",
        pid: "",
        name: "",
        url: "",
        path: "",
        api_profix: "",
        icon: "",
        visible: 1,
        sortnumber: 0
      },

      isShowAddRole: false,
      roles: [],
      roleTotal: 0,
      validRoleRules: {
        name: [
          { required: true, message: "请输入角色" }
        ]
      },
      roleForm: {
        id: "",
        module_id: "",
        name: "",
        sortnumber: 0
      },
      isShowBindPermissions: false,

      users: [],
      userTotal: 0,
      isShowBindRoles: false,
    }
  },
  methods: {
    bindPermission(row) {
      this.$refs['ModuleAuthBindPermissions'].setForm(['permission_id'],[row.permissions?.map(i => i.id)||[]])
      this.isShowBindPermissions = true
    },
    bindRole(row) {
      this.$refs['ModuleAuthBindRole'].setForm(['id','role_id'],[row.id,row.roles?.map(i => i.id)||[]])
      this.isShowBindRoles = true;
    },

    editRowEvent (row,table) {
      if (this.$refs[table]) {
        this.$refs[table].setEditRow(row)
      }
    },
    cancelRowEvent (row,table) {
      if (this.$refs[table]) {
        this.$refs[table].clearEdit().then(() => {
          // 还原行数据
          this.$refs[table].revertData(row)
        })
      }
    },

    setId(id) {
      this.moduleId = id
    },

    async getMenu() {
      this.loading = true;
      try {
        const res = await menu({
          with_root: 1,
          data_only: 1,
          module_id: this.moduleId
        })
        console.log(res)
        this.menus = res;
        this.loading = false;
      } catch (err) {
        console.error(err)
        this.loading = false;
      }
    },

    async saveMenuRowEvent (row) {
      try {
        await this.$confirm("确认保存？","提示",{
          confirmButtonText: "确认",
          cancelButtonText: "取消"
        })
        await this.$refs['menuTable'].clearEdit()
        let form = deepCopy(this.menuForm)
        for (let key in form) {
          form[key] = row[key]
        }
        this.loading = true;
        await menuSave(form)
        await this.getMenu();
        this.loading = false;
      } catch (err) {
        this.loading = false;
      }
    },
    async destroyMenuRowEvent (row) {
      try {
        await this.$confirm("确认删除？","提示",{
          confirmButtonText: "确认",
          cancelButtonText: "取消"
        })
        this.loading = true;
        if (row.id) {
          await menuDestroy({
            id: row.id
          })
          await this.getMenu();
        } else {
          this.menus.splice(this.menus.findIndex(i => i._X_ROW_KEY === row._X_ROW_KEY),1)
        }
        this.loading = false;
      } catch (err) {
        this.loading = false;
      }
    },


    async getRole() {
      this.loading = true;
      try {
        const res = await role({
          module_id: this.moduleId
        })
        console.log(res)
        this.roles = res.rows;
        this.roleTotal = res.total;
        this.loading = false;
      } catch (err) {
        console.error(err)
        this.loading = false;
      }
    },
    async saveRoleRowEvent (row) {
      try {
        await this.$confirm("确认保存？","提示",{
          confirmButtonText: "确认",
          cancelButtonText: "取消"
        })
        await this.$refs['menuTable'].clearEdit()
        let form = deepCopy(this.menuForm)
        for (let key in form) {
          form[key] = row[key]
        }
        this.loading = true;
        await roleSave(form)
        await this.getRole();
        this.loading = false;
      } catch (err) {
        this.loading = false;
      }
    },
    async destroyRoleRowEvent (row) {
      try {
        await this.$confirm("确认删除？","提示",{
          confirmButtonText: "确认",
          cancelButtonText: "取消"
        })
        this.loading = true;
        if (row.id) {
          await roleDestroy({
            id: row.id
          })
          await this.getRole();
        } else {
          this.roles.splice(this.roles.findIndex(i => i._X_ROW_KEY === row._X_ROW_KEY),1)
        }
        this.loading = false;
      } catch (err) {
        this.loading = false;
      }
    },

    async getUsers() {
      this.loading = true;
      try {
        const res = await grant()
        console.log(res)
        this.users = res.rows;
        this.userTotal = res.total;
        this.loading = false;
      } catch (err) {
        console.error(err)
        this.loading = false;
      }
    }
  },
  computed: {
    isActiveStatus () {
      return function (row,table) {
        if (this.$refs[table]) {
          return  this.$refs[table].isEditByRow(row)
        }
      }
    },
  },
  watch: {
    isShow(newVal) {
      this.visible = newVal;
      this.getMenu()
    },
    visible(newVal) {
      this.$emit('update:isShow', newVal);
    },
    activeName: {
      handler:function(newVal) {
        switch (newVal){
          case 'menu':
            this.getMenu()
            break;
          case 'role':
            this.getRole()
            break;
          case 'permission':
            this.getUsers()
            break;
        }
      }
    }
  },
  created() {
    this.getRole()
  }
}
</script>

<style scoped lang="scss">
.total {
  color: #666;
  text-align: right;
  line-height: 3;
}
::v-deep .el-tag + .el-tag {
  margin-left: 4px;
}
</style>
