<script setup lang="ts">
import {
  User_Power_List,
  User_Sys_List,
  User_Power_Get,
  User_Power_Add,
  User_Power_Del,
  User_Power_Edit,
  User_Power_Edit_Menu
} from '@/api/role/index'
import { GlobalStore } from '@/stores/index'
import { ref, reactive, nextTick } from 'vue'
import Drawer from '@/components/Drawer/index.vue'
import Dialog from '@/components/dialog/Dialog.vue'
import { ElTree } from 'element-plus'
import TableBase from '@/components/TableBase/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { ColumnProps } from '@/components/TableBase/interface/index'
import { Edit, Delete, Operation, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { ElNotification, ElMessageBox, ElMessage,TabsPaneContext  } from 'element-plus'

interface InSys {
  T_sys: string
  T_name: string
  children: any
  checkList: string[]
}

const isNew = ref(true)
let currentVal: any = {}
const globalStore = GlobalStore()
const User_tokey = globalStore.GET_User_tokey
const formLabelWidth = ref('100px')
const ruleFormRef = ref<FormInstance>()
const dialog = ref<InstanceType<typeof Dialog> | null>(null)
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)
const initParam = { User_tokey, T_name: '' }



const DialogOpen = async (row: any) => {
  currentVal = row
  await getSysList()
  dialog.value?.DialogOpen()
}

const columns: ColumnProps[] = [
  { type: 'index', label: '#', width: 80 },
  { prop: 'T_name', label: '姓名' },
  { prop: 'T_id', label: 'id' },
  { prop: 'operation', label: '操作', width: 200, fixed: 'right' }
]

const menuDir:any = reactive({
  activeName:null,//选中的tabs
  MenuData:[],//tabs导航栏
  tabsMenu:[],//tab展开导航
  defaultKeys:[],//默认选中
  selectData:[],//勾选项
  isExpanded: false // 是否展开所有节点
})
const getSysList = async () => {
  const { Data } = await User_Sys_List({ User_tokey })
  console.log('导航',Data)
  menuDir.MenuData = Data
  menuDir.activeName = menuDir.MenuData[0].T_sys
  const {Data:resIt} = await getMenuList(menuDir.activeName)
  menuDir.tabsMenu = resIt.Menu
  menuDir.defaultKeys = resIt.Menu_checked?resIt.Menu_checked:[]
}
//点击切换tabs调用导航
const handleClick = async(tab: TabsPaneContext, event: Event) => {
  menuDir.defaultKeys = []
  menuDir.activeName = tab.props.name
  const {Data:resIt} = await getMenuList(menuDir.activeName)
  menuDir.tabsMenu = resIt.Menu
  menuDir.defaultKeys = resIt.Menu_checked?resIt.Menu_checked:[]
}

//调用当前权限的子选项
const getMenuList = async (code: string) => {
  const res: any = await User_Power_Get({ User_tokey, T_code: code, T_id: currentVal.T_id })
  return {
    code,
    ...res
  }
}

// 添加角色
const form = reactive({
  name: '',
  id: ''
})

const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
})

const callbackDrawer = (done: () => void) => {
  resetForm(ruleFormRef.value)
  done()
}

const openDrawer = (type: string, row?: any) => {
  isNew.value = type === 'new' ? true : false
  nextTick(() => {
    !isNew.value && ((form.name = row.T_name), (form.id = row.T_id))
  })
  drawerRef.value?.openDrawer()
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const AddUserName = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      let res: any = {}
      if (isNew.value) {
        res = await User_Power_Add({ User_tokey, T_name: form.name })
      } else {
        res = await User_Power_Edit({ User_tokey, T_name: form.name, T_id: form.id })
      }
      if (res.Code === 200) {
        ElNotification.success({
          title: '添加角色',
          message: '添加成功！',
          position: 'bottom-right'
        })
        nextTick(() => {
          drawerRef.value?.closeDrawer()
          TableRef.value?.getTableList()
          resetForm(ruleFormRef.value)
          isNew.value = true
        })
      }
    }
  })
}

// 删除
const UserDelete = (row: any) => {
  ElMessageBox.confirm('您确定要删除吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res: any = await User_Power_Del({ User_tokey, T_id: row.T_id })
      if (res.Code === 200) {
        ElMessage.success('删除成功！')
        nextTick(() => {
          TableRef.value?.getTableList()
        })
      }
    })
    .catch(() => {
      ElMessage.warning('取消成功！')
    })
}

// 搜索
const search = ref('')
const searchHandle = () => {
  initParam.T_name = search.value
  TableRef.value?.searchTable()
}

// 重写角色权限
const treeRefMap = new Map<string, InstanceType<typeof ElTree>>()
const treeKey = ref(0) // 用于强制重新渲染树组件

/**
 * 返回拼接的 M + Id
 * @param children 菜单数组
 */
const getMontageRole = (children: any[]) => {
  let result = ''
  let arrMap:any = []
  if(children.length!=0){
    children.forEach((item:any)=>{
      arrMap.push('M'+item)
    })
    result = arrMap.join('|') + '|'
    return result
  }else{
    return ''
  }
}
/**
 * 提交
 */
