<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 } from '@element-plus/icons-vue'
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'

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

const menuMap = new Map()
const isNew = ref(true)
let currentVal: any = {}
const SysList = ref<InSys[]>([])
const globalStore = GlobalStore()
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: globalStore.GET_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 getSysList = async () => {
  const { Data } = await User_Sys_List({ User_tokey: globalStore.GET_User_tokey })
  SysList.value = Data as InSys[]
  const promises = []
  for (let item of SysList.value) {
    promises.push(getMenuList(item.T_sys))
  }

  Promise.all(promises).then(res => {
    const menuListTemporary: any[] = []
    res.forEach((item: any) => {
      const { Children, T_permission } = item.Data.Menu[0]
      item.Data.Menu[0].children = Children
      if (['/account', 'mangage', '/salary', '/stock'].includes(T_permission)) {
        item.Data.Menu[0].father = true
        menuMap.set(T_permission, { code: item.code, children: [] })
      }
      if (item.Data.Menu_checked) {
        getPermissionArr(item.Data)
      }
      menuListTemporary.push(item.Data.Menu[0])
    })
    menuList.value = menuListTemporary
    setCheckedTreeKeys(permissionArr.value)
    console.log(permissionArr.value)
  })
}
const getMenuList = async (code: string) => {
  const res: any = await User_Power_Get({ User_tokey: globalStore.GET_User_tokey, T_code: code, T_id: currentVal.T_id })
  return {
    code,
    ...res
  }
}

const permissionArr = ref<string[]>([])
const getPermissionArr = (menu: any) => {
  const { Menu, Menu_checked } = menu
  const { Children, T_permission } = Menu[0]
  getCurrentFlatMenu(Children, Menu_checked, T_permission)
}

const getCurrentFlatMenu = (children: any[], arr: number[], permission: string) => {
  const fatherMenu = menuMap.get(permission)

  children.forEach((item: any) => {
    const index = arr.findIndex((num: any) => num === item.Id)
    if (item.Children) {
      getCurrentFlatMenu(item.Children, arr, permission)
    }
    if (index !== -1 && !item.Children) {
      permissionArr.value.push(item.T_permission)
      fatherMenu.children.push(item)
    }
  })
}
const setCheckedTreeKeys = (arr: string[]) => treeRef.value?.setCheckedKeys(arr, true)

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

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

const callbackDrawer = (done: Fn) => {
  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: globalStore.GET_User_tokey, T_name: form.name })
      } else {
        res = await User_Power_Edit({ User_tokey: globalStore.GET_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
        })
      }
    } else {
      return false
    }
  })
}

// 删除
const UserDelete = (row: any) => {
  ElMessageBox.confirm('您确定要删除吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res: any = await User_Power_Del({ User_tokey: globalStore.GET_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 treeRef = ref<InstanceType<typeof ElTree>>()
const menuList = ref<any[]>([])

/**
 * 返回拼接的 M + Id
 * @param children 菜单数组
 */
const getMontageRole = (children: any[]) => {
  let result = ''

  const getChildIds = (node: any) => {
    if (!node.Children) {
      return `M${node.Id}|`
    }
    let ids = node.Children.map((child: any) => {
      return getChildIds(child)
    })
    return `M${node.Id}|${ids.join('')}`
  }

  children.forEach((item: any) => {
    result += getChildIds(item)
  })
  return result
}
/**
 * 提交
 */
const append = async (data: any) => {
  const currentMenu = menuMap.get(data.T_permission)
  console.log(menuMap)

  const { code, children } = currentMenu

  let T_menu = getMontageRole(children)
  console.log(children)

  const params = {
    User_tokey: globalStore.GET_User_tokey,
    T_id: currentVal.T_id,
    T_code: code,
    T_menu
  }
  // const res = await User_Power_Edit_Menu(params)
  // if (res.Code === 200) {
  //   ElMessage.success('修改成功！')
  //   // dialog.value?.DialogClose()
  // }
}
let fatherData: any = {}
const checkChange = (data: any, check: boolean) => {
  let fatherData = menuMap.get(data.T_permission)
  if (['/base'].includes(data.T_permission)) {
    fatherData = menuMap.get('/stock')
  }

  if (check) {
    console.log(data, fatherData)
  }

  // console.log(data, check)
  // if (father) {
  //   fatherData = data
  //   fatherCheckHandle(data.Children, father, check)
  //   // console.log(father)
  //   return
  // }
  // const prevFather = menuMap.get(fatherData.T_permission)
  // console.log(fatherData, prevFather)

  // const children = prevFather?.children
  // // console.log(children)
  // if (check) {
  //   console.log(children)
  //   prevFather.children.push(data)
  // }
  // if (!father && !check) {
  //   const index = children.findIndex((item: any) => item.T_permission === data.T_permission)
  //   if (index !== -1) {
  //     console.log('-1')
  //     children.splice(index, 1)
  //   }
  // }
}

/**
 * 处理点击父级 tree 时的处理
 */
const fatherCheckHandle = (children: any[], father: any, check: boolean) => {
  if (check) {
    children.forEach((item: any) => {
      if (item.Children) {
        if (father.children.findIndex((child: any) => item.T_permission === child.T_permission) === -1) {
          father.children.push(item)
          fatherCheckHandle(item.Children, father, check)
        }
      } else {
        if (father.children.findIndex((child: any) => item.T_permission === child.T_permission) === -1) {
          console.log('push3')
          father.children.push(item)
        }
      }
    })
  }
}
/**
 * dialog 关闭回调
 */
const dialogCloseCallback = () => {
  nextTick(() => {
    menuMap.clear()
    permissionArr.value = []
    fatherData = {}
  })
}
</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" />
              <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">
      <template #header>
        <h3>编辑权限</h3>
      </template>
      <transition appear name="fade" mode="out-in">
        <el-tree
          ref="treeRef"
          :data="menuList"
          show-checkbox
          node-key="T_permission"
          :expand-on-click-node="false"
          :props="{ label: 'T_name', children: 'Children' }"
          @check-change="checkChange"
        >
          <template #default="{ data }">
            <div
              class="custom-tree-node"
              :style="{ 'border-bottom': data.Children && data.father ? ' 1px solid #ddd' : '' }"
            >
              <span>{{ data.T_name }}</span>
              <span v-if="data.Children && data.father">
                <el-button type="primary" size="small" @click="append(data)">提交</el-button>
              </span>
            </div>
          </template>
          <template #empty>
            <el-empty></el-empty>
          </template>
        </el-tree>
      </transition>
    </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>
