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

const globalStore = GlobalStore()
// 权限
const dialog = ref()
const TableRef = ref()
let currentVal: any = {}
const DialogOpen = async (row: any) => {
  currentVal = row
  await getSysList()
  dialog.value.DialogOpen()
}

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

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

let SysList = ref<InSys[]>([])
const getSysList = async () => {
  const { Data } = await User_Sys_List({ User_tokey: globalStore.GET_User_tokey })
  SysList.value = Data as InSys[]
}
const getMenuList = async (code: string) => {
  // User_Power_Get
  const res: any = await User_Power_Get({ User_tokey: globalStore.GET_User_tokey, T_code: code, T_id: currentVal.T_id })
  const sys = SysList.value.find(item => item.T_sys === code) as InSys
  console.log(res)
  sys.children = res.Data.Menu[0].Children
  if (res.Data.Menu_checked) {
    sys.checkList = sys.children.map((m: any) => {
      if (res.Data.Menu_checked.includes(m.Id)) return m.T_name
    })
  } else {
    sys.checkList = []
  }
}
const submitUserRole = async (item: InSys) => {
  let Sys: any = SysList.value.find(sys => item.T_sys === sys.T_sys)
  let childs = Sys?.children.filter((child: InSys) => Sys.checkList.includes(child.T_name))
  let T_menu = ''
  if (childs.length > 1) {
    childs.forEach((f: any) => {
      let str = 'M' + f.Id + '|'
      T_menu += str
    })
  } else {
    T_menu = 'M' + childs[0].Id
  }
  const params = {
    User_tokey: globalStore.GET_User_tokey,
    T_id: currentVal.T_id,
    T_code: item.T_sys,
    T_menu
  }

  const res = await User_Power_Edit_Menu(params)
  if (res.Code === 200) {
    ElMessage({
      type: 'success',
      message: '修改成功！'
    })
    dialog.value.DialogClose()
    checkList.value = []
  }
}

const initParam = {
  User_tokey: globalStore.GET_User_tokey,
  T_name: ''
}

// 添加角色
const drawerRef = ref()
const ruleFormRef = ref<FormInstance>()
const formLabelWidth = ref('80px')
const isNew = ref(true)
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
})
type Fn = () => void
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 form = reactive({
  name: '',
  id: ''
})
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 = false
        })
      }
    } else {
      console.log('error submit!')
      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({
          type: 'success',
          message: '删除成功！'
        })
        nextTick(() => {
          TableRef.value.getTableList()
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'warning',
        message: '取消成功！'
      })
    })
}

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

<template>
  <TableBase ref="TableRef" :columns="columns" :requestApi="User_Power_List" :initParam="initParam">
    <template #table-header>
      <div class="input-suffix">
        <el-row :gutter="20">
          <el-col :span="12">
            <span class="ml-3 w-35 text-gray-600 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="80%">
    <template #header>
      <h3>编辑权限</h3>
    </template>
    <el-row :gutter="24">
      <el-col :span="3"><div class="grid-content">功能模块</div></el-col>
      <el-col :span="18"><div class="grid-content">权限</div></el-col>
      <el-col :span="3"><div class="grid-content">操作</div></el-col>
    </el-row>
    <el-row :gutter="24" v-for="item in SysList" :key="item.T_sys">
      <el-col :span="3"
        ><div class="grid-content">
          <el-button type="success" link @click="getMenuList(item.T_sys)">{{ item.T_name }}</el-button>
        </div></el-col
      >
      <el-col :span="18"
        ><div class="grid-content grid-active">
          <el-checkbox-group v-model="item.checkList" v-if="item.children">
            <el-checkbox :label="child.T_name" v-for="child in item.children" :key="'rr' + child.Id">{{
              child.T_name
            }}</el-checkbox>
          </el-checkbox-group>
        </div>
      </el-col>
      <el-col :span="3"
        ><div class="grid-content">
          <el-button type="primary" @click="submitUserRole(item)">提交</el-button>
        </div></el-col
      >
    </el-row>
  </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>
</template>

<style scoped lang="scss">
@import './index.scss';
</style>
