<template>
  <el-card shadow="hover">
    <el-row>
      <el-col :span="20">
        <el-button @click="addRole">新增角色</el-button>
        <el-input
            style="width: 200px;margin-left: 10px"
            :suffix-icon="Search"
            v-model="search.inputSearch"
            placeholder="请输入角色名"
            @change="searchQuery"
        >
        </el-input>
        <el-button style="margin-left: 10px" @click="clearSerach">清空查询</el-button>
        <el-button @click="updateRoleMenus">为所有角色添加菜单</el-button>
      </el-col>
      <el-col :span="4">
        <el-button @click="saveRole">保存</el-button>
        <el-button @click="searchPage">刷新</el-button>
      </el-col>
    </el-row>

    <br/>

    <vxe-table
        round
        border="inner"
        size="mini"
        keep-source
        :row-config="{isHover: true}"
        :column-config="{resizable: true}"
        :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
        :edit-rules="validRules"
        ref="tableRef"
        :data="tableData"
    >
      <vxe-column type="seq" width="60"></vxe-column>
      <vxe-column field="rolename" title="角色名称" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.rolename" type="text" ></vxe-input>
        </template>
      </vxe-column>
      <vxe-column field="interfaceAuth" title="接口权限" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.interfaceAuth" type="text" ></vxe-input>
        </template>
      </vxe-column>
      <vxe-column title="数据权限"></vxe-column>
      <vxe-column field="enabled" title="是否可用" :edit-render="{}" formatter="formatIsNo">
        <template #edit="{ row }">
          <vxe-switch v-model="row.enabled" open-label="是" close-label="否" size="mini"></vxe-switch>
        </template>
      </vxe-column>
      <vxe-column title="操作" width="200">
        <template #default="{ row }">
          <el-button link type="primary" @click="editRoleMenus(row)">菜单权限</el-button>
          <el-button link type="primary" @click="delRole(row)">删除</el-button>

        </template>
      </vxe-column>
    </vxe-table>

    <br/>

    <el-pagination
        small
        :currentPage="page.current"
        :page-size="page.size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <el-dialog
        draggable
        v-model="dialogRoleMenusVisible"
        title="菜单权限"
    >

      <vxe-table
          round
          border="inner"
          size="mini"
          max-height="400"
          :row-config="{isHover: true, keyField: 'id'}"
          :column-config="{resizable: true}"
          :tree-config="{transform: true, rowField: 'id', parentField: 'parentId'}"
          :checkbox-config="{labelField: 'menuName'}"
          ref="menusTree"
          :data="menusData"
      >
        <vxe-column type="checkbox" title="菜单名称" tree-node />
      </vxe-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogRoleMenusVisible = false">取消</el-button>
          <el-button type="primary" @click="roleMenusSave">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

  </el-card>
</template>

<script setup>
import { reactive, ref, getCurrentInstance, onMounted } from 'vue'
import { Plus, ArrowLeft, Search } from '@element-plus/icons-vue'

const {proxy} = getCurrentInstance()

const ConditionEnum = proxy.$launchUtil.ConditionEnum
const {handleTreeData, handleListData} = proxy.$launchUtil.vxeUtils
const {Page, Query, createSelectPage} = proxy.$launchUtil.selectPage

const rolesApi = proxy.$launchApi.rolesApi
const menusApi = proxy.$launchApi.menusApi

let tableRef = ref(null)

let tableData = ref([])

let validRules = ref({
  rolename:[
    { required: true, message: '该值不能为空' }
  ]
})

// 搜索
let search = ref({})

let page = ref(new Page(10,1))
page.value.setOrders([
  {column:"update_time",asc:false}
])

let querys = ref([])

let dialogRoleMenusVisible = ref(false)

// 菜单
let menusTree = ref(null)

let menusData = ref([])

let currentRow = ref(null)  // 当前点击的角色行


/**
 * 角色业务
 */
function addRole() {
  let newRow = {
    enabled: true
  }
  tableRef.value.insertAt(newRow, -1)
}

function saveRole() {
  tableRef.value.validate(true).then(valid => {
    if(valid){
      proxy.$message.error("请完成所有的必填项")
    }else{
      let record = tableRef.value.getRecordset()
      if(record.insertRecords.length === 0
          && record.removeRecords.length === 0
          && record.updateRecords.length === 0){
        proxy.$message.warning("暂无需要保存的数据")
      }else{
        updateData(record)
      }
    }
  })
}

function updateData(record) {
  rolesApi.save(handleTreeData(record)).then(data => {
    if(data){
      proxy.$message.success("保存成功")
      searchPage()
    }
  })
}

function searchPage() {
  rolesApi.selectPage(createSelectPage(page.value,querys.value)).then(data => {
    if(data != null){
      tableData.value = data.records
      page.value.total = data.total
      page.value.current = data.current
    }
  })
}

function editRoleMenus(row) {
  if(row){
    if(row.id){
      currentRow.value = row
      dialogRoleMenusVisible.value = true
      searchMenus(row)
    }else{
      proxy.$message.error("请先保存此角色")
    }
  }
}

function delRole(row) {
  tableRef.value.remove(row)
}

function handleSizeChange(val) {
  page.value.size = val
  searchPage()
}

function handleCurrentChange(val) {
  page.value.current = val
  searchPage()
}

/**
 * 角色菜单业务
 */
function searchMenus(row) {
  menusApi.searchMenus().then(data => {
    if(data){
      menusData.value = data
      searchRoleMenus(row)
    }
  })
}

function searchRoleMenus(row) {
  menusApi.searchRoleMenus(row.id).then(result => {
    if(result){
      menusTree.value.clearCheckboxRow()
      result.forEach(item => {
        let treeRow = menusTree.value.getRowById(item.id)
        menusTree.value.setCheckboxRow(treeRow,true)
      })
    }
  })
}

function roleMenusSave() {
  let records = menusTree.value.getCheckboxRecords()
  let reqData = {
    roleId: currentRow.value.id,
    menus: handleListData(records)
  }
  rolesApi.roleMenusSave(reqData).then(data => {
    if(data){
      proxy.$message.success("保存成功")
      searchMenus(currentRow.value)
      dialogRoleMenusVisible.value = false
    }
  })
}

function updateRoleMenus() {

}

function searchQuery() {
  let queryArray = []
  if(search.value.inputSearch && search.value.inputSearch.trim() !== ""){
    let query = new Query()
    query.setCondition(ConditionEnum.eq())
    query.setVal(search.value.inputSearch)
    query.setColumn("rolename")
    queryArray.push(query)
  }
  querys.value = queryArray
  searchPage()
}

function clearSerach() {
  search.value = {}
  querys.value = []
  searchPage()
}

onMounted(() => {

  searchPage()
})
</script>

<style scoped>
.dialog-footer{
  margin-right: var(--launch-dialog-footer-m-r);
}
</style>