<template>
  <div class="app-container mes-admin-page menu-management-page">
<!--    <div class="heroCard">-->
<!--      <div class="heroContent">-->
<!--        <div class="heroText">-->
<!--          <div class="heroTitle">菜单权限编排</div>-->
<!--          <div class="heroSubtitle">围绕角色完成一级菜单、二级菜单的分配、回收与排序维护。</div>-->
<!--        </div>-->
<!--        <div class="heroActions">-->
<!--          <el-button size="small" type="primary" plain icon="el-icon-plus" @click="addFisrtLevel">-->
<!--            {{ $t('menuManagement.addFirstLevelModule') }}-->
<!--          </el-button>-->
<!--          <div class="roleStatus">-->
<!--            <span class="roleStatusLabel">{{ $t('menuManagement.role') }}</span>-->
<!--            <span class="roleStatusValue">{{ roleName || '&#45;&#45;' }}</span>-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->

    <el-row :gutter="18" class="workspaceRow">
      <el-col :span="7">
        <el-card class="boardCard">
          <div slot="header" style="padding: 5px 11px">
            <div class="panelHeader">
                <div class="panelTitle">{{ $t('menuManagement.firstLevelMenuName') }}</div>
              <div class="panelCount">{{ fisrtLevelFilter.length }}</div>
            </div>
            <el-input v-model="filterTextLeft" clearable :placeholder="$t('menuManagement.filterPlaceholder')" size="small"/>
          </div>
          <el-table
            ref="multipleTableLeft"
            class="panelTable"
            :data="fisrtLevelFilter"
            height="500"
            highlight-current-row
            size="mini"
            stripe
            @selection-change="handleSelectionChangeLeft">
            <el-table-column :selectable="selectable" align="center" type="selection" width="55"/>
            <el-table-column align="center" type="index" width="60"/>
            <el-table-column align="center" :label="$t('menuManagement.firstLevelMenuName')">
              <template slot-scope="scope">
                {{ translateMenuTitle(scope.row.title) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="1">
        <div class="transferRail">
          <el-tooltip class="item" :content="$t('menuManagement.assignFirstLevelTooltip')" effect="dark" placement="top-start">
            <el-button
              :disabled="!roleName || selectLeft.length === 0"
              class="transferButton"
              icon="el-icon-right"
              size="mini"
              type="primary"
              @click="giveFirstLevel"/>
          </el-tooltip>
        </div>
      </el-col>
      <el-col :span="8">
        <el-card class="boardCard centerBoardCard">
          <div slot="header" style="padding: 5px 11px">
            <div class="panelHeader">
                <div class="panelTitle">{{ $t('menuManagement.roleMenuData') }}</div>
              <div class="panelCount">{{ moduleTree.length }}</div>
            </div>
            <div class="panelControls">
              <div class="roleSelector">
                <span class="fieldLabel">{{ $t('menuManagement.role') }}</span>
                <el-select
                  v-model="roleName"
                  filterable
                  :placeholder="$t('menuManagement.selectPlaceholder')"
                  size="small"
                  style="width: 150px"
                  @change="getModule">
                  <el-option
                    v-for="item in roleNames"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
              </div>
              <el-input v-model="filterText" clearable :placeholder="$t('menuManagement.filterPlaceholder')" size="small" style="width: 200px"/>
            </div>
          </div>
          <el-tree
            ref="moduleTree"
            :data="moduleTree"
            :filter-node-method="filterNode"
            check-strictly
            class="moduleTree panelTree"
            default-expand-all
            node-key="id"
            show-checkbox
            @check-change="treeCheck">
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ translateMenuTitle(node.label) }}</span>
              <span>
                <el-button
                  size="mini"
                  type="text"
                  @click="() => moveUp(node, data)">
                  {{ $t('menuManagement.moveUp') }}
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  @click="() => moveDown(node, data)">
                  {{ $t('menuManagement.moveDown') }}
                </el-button>
                <el-button
                  :disabled="data.children && data.children.length!==0"
                  size="mini"
                  type="text"
                  @click="() => returnModule(node, data)">
                  {{ $t('menuManagement.remove') }}
                </el-button>
              </span>
            </span>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="1">
        <div class="transferRail">
          <el-tooltip class="item" :content="$t('menuManagement.assignSecondLevelTooltip')" effect="dark" placement="top-start">
            <el-button
              :disabled="treeCheckList.length !== 1 || selectRight.length === 0 || treeCheckListJudge"
              class="transferButton"
              icon="el-icon-back"
              size="mini"
              type="primary"
              @click="giveSecondLevel"/>
          </el-tooltip>
        </div>
      </el-col>
      <el-col :span="7">
        <el-card class="boardCard">
          <div slot="header" style="padding: 5px 11px">
          <div class="panelHeader">

                <div class="panelTitle">{{ $t('menuManagement.secondLevelMenuName') }}</div>

              <div class="panelCount">{{ secondLevelFilter.length }}</div>
            </div>
            <el-input v-model="filterTextRight" clearable :placeholder="$t('menuManagement.filterPlaceholder')" size="small"/>
          </div>
          <el-table
            ref="multipleTableRight"
            class="panelTable"
            :data="secondLevelFilter"
            height="500"
            highlight-current-row
            size="mini"
            stripe
            @selection-change="handleSelectionChangeRight">
            <el-table-column :selectable="selectable" align="center" type="selection" width="55"/>
            <el-table-column align="center" type="index" width="60"/>
            <el-table-column align="center" :label="$t('menuManagement.secondLevelMenuName')">
              <template slot-scope="scope">
                {{ translateMenuTitle(scope.row.title) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-row v-show="RoleNameasdShow" class="statusRow">
      <el-card class="statusCard">
        <div slot="header">
          <div class="panelHeader">
            <div>
              <div class="panelTitle">模块分配情况</div>
              <div class="panelSubtitle">按菜单查看已分配角色</div>
            </div>
            <el-select
              v-model="TitleValue"
              filterable
              :placeholder="$t('menuManagement.selectPlaceholder')"
              size="small"
              style="width: 220px"
              @change="getTitle">
              <el-option
                v-for="item in Title"
                :key="item.value"
                :label="translateMenuTitle(item.label)"
                :value="item.value"/>
            </el-select>
          </div>
        </div>
        <el-table :data="RoleNameasd" border class="statusTable" height="200" size="mini" stripe style="width: 100%">
          <el-table-column align="center" :label="$t('menuManagement.sequence')" type="index" width="50"/>
          <el-table-column align="center" :label="$t('menuManagement.roleName')" width="400">
            <template slot-scope="scope">
              {{ scope.row.角色功能 }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-row>

    <el-dialog :visible.sync="dialogVisible1" center style="min-height: 300px" :title="$t('menuManagement.addFirstLevelModule')" width="400px">
      <el-form
        ref="form1"
        :model="form1"
        :rules="rules1"
        class="demo-ruleForm"
        label-position="left"
        label-width="110px">
        <el-form-item :label="$t('menuManagement.menuName')" 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">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="submitAdd()">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { translateMenuTitle } from '@/utils/i18n'
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: {
    translateMenuTitle,
    // 撤回分配菜单
    returnModule(node, data) {
      console.log(node, data, 123)
      this.$confirm(this.$t('menuManagement.confirmReturnMenu'), this.$t('menuManagement.prompt'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        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(this.$t('menuManagement.operationSuccess'))
          } else {
            this.$message.error(this.$t('menuManagement.operationFailed'))
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('menuManagement.operationCanceled')
        })
      })
    },
    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(this.$t('menuManagement.moveUpSuccess'))
            } else {
              this.$message.error(this.$t('menuManagement.moveUpFailed'))
            }
          })
        } else {
          this.$message.error(this.$t('menuManagement.alreadyFirst'))
        }
      })
    },
    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(this.$t('menuManagement.operationSuccess'))
            } else {
              this.$message.error(this.$t('menuManagement.operationFailed'))
            }
          })
        } else {
          this.$message.error(this.$t('menuManagement.alreadyLast'))
        }
      })
    },
    // 分配一级菜单
    giveFirstLevel() {
      this.$confirm(this.$t('menuManagement.confirmAssignFirstLevelMenu'), this.$t('menuManagement.prompt'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        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(this.$t('menuManagement.operationSuccess'))
          } else {
            this.$message.error(this.$t('menuManagement.operationFailed'))
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('menuManagement.operationCanceled')
        })
      })
    },
    // 分配二级菜单
    giveSecondLevel() {
      if (this.$refs.moduleTree.getCheckedKeys().length === 1) {
        this.$confirm(this.$t('menuManagement.confirmAssignSecondLevelMenu'), this.$t('menuManagement.prompt'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          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(this.$t('menuManagement.operationSuccess'))
            } else {
              this.$message.error(this.$t('menuManagement.operationFailed'))
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('menuManagement.operationCanceled')
          })
        })
      } else {
        this.$message.error(this.$t('menuManagement.assignOneFirstLevelOnly'))
      }
    },
    // 控制某行是否可选
    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>
