<template>
  <div>
    <el-card>
      <span class="show-text">角色:</span>
      <el-select
        id="selectRoleName"
        v-model="roleName"
        class="personal-role-value"
        filterable
        placeholder="请选择"
        style="width:200px;margin-right: 14px"
        @change="getModule">
        <el-option
          v-for="item in roleNames"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>
      <el-row style="margin-top: 10px;width: 1500px">
        <el-col
          :span="7"
          style="border: 1px solid #bfbfbf;height: 700px;padding: 5px;border-radius: 5px;overflow: auto">
          <el-input
            id="inputFilterTextLeft"
            v-model="filterTextLeft"
            class="personal-name"
            clearable
            placeholder="输入关键字进行过滤"/>
          <el-table
            ref="multipleTableLeft"
            :data="fisrtLevelFilter"
            height="calc(100vh - 330px)"
            highlight-current-row
            stripe
            style="height:calc(100vh - 330px);"
            @selection-change="handleSelectionChangeLeft">
            <el-table-column
              :selectable="selectable"
              align="center"
              type="selection"
              width="55"/>
            <el-table-column align="center" label="模块名称">
              <template slot-scope="scope">
                {{ scope.row.title }}
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="1">
          <el-tooltip class="item" content="将选中一级菜单分配给该角色" effect="dark" placement="top-start">
            <el-button
              :disabled="!roleName || selectLeft.length === 0"
              icon="el-icon-arrow-right"
              style="margin: 300px auto 0 auto;display: block;width: 40px;height: 60px;padding: 12px 12px"
              type="primary"
              @click="giveFirstLevel"/>
          </el-tooltip>
        </el-col>
        <el-col
          :span="8"
          style="border: 1px solid #bfbfbf;height: 700px;padding: 5px;border-radius: 5px;overflow: auto">
          <el-input
            id="inputFilterText"
            v-model="filterText"
            class="personal-name"
            clearable
            placeholder="输入关键字进行过滤"
            size="small"/>
          <el-tree
            ref="moduleTree"
            :data="moduleTree"
            :filter-node-method="filterNode"
            check-strictly
            class="moduleTree"
            default-expand-all
            node-key="id"
            show-checkbox
            @check-change="treeCheck">
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>
                <!--                &nbsp;-->
                <!--                <div v-if="data.isPage" style="flex:1;">-->
                <!--                  <el-checkbox :indeterminate="data.isIndeterminate" v-model="data.AuthButtonsAll" style="margin-right: 10px" @change="handleCheckAllChange(0, $event)">全部</el-checkbox>-->
                <!--                  <el-checkbox v-model="data.SearchData" style="margin-right: 10px" @change="handleCheckAllChange(1, $event)">查询</el-checkbox>-->
                <!--                  <el-checkbox v-model="data.AddData" style="margin-right: 10px" @change="handleCheckAllChange(2, $event)">增加</el-checkbox>-->
                <!--                  <el-checkbox v-model="data.EditData" style="margin-right: 10px" @change="handleCheckAllChange(3, $event)">编辑</el-checkbox>-->
                <!--                  <el-checkbox v-model="data.DeleteData" style="margin-right: 10px" @change="handleCheckAllChange(4, $event)">删除</el-checkbox>-->
                <!--                </div>-->
                <el-button
                  :disabled="data.children && data.children.length!==0"
                  style="font-size: 14px"
                  type="text"
                  @click="() => returnModule(node, data)">
                  移除
                </el-button>
              </span>
            </span>
          </el-tree>
        </el-col>
        <el-col :span="1">
          <el-tooltip
            class="item"
            content="将选中二级菜单分配给该角色选中的一级菜单"
            effect="dark"
            placement="top-start">
            <el-button
              :disabled="treeCheckList.length !== 1 || selectRight.length === 0 || treeCheckListJudge"
              icon="el-icon-arrow-left"
              style="margin: 300px auto 0 auto;display: block;width: 40px;height: 60px;padding: 12px 12px"
              type="primary"
              @click="giveSecondLevel"/>
          </el-tooltip>
        </el-col>
        <el-col
          :span="7"
          style="border: 1px solid #bfbfbf;height: 700px;padding: 5px;border-radius: 5px;overflow: auto">
          <el-input
            id="inputFilterTextRight"
            v-model="filterTextRight"
            class="personal-name"
            clearable
            placeholder="输入关键字进行过滤"
            size="small"/>
          <el-table
            ref="multipleTableRight"
            :data="secondLevelFilter"
            height="calc(100vh - 330px)"
            highlight-current-row
            stripe
            style="height:calc(100vh - 330px);"
            @selection-change="handleSelectionChangeRight">
            <el-table-column
              :selectable="selectable"
              align="center"
              type="selection"
              width="55"/>
            <el-table-column align="center" label="模块名称">
              <template slot-scope="scope">
                {{ scope.row.title }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="模块路径">
              <template slot-scope="scope">
                {{ scope.row.title1 }}
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog :visible.sync="dialogVisible1" center style="min-height: 300px" title="新增一级模块" width="400px">
      <el-form
        ref="form1"
        :model="form1"
        :rules="rules1"
        class="demo-ruleForm"
        label-position="left"
        label-width="110px">
        <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 {
  getModule,
  initFisrtLevel,
  initSecondLevel,
  returnModule,
  giveFirstLevel,
  giveSecondLevel,
  submitAdd
} 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'] }]
      }
    }
  },
  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()
  },
  methods: {
    // 撤回分配模块
    returnModule(node, data) {
      this.$confirm('确定撤回分配模块?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirm-confirm-button',
        cancelButtonClass: 'confirm-cancel-button',
        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: '取消操作'
        })
      })
    },
    // 分配一级
    giveFirstLevel() {
      this.$confirm('确定将选中的一级模块分配给选中角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirm-confirm-button',
        cancelButtonClass: 'confirm-cancel-button',
        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: '取消',
          confirmButtonClass: 'confirm-confirm-button',
          cancelButtonClass: 'confirm-cancel-button',
          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 {
          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) {
          let isPage = false
          if (!data[i].redirect) isPage = true
          const obj = {
            'id': data[i].id,
            'label': data[i].title,
            'isPage': isPage,
            'AddData': !!parseInt(data[i].AddData),
            'DeleteData': !!parseInt(data[i].DeleteData),
            'EditData': !!parseInt(data[i].EditData),
            'SearchData': !!parseInt(data[i].SearchData),
            'isIndeterminate': !!parseInt(data[i].DeleteData) && !!parseInt(data[i].AddData) && !!parseInt(data[i].DeleteData) && !!parseInt(data[i].SearchData),
            'AuthButtonsAll': !!parseInt(data[i].DeleteData) && !!parseInt(data[i].AddData) && !!parseInt(data[i].DeleteData) && !!parseInt(data[i].SearchData)
          }
          temp = this.fn(data, data[i].id)
          if (temp.length > 0) {
            obj.children = temp
          }
          result.push(obj)
        }
      }
      return result
    },
    // 初始化角色
    getRoleName() {
      var param = []
      param[0] = ['角色功能', this.RoleFunctioning]
      param[1] = ['PageCurrent', 1]
      param[2] = ['PageSize', 1000000]
      param[3] = ['PageCount', '1111', 'int', '1']
      param[4] = ['ItemCount', '1111', 'int', '1']
      var Data = this.CreateData('11', '菜单系统模块_项目角色_查询数据_MESWORK', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.result.length !== 0) {
          for (let i = 0; i < response.data.result.length; i++) {
            this.roleNames.push({
              value: response.data.result[i].Roles_number,
              label: response.data.result[i].Roles_Function
            })
          }
        }
      })
    },
    // 根据角色查模块
    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
    },
    handleCheckAllChange(value, type) {
      console.log(value, type)
    }
  }
}
</script>

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