<template>
  <div class="roles-total-wrapper">
    <div class="tools-wrapper">
      <el-button type="primary" @click="addRoleDialogShow">新增</el-button>
      <el-button type="warning" :disabled="!(curSelection.length===1)" @click="editRoleDialogShow">编辑</el-button>
      <el-button type="danger" @click="deleteRoles">删除</el-button>
    </div>
    <el-row>
      <el-col :span="10">
        <div class="table-wrapper">
          <el-table
            ref="multipleTable"
            :data="curRoles"
            highlight-current-row
            @current-change="handleCurrentChange"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column
              label="角色名称"
              prop="name"
            />
            <el-table-column
              label="权限等级"
              prop="level"
            />
            <el-table-column
              label="描述"
              prop="description"
            />
          </el-table>
        </div>
      </el-col>
      <el-col :span="8">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu"
            >保存菜单</el-button>
          </div>
          <div class="checks-wrapper">
            <!-- <div v-for="item in curMe" class="checks"></div> -->
            <el-tree ref="menuref" :data="curMenus" :props="defaultProps" show-checkbox node-key="id" />
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配区域" placement="top">
              <span class="role-span">区域分配</span>
            </el-tooltip>
            <el-button
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveRegion"
            >保存区域</el-button>
          </div>
          <div class="checks-wrapper">
            <div v-for="item in curRegion" :key="item.region" class="checks">
              <input type="checkbox" :checked="item.checked" @input="regioninput($event,item)">{{ '&nbsp;&nbsp;' + item.region }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      title="新增角色"
      :visible.sync="addRoleVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="formInfo">
        <el-form-item
          label="角色名称"
          prop="name"
        >
          <el-input v-model="formInfo.name" />
        </el-form-item>
        <el-form-item
          label="权限等级"
          prop="level"
        >
          <el-input v-model="formInfo.level" type="number" />
        </el-form-item>
        <el-form-item
          label="权限描述"
          prop="description"
        >
          <el-input v-model="formInfo.description" />
        </el-form-item>
        <el-form-item
          label="区域"
        >
          <el-select v-model="formInfo.roleArea" multiple placeholder="请选择">
            <el-option
              v-for="item in regions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRoleVisible = false">取消</el-button>
        <el-button type="primary" @click="addRoleConfirm">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="formInfo">
        <el-form-item
          label="角色名称"
          prop="name"
        >
          <el-input v-model="formInfo.name" />
        </el-form-item>
        <el-form-item
          label="权限等级"
          prop="level"
        >
          <el-input v-model="formInfo.level" type="number" />
        </el-form-item>
        <el-form-item
          label="权限描述"
          prop="description"
        >
          <el-input v-model="formInfo.description" />
        </el-form-item>
        <el-form-item
          label="区域"
        >
          <el-select v-model="formInfo.roleArea" multiple placeholder="请选择">
            <el-option
              v-for="item in regions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editRoleVisible = false">取消</el-button>
        <el-button type="primary" @click="editRoleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAll } from '@/api/system/role'
// import { addRole, editRole, deleteRole } from '../../../api/industry.js'
import { addRole, editRole, deleteRole, getMenus, getSubMenus, putRolesMenu } from '../../../api/industry.js'
export default {
  data() {
    return {
      // 所有的角色
      curRoles: [],
      // 威海(暂时)所有的区域
      curRegion: [],
      regions: ['环翠区', '威海经济技术开发区', '威海火炬高技术产业开发区', '威海临港经济技术开发区', '文登区', '荣成市', '乳山市', '南海区'],
      // 当前选中的角色
      curSelection: [],
      // 当前的row
      currentRow: null,
      // 新增角色显示
      addRoleVisible: false,
      // 编辑角色显示
      editRoleVisible: false,
      formInfo: {
        // 权限等级
        level: 1,
        // 权限描述
        description: '',
        // 角色名称
        name: '',
        // 当前区域
        roleArea: ''
      },
      // 待分配的菜单
      curMenus: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // defaultExpandKeys
      defaultExpandKeys: []
    }
  },
  mounted() {
    // 获取所有角色
    this.initGetAllrole()
    // 获取所有区域
    this.initGetAllRegion()
    // 获取所有菜单
    this.initAllMenu()
  },
  methods: {
    // 初始化所有角色
    async initGetAllrole() {
      await getAll().then(res => {
        this.curRoles = [...res]
        console.log('查看当前所有角色的信息', res)
      })
    },
    // 初始化所有菜单
    async initAllMenu() {
      let replaceMenu = []
      await getMenus().then(res => {
        replaceMenu = res.content
      })
      for (let i = 0; i < replaceMenu.length; i++) {
        // if (replaceMenu[i].hasChildren) {
        //   this.recursiveGetSubMenu(replaceMenu[i].id, replaceMenu[i])
        // }
        await this.recursiveGetSubMenu(replaceMenu[i])
      }
      this.curMenus = replaceMenu
      console.log(this.curMenus, 'this.curMenus, this.curMenus, this.curMenus')
    },
    // 不需要递归，直接获取下一层的子菜单
    async recursiveGetSubMenu(topmenu) {
      if (topmenu.hasChildren) {
        await getSubMenus(topmenu.id).then(res => {
          topmenu.children = res.content
          for (const item of topmenu.children) {
            this.recursiveGetSubMenu(item)
          }
        })
      }
    },
    // 初始化所有区域
    async initGetAllRegion() {
      this.curRegion = []
      const curRegion = ['环翠区', '威海经济技术开发区', '威海火炬高技术产业开发区', '威海临港经济技术开发区', '文登区', '荣成市', '乳山市', '南海区']
      for (let i = 0; i < curRegion.length; i++) {
        this.curRegion.push({
          region: curRegion[i],
          checked: false
        })
      }
    },
    // 选择selection
    handleSelectionChange(val) {
      this.curSelection = val
    },
    // 显示新增对话框
    addRoleDialogShow() {
      this.addRoleVisible = true
    },
    // 显示编辑对话框
    editRoleDialogShow() {
      // RoleVisible
      this.editRoleVisible = true
      // 先把所有数据赋值到formInfo
      this.formInfo = this.curSelection[0]
    },
    // 删除选中的角色
    deleteRoles() {
      this.$confirm('此操作不可逆, 确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(
        () => {
          // 获取当前被选中的角色
          this.curSelection
          deleteRole(this.curSelection.map(item => item.id)).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.initGetAllrole()
          }, () => {
            this.$message.error('删除失败')
          })
        }
      )
    },
    // 当前选中被更改
    handleCurrentChange(val) {
      this.currentRow = val
      // 更新右边的区域
      // 先将右边的区域初始化为0
      this.curRegion.forEach(item => {
        item.checked = false
      })
      // 上面是开始设置角色的菜单
      console.log(this.currentRow, '角色的菜单')
      const replaceMenuids = []
      this.currentRow.menus.forEach(item => {
        replaceMenuids.push(item.id)
      })
      // console.log(replaceMenuids, 'currentId,helloworld,fucktheworld')
      // 调用setChecked选中已经有过的menuid
      this.$refs.menuref.setCheckedKeys(replaceMenuids)
      console.log('默认展开的ids', replaceMenuids)
      this.defaultExpandKeys = replaceMenuids
      // 下面开始设置角色的区域
      if (!this.currentRow.roleArea) return
      if (this.currentRow.roleArea.length > 2) {
        // const replaceRoleArea =  this.currentRow.roleArea.splice(1, this.currentRow.roleArea.length - 2)
        // const su
        // console.log(JSON.parse(this.currentRow.roleArea))
        // const roleAreaArray = JSON.parse(this.currentRow.roleArea)
        const roleAreaArray = this.currentRow.roleArea.split(',')
        this.curRegion.forEach(item => {
          if (roleAreaArray.includes(item.region)) {
            item.checked = true
          }
        })
      }
    },
    // 点击保存区域
    saveRegion() {
      // 点击保存区域
      console.log('saveRegion', '保存当前区域')
      // 从curSelection中获取当前的row
      if (this.currentRow) {
        // console.log(this.currentRow, 'currentRow')
        // console.log('format helloworld', this.curRegion.filter(item => item.checked).map(item => item.region).join(','))
        editRole(this.currentRow, this.curRegion.filter(item => item.checked).map(item => item.region).join(',')).then(res => {
          console.log(res, 'helloworld')
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.initGetAllrole()
          // this.initGetAllRegion()
        }, () => {
          this.$message.error('保存失败')
        })
      }
    },
    // 单个区域input事件
    regioninput(event, item) {
      console.log(item, event)
      item.checked = !item.checked
    },
    // 提交添加角色
    addRoleConfirm() {
      // 提交添加角色
      // 调用接口添加角色并且刷新当前所有角色
      this.addRoleVisible = false
      addRole(this.formInfo.name, this.formInfo.level, this.formInfo.roleArea.join(','), this.formInfo.description).then(res => {
        this.$message({
          message: '添加成功',
          type: 'success'
        })
        this.initGetAllrole()
      }, () => {
        this.$message.error('添加失败')
      })
    },
    // 编辑角色添加
    editRoleConfirm() {
      console.log('hello world edit role')
      console.log(this.curSelection[0].roleArea, 'wokankanshenmegeshi')
      // 上传数据
      this.editRoleVisible = false
      editRole(this.formInfo, this.formInfo.roleArea.join(',')).then(res => {
        this.$message({
          message: '编辑成功',
          type: 'success'
        })
        this.initGetAllrole()
      }, () => {
        this.$message.error('编辑失败')
      })
    },
    // 获取菜单Node
    saveMenu() {
      console.log('这样还会出问题吗', 'what the fuck')
      console.log(this.$refs.menuref.getCheckedKeys(), 'getCheckedKeys')
      // 修改角色菜单
      // 判断是否有当前row
      if (!this.currentRow) {
        this.$message.error('请选择当前角色')
        return
      }
      // 获取当前选择的menus
      const replacemenus = []
      const cardMenus = this.$refs.menuref.getCheckedKeys()
      const recursiveCurMenus = (item) => {
        if (cardMenus.includes(item.id)) {
          replacemenus.push({ ...item, children: null })
        }
        if (item.hasChildren) {
          item.children.forEach(item1 => {
            recursiveCurMenus(item1)
          })
        }
      }
      this.curMenus.forEach(item => {
        recursiveCurMenus(item)
      })
      putRolesMenu(this.currentRow.id, this.currentRow.level, this.currentRow.dataScope, this.currentRow.description, replacemenus).then(res => {
        this.$message({
          message: '编辑角色菜单成功,正在为您刷新页面',
          type: 'success'
        })
        window.location.reload()
      }, (err) => {
        this.$message.error('编辑角色菜单失败' + err)
      })
      // putRolesMenu()
    }
  }
}
</script>

<style lang="scss">

</style>