.menu-management-page {
  min-height: calc(100vh - 84px);
}

.heroCard {
  margin-bottom: 18px;
  padding: 18px 22px;
  border: 1px solid rgba(207, 220, 232, 0.9);
  border-radius: 18px;
  background:
    linear-gradient(135deg, rgba(255, 255, 255, 0.98) 0%, rgba(242, 247, 252, 0.98) 100%);
  box-shadow: 0 14px 34px rgba(31, 57, 90, 0.08);
}

.heroContent {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 18px;
}

.heroTitle {
  color: #203247;
  font-size: 22px;
  font-weight: 700;
  letter-spacing: 0.01em;
}

.heroSubtitle {
  margin-top: 6px;
  color: #667a90;
  font-size: 13px;
}

.heroActions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.roleStatus {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  min-height: 36px;
  padding: 0 14px;
  border: 1px solid rgba(31, 120, 209, 0.18);
  border-radius: 999px;
  background: rgba(239, 247, 255, 0.92);
}

.roleStatusLabel {
  color: #5f7186;
  font-size: 12px;
  font-weight: 600;
}

.roleStatusValue {
  color: #1f78d1;
  font-size: 13px;
  font-weight: 700;
}

.workspaceRow {
  margin-top: 2px;
}

.panelHeader {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 12px;
}

