<template>
  <div class="app-container">
    <el-row>
      <el-col :span="7">
        <el-card style="margin-bottom: 10px;height: 44px">
          <span style="line-height: 32px">请选择要分配的一级菜单</span>
          <!--          <el-button size="small" type="distribution" @click="addFisrtLevel">创建一级菜单</el-button>-->
        </el-card>
        <el-card>
          <div slot="header">
            <el-input v-model="filterTextLeft" size="small" placeholder="输入关键字进行过滤" clearable/>
          </div>
          <el-table ref="multipleTableLeft" :data="fisrtLevelFilter" stripe highlight-current-row size="mini" height="500" style="height:calc(100vh - 330px);" @selection-change="handleSelectionChangeLeft">
            <el-table-column :selectable="selectable" align="center" type="selection" width="55"/>
            <el-table-column type="index" align="center" width="60"/>
            <el-table-column align="center" label="模块名称">
              <template slot-scope="scope">
                {{ scope.row.title }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="1">
        <el-tooltip class="item" effect="dark" content="将选中一级菜单分配给该角色" placement="top-start">
          <el-button :disabled="!roleName || selectLeft.length === 0" size="mini" type="primary" icon="el-icon-right" style="margin: 300px auto 0 auto;display: block" @click="giveFirstLevel"/>
        </el-tooltip>
      </el-col>
      <el-col :span="8">
        <el-card style="margin-bottom: 10px">
          <span>角色:</span>
          <el-select v-model="roleName" placeholder="请选择" size="small" style="width:200px;margin-left:10px" filterable @change="getModule">
            <el-option
              v-for="item in roleNames"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-card>
        <el-card style="height: 550px;overflow: auto">
          <div slot="header">
            <el-input v-model="filterText" size="small" placeholder="输入关键字进行过滤" clearable/>
          </div>
          <el-tree ref="moduleTree" :data="moduleTree" :filter-node-method="filterNode" check-strictly class="moduleTree" show-checkbox node-key="id" default-expand-all @check-change="treeCheck">
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>
                <el-button
                  type="text"
                  size="mini"
                  @click="() => moveUp(node, data)">
                  上移
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="() => moveDown(node, data)">
                  下移
                </el-button>
                <el-button
                  :disabled="data.children && data.children.length!==0"
                  type="text"
                  size="mini"
                  @click="() => returnModule(node, data)">
                  移除
                </el-button>
              </span>
            </span>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="1">
        <el-tooltip class="item" effect="dark" content="将选中二级菜单分配给该角色选中的一级菜单" placement="top-start">
          <el-button :disabled="treeCheckList.length !== 1 || selectRight.length === 0 || treeCheckListJudge" size="mini" type="primary" icon="el-icon-back" style="margin: 300px auto 0 auto;display: block" @click="giveSecondLevel"/>
        </el-tooltip>
      </el-col>
      <el-col :span="7">
        <el-card style="margin-bottom: 10px;height: 44px">
          <span style="line-height: 32px">请选择要分配的二级菜单</span>
          <!--          <el-button size="small" type="distribution" @click="addSecondLevel">创建二级菜单</el-button>-->
          <!--          <el-button size="small" style="float: right" type="success" @click="RoleNameasdShow=!RoleNameasdShow">模块分配情况</el-button>-->
        </el-card>
        <el-card>
          <div slot="header">
            <el-input v-model="filterTextRight" size="small" placeholder="输入关键字进行过滤" clearable/>
          </div>
          <el-table ref="multipleTableRight" :data="secondLevelFilter" stripe highlight-current-row size="mini" height="500" style="height:calc(100vh - 330px);" @selection-change="handleSelectionChangeRight">
            <el-table-column :selectable="selectable" align="center" type="selection" width="55"/>
            <el-table-column type="index" align="center" width="60"/>
            <el-table-column align="center" label="模块名称">
              <template slot-scope="scope">
                {{ scope.row.title }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-row v-show="RoleNameasdShow">
      <el-card>
        <div slot="header">
          <el-select v-model="TitleValue" placeholder="请选择" size="small" style="width:200px;margin-left:10px" filterable @change="getTitle">
            <el-option
              v-for="item in Title"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </div>
        <el-table :data="RoleNameasd" stripe size="mini" height="200" border style="width: 465px">
          <el-table-column label="序号" align="center" type="index" width="50"/>
          <el-table-column align="center" label="模块名称" width="400">
            <template slot-scope="scope">
              {{ scope.row.角色功能 }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-row>

    <el-dialog :visible.sync="dialogVisible1" title="新增一级模块" center style="min-height: 300px" width="400px">
      <el-form ref="form1" :model="form1" :rules="rules1" label-position="left" label-width="110px" class="demo-ruleForm">
        <el-form-item label="模块名称" prop="moduleName">
          <el-input
            v-model="form1.moduleName"
            size="small"
            style="width:200px"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1=false">取消</el-button>
        <el-button type="primary" @click="submitAdd()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRole, getModule, initFisrtLevel, initSecondLevel, returnModule, giveFirstLevel, giveSecondLevel, submitAdd, getRoleTitle, getRoleNameasd, upModule, downModule, searchUpModule, searchDownModule } from '@/api/BasicData/MenuManagement'
export default {
  name: 'MenuManagement',
  data() {
    return {
      roleName: null,
      roleNames: [],
      filterText: '',
      filterTextLeft: '',
      filterTextRight: '',
      allModuleId: [],
      moduleTree: [],
      fisrtLevel: [],
      fisrtLevelFilter: [],
      secondLevel: [],
      secondLevelFilter: [],
      selectLeft: [],
      selectRight: [],
      treeCheckList: [],
      treeCheckListJudge: null,
      dialogVisible1: false,
      form1: {
        moduleName: ''
      },
      rules1: {
        moduleName: [{ required: true, message: '请输入', trigger: ['blur', 'change'] }]
      },
      RoleNameasdShow: false,
      TitleValue: '',
      Title: [],
      RoleNameasd: []
    }
  },
  watch: {
    filterText(val) {
      this.$refs.moduleTree.filter(val)
    },
    filterTextLeft(val) {
      this.fisrtLevelFilter = this.fisrtLevel.filter(v => {
        return v.title.indexOf(val) > -1
      })
    },
    filterTextRight(val) {
      this.secondLevelFilter = this.secondLevel.filter(v => {
        return v.title.indexOf(val) > -1
      })
    }
  },
  created() {
    this.getRoleName()
    this.initFisrtLevel()
    this.initSecondLevel()
    this.getRoleTitle()
  },
  methods: {
    // 撤回分配模块
    returnModule(node, data) {
      console.log(node, data, 123)
      this.$confirm('确定撤回分配模块?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        returnModule(data.id, this.roleName).then(response => {
          if (response.data[0].result === '1') {
            this.filterText = ''
            this.filterTextLeft = ''
            this.filterTextRight = ''
            this.getModule()
            this.initFisrtLevel()
            this.initSecondLevel()
            this.$message.success('操作成功')
          } else { this.$message.error('操作失败') }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
    },
    moveUp(node, data) {
      searchUpModule(data.id, this.roleName).then(response => {
        if (Number(response.data[0].角色模块顺序) !== 1) {
          upModule(data.id, this.roleName).then(response => {
            if (response.data[0].result === '1') {
              this.filterText = ''
              this.filterTextLeft = ''
              this.filterTextRight = ''
              this.getModule()
              this.initFisrtLevel()
              this.initSecondLevel()
              this.$message.success('上移成功')
            } else { this.$message.error('上移失败') }
          })
        } else { this.$message.error('当前已经排在第一') }
      })
    },
    moveDown(node, data) {
      searchDownModule(data.id, this.roleName).then(response => {
        if (response.data[0].result === 1) {
          downModule(data.id, this.roleName).then(response => {
            if (response.data[0].result === '1') {
              this.filterText = ''
              this.filterTextLeft = ''
              this.filterTextRight = ''
              this.getModule()
              this.initFisrtLevel()
              this.initSecondLevel()
              this.$message.success('操作成功')
            } else { this.$message.error('操作失败') }
          })
        } else {
          this.$message.error('当前已经排在最后')
        }
      })
    },
    // 分配一级
    giveFirstLevel() {
      this.$confirm('确定将选中的一级模块分配给选中角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        giveFirstLevel(this.selectLeft, this.roleName).then(response => {
          if (response.data[0].result === '1') {
            this.filterText = ''
            this.filterTextLeft = ''
            this.filterTextRight = ''
            this.getModule()
            this.initFisrtLevel()
            this.initSecondLevel()
            this.$message.success('操作成功')
          } else { this.$message.error('操作失败') }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
    },
    // 分配二级
    giveSecondLevel() {
      if (this.$refs.moduleTree.getCheckedKeys().length === 1) {
        this.$confirm('确定将选中的二级模块分配给选中角色的选中一级模块?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          giveSecondLevel(this.selectRight, this.roleName, this.$refs.moduleTree.getCheckedKeys()).then(response => {
            if (response.data[0].result === '1') {
              this.filterText = ''
              this.filterTextLeft = ''
              this.filterTextRight = ''
              this.getModule()
              this.initFisrtLevel()
              this.initSecondLevel()
              this.$message.success('操作成功')
            } else { this.$message.error('操作失败') }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消操作'
          })
        })
      } else {
        this.$message.error('只可以分配给一个一级菜单')
      }
    },
    // 控制某行是否可选
    selectable(row) {
      return !this.allModuleId.includes(row.id)
    },
    // 树checkChange
    treeCheck() {
      const param = []
      this.treeCheckList = this.$refs.moduleTree.getCheckedKeys()
      this.fisrtLevel.map(v => {
        param.push(v.id)
      })
      this.treeCheckListJudge = !param.includes(parseInt(this.treeCheckList))
    },
    // leftChange
    handleSelectionChangeLeft(val) {
      this.selectLeft = []
      val.map(v => {
        this.selectLeft.push(v.id)
      })
    },
    // rightChange
    handleSelectionChangeRight(val) {
      this.selectRight = []
      val.map(v => {
        this.selectRight.push(v.id)
      })
    },
    // 初始化一级
    initFisrtLevel() {
      initFisrtLevel().then(res => {
        this.fisrtLevel = res.data
        this.fisrtLevelFilter = res.data
      })
    },
    // 初始化二级
    initSecondLevel() {
      initSecondLevel().then(res => {
        this.secondLevel = res.data
        this.secondLevelFilter = res.data
      })
    },
    // 新增一级
    addFisrtLevel() {
      if (this.$refs['form1'] !== undefined) {
        this.$refs['form1'].resetFields()
      }
      this.form1.moduleName = ''
      this.dialogVisible1 = true
    },
    // 确认新增一级
    submitAdd() {
      this.$refs['form1'].validate((valid) => {
        if (valid) {
          this.dialogVisible1 = false
          submitAdd(this.form1.moduleName).then(response => {
            if (response.data[0].result === '1') {
              this.$message.success('操作成功')
              this.dialogVisible1 = false
              this.initFisrtLevel()
            } else {
              this.$message.error('操作失败')
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 新增二级
    addSecondLevel() {
      console.log(1)
    },
    // 递归
    fn(data, pid) {
      const result = []
      let temp
      for (let i = 0; i < data.length; i++) {
        if (data[i].pid === pid) {
          const obj = {
            'id': data[i].id,
            'label': data[i].title
          }
          temp = this.fn(data, data[i].id)
          if (temp.length > 0) {
            obj.children = temp
          }
          result.push(obj)
        }
      }
      return result
    },
    // 初始化角色
    getRoleName() {
      getRole().then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.roleNames.push({
            value: response.data[i].角色编号,
            label: response.data[i].角色功能
          })
        }
      })
    },
    // 根据角色查模块
    getModule() {
      this.$refs.multipleTableLeft.clearSelection()
      this.$refs.multipleTableRight.clearSelection()
      getModule(this.roleName).then(response => {
        this.allModuleId = []
        response.data.map(v => {
          this.allModuleId.push(v.id)
        })
        this.moduleTree = this.fn(response.data, 0)
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 初始化模块
    getRoleTitle() {
      getRoleTitle().then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.Title.push({
            value: response.data[i].title,
            label: response.data[i].title
          })
        }
      })
    },
    getTitle() {
      this.RoleNameasd = []
      getRoleNameasd(this.TitleValue).then(responmse => {
        this.RoleNameasd = responmse.data
      })
    }
  }
}
</script>

<style scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