const submit = async (data: any) => {
  let T_menu = getMontageRole([...menuDir.defaultKeys])
  console.log('提交',menuDir.defaultKeys,T_menu)
  const params = {
    User_tokey,
    T_id: currentVal.T_id,
    T_code: menuDir.activeName,
    T_menu
  }
  const res = await User_Power_Edit_Menu(params)
  if (res.Code === 200) {
    ElMessage.success('修改成功！')
    // dialog.value?.DialogClose()
  }
}

/**
 * 一键展开/折叠所有节点
 */
const toggleExpandAll = () => {
  menuDir.isExpanded = !menuDir.isExpanded
  // 更新 treeKey 强制重新渲染树组件，这样 default-expand-all 会重新生效
  treeKey.value++
  
  // 重新渲染后需要重新设置勾选状态
  nextTick(() => {
    setTimeout(() => {
      const currentTreeRef = treeRefMap.get(menuDir.activeName)
      if (currentTreeRef && menuDir.defaultKeys.length > 0) {
        currentTreeRef.setCheckedKeys(menuDir.defaultKeys, false)
      }
    }, 50)
  })
}

const checkChange = (data: any, check:any) => {
    // 获取所有被勾选的节点（包括半选节点和全选节点）
    // checkedKeys 只包含全选节点，halfCheckedKeys 包含半选节点
    // 提交时需要所有全选的节点
    menuDir.defaultKeys = check!.checkedKeys
}

/**
 * dialog 关闭回调
 */
const dialogCloseCallback = () => {
  nextTick(() => {
    treeRefMap.clear()
    menuDir.isExpanded = false // 重置展开状态
  })
}


</script>

<template>
  <div class="roles">
    <TableBase ref="TableRef" :columns="columns" :requestApi="User_Power_List" :initParam="initParam">
      <template #table-header>
        <div class="input-suffix">
          <el-row :gutter="20" style="margin-bottom: 0">
            <el-col :span="12">
              <span class="inline-flex items-center">角色名：</span>
              <el-input v-model="search" type="text" class="w-50 m-2" placeholder="输入角色名称查询" />
              <el-button type="primary" @click="searchHandle">搜索</el-button>
            </el-col>
            <el-col :span="6" :offset="6"><el-button type="primary" @click="openDrawer('new')">添加</el-button></el-col>
          </el-row>
        </div>
      </template>
      <template #right="{ row }">
        <el-button link type="primary" size="small" :icon="Edit" @click="openDrawer('edit', row)">编辑</el-button>
        <el-button link type="success" size="small" :icon="Operation" @click="DialogOpen(row)">权限</el-button>
        <el-button link type="danger" size="small" :icon="Delete" @click="UserDelete(row)">删除</el-button>
      </template>
    </TableBase>
    <Dialog ref="dialog" width="50%" :handleClose="dialogCloseCallback" draggable>
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <h3 style="margin: 0;">编辑权限</h3>
          <el-button 
            :icon="menuDir.isExpanded ? ArrowUp : ArrowDown"
            @click="toggleExpandAll"
            size="small"
          >
            {{ menuDir.isExpanded ? '一键折叠' : '一键展开' }}
          </el-button>
        </div>
      </template>
      <el-tabs v-model="menuDir.activeName" class="demo-tabs" tabPosition="left" @tab-click="handleClick">
        <el-tab-pane :label="item.T_name" :name="item.T_sys" v-for="item,index in menuDir.MenuData" :key="index">
          <el-tree
            :ref="(el: any) => { if (el) treeRefMap.set(item.T_sys, el) }"
            :key="`tree-${item.T_sys}-${treeKey}`"
            :data="item.T_sys === menuDir.activeName ? menuDir.tabsMenu : []"
            :props="{ label: 'T_name', children: 'Children' }"
            node-key="Id"
            :default-expand-all="menuDir.isExpanded"
            :default-checked-keys="item.T_sys === menuDir.activeName ? menuDir.defaultKeys : []"
            show-checkbox
            @check="checkChange"
          />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div style="border-top: 1px solid #dcdfe6;padding-top: 10px;">
          <el-button @click="dialog?.DialogClose()">取消</el-button>
          <el-button type="primary" @click="submit">立即提交</el-button>
        </div>
      </template>
    </Dialog>
    <Drawer ref="drawerRef" :handleClose="callbackDrawer">
      <template #header="{ params }">
        <h4 :id="params.titleId" :class="params.titleClass">{{ isNew ? '添加' : '编辑' }} - 角色</h4>
      </template>
      <el-form ref="ruleFormRef" :model="form" :rules="rules">
        <el-form-item label="角色名：" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" type="text" autocomplete="off" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth">
          <el-button v-if="isNew" color="#626aef" @click="AddUserName(ruleFormRef)">添加</el-button>
          <el-button v-else color="#626aef" @click="AddUserName(ruleFormRef)">修改</el-button>
        </el-form-item>
      </el-form>
    </Drawer>
  </div>
</template>

<style scoped lang="scss">
@import './index.scss';
@import '@/styles/var.scss';
.roles {
  @include f-direction;
}
/* fade */
.fade-leave-active,
.fade-enter-active {
  transition: all 1s;
}
.fade-enter-from {
  opacity: 0;
  transition: all 1s;
  transform: translateY(-60px);
}
.fade-leave-to {
  opacity: 0;
  transition: all 1s;
  transform: translateY(60px);
}
</style>