.panelTitle {
  color: #203247;
  font-size: 15px;
  font-weight: 700;
}

.panelSubtitle {
  margin-top: 4px;
  color: #6e8197;
  font-size: 12px;
}

.panelCount {
  min-width: 38px;
  height: 28px;
  padding: 0 10px;
  border-radius: 999px;
  background: linear-gradient(135deg, #edf6ff 0%, #dbeeff 100%);
  color: #1f78d1;
  font-size: 13px;
  font-weight: 700;
  line-height: 28px;
  text-align: center;
}

.panelControls {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 12px;
  flex-wrap: nowrap;
}

.roleSelector {
  display: inline-flex;
  align-items: center;
  gap: 10px;
}

.fieldLabel {
  color: #203247;
  font-weight: 600;
}

.transferRail {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 550px;
}

.transferButton {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  box-shadow: 0 12px 24px rgba(31, 120, 209, 0.16);
}

.panelTree {
  min-height: 500px;
  max-height: 500px;
  overflow: auto;
  padding: 6px 4px 0;
}

.panelTable,
.statusTable {
  width: 100% !important;
}

.statusRow {
  margin-top: 18px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  gap: 12px;
  padding: 6px 8px 6px 2px;
}

::v-deep .boardCard > .el-card__header,
::v-deep .statusCard > .el-card__header {
  padding-bottom: 10px;
}

::v-deep .boardCard > .el-card__body,
::v-deep .statusCard > .el-card__body {
  //display: flex;
  //flex-direction: column;
}

::v-deep .centerBoardCard > .el-card__body {
  overflow: visible;
}

::v-deep .panelTree .el-tree-node__content {
  height: auto;
  min-height: 34px;
  border-radius: 10px;
}

::v-deep .panelTree .el-tree-node__content:hover {
  background: #eef6ff;
}

::v-deep .custom-tree-node .el-button--text {
  padding: 4px 6px;
  color: #1f78d1;
}

@media (max-width: 1400px) {
  .heroContent {
    flex-direction: column;
    align-items: flex-start;
  }

  .heroActions {
    width: 100%;
    justify-content: space-between;
    flex-wrap: wrap;
  }
}

@media (max-width: 1200px) {
  .workspaceRow {
    display: block;
  }

  .workspaceRow .el-col {
    width: 100%;
    margin-bottom: 16px;
  }

  .transferRail {
    min-height: auto;
    padding: 4px 0;
  }

  .transferButton {
    transform: rotate(90deg);
  }
}
</style>
