<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 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 isNew = ref(true)
let currentVal: any = {}
const SysList = ref<InSys[]>([])
const globalStore = GlobalStore()
const formLabelWidth = ref('80px')
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 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' }
]

const getSysList = async () => {
  const { Data } = await User_Sys_List({ User_tokey: globalStore.GET_User_tokey })
  SysList.value = Data as InSys[]
  for await (let item of SysList.value) {
    getMenuList(item.T_sys)
  }
}

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 })
  const sys = SysList.value.find(item => item.T_sys === code) as InSys
  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 = ''
  childs.forEach((f: any) => {
    let str = 'M' + f.Id + '|'
    T_menu += str
  })
  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.success('修改成功！')
    dialog.value?.DialogClose()
    checkList.value = []
  }
}

// 添加角色
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()
}
</script>

<template>
  <div>
    <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="80%">
      <template #header>
        <h3>编辑权限</h3>
      </template>
      <el-row :gutter="24">
        <el-col :span="3"><div class="grid-content b-radius-4">功能模块</div></el-col>
        <el-col :span="18"><div class="grid-content b-radius-4">权限</div></el-col>
        <el-col :span="3"><div class="grid-content b-radius-4">操作</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 b-radius-4">
            <el-button type="success" link>{{ item.T_name }}</el-button>
          </div></el-col
        >
        <el-col :span="18"
          ><div class="grid-content grid-active b-radius-4">
            <transition appear name="fade-transform" mode="out-in">
              <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>
            </transition>
          </div>
        </el-col>
        <el-col :span="3"
          ><div class="grid-content b-radius-4">
            <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>
  </div>
</template>

<style scoped lang="scss">
@import './index.scss';
/* fade-transform */
.fade-transform-leave-active,
.fade-transform-enter-active {
  transition: all 0.5s;
}
.fade-transform-enter-from {
  opacity: 0;
  transition: all 0.5s;
  transform: translateY(-30px);
}
.fade-transform-leave-to {
  opacity: 0;
  transition: all 0.5s;
  transform: translateY(30px);
}
</style>
