<template>
  <div class="main-content">
    <BaseTable
      :tableHeader="tableHeader"
      :tableData="tableData"
      :tableOperate="tableOperate"
      :searchParams="searchParams"
      @searchFn="searchFn"
      @resetFn="resetFn"
      @addFn="addFn"
      @batchDelFn="batchDelFn"
    >
      <template #search>
        <el-form-item label="角色名称">
          <el-input v-model.trim="searchParams.roleCnName" placeholder="请输入角色名称" />
        </el-form-item>
      </template>
    </BaseTable>

    <el-dialog :title="formDialog.title" v-model="formDialog.visible" :close-on-click-modal="false">
      <el-form ref="formRef" size="small" label-width="120px" :model="formDialog.formData" :rules="formDialog.formRules">
        <el-form-item label="角色名称" prop="roleCnName">
          <el-input v-model.trim="formDialog.formData.roleCnName" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model.trim="formDialog.formData.roleCode" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model.trim="formDialog.formData.roleDesc" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" :loading="formDialog.loading" @click="submitFn">确定</el-button>
        <el-button @click="cancelFn">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { createRole, updateRole, removeRole, queryRoleList } from '@/api/role'
import type { FormInstance, FormRules } from 'element-plus'

const formRef = ref<FormInstance>()

const defaultSearch = { current: 1, size: 10, total: 0 }

const searchParams = reactive({
  ...defaultSearch,
  roleCnName: ''
})

const tableHeader = [
  { label: '角色名称', prop: 'roleCnName', align: 'center' as const, minWidth: 120 },
  { label: '角色编码', prop: 'roleCode', align: 'center' as const, minWidth: 120 },
  { label: '角色描述', prop: 'roleDesc', align: 'center' as const, minWidth: 200 },
  { label: '创建时间', prop: 'createTime', align: 'center' as const, minWidth: 160 }
]

const tableData = ref<any[]>([])

const tableOperate = [
  { label: '编辑', type: 'primary', icon: 'el-icon-edit', func: (row: any) => editFn(row) },
  { label: '删除', type: 'danger', icon: 'el-icon-delete', func: (row: any) => delFn(row) }
]

const formDialog = reactive({
  title: '',
  visible: false,
  loading: false,
  formData: {} as any,
  formRules: {
    roleCnName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    roleCode: [{ required: true, message: '请输入角色编码', trigger: 'blur' }]
  } as FormRules
})

function searchFn(isReset = false) {
  if (isReset) Object.assign(searchParams, defaultSearch)
  queryRoleList(searchParams).then(
    (res: any) => {
      tableData.value = res.data || []
      searchParams.total = (res.data || []).length
    },
    (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  )
}

function resetFn() {
  Object.assign(searchParams, defaultSearch, { roleCnName: '' })
  searchFn()
}

function addFn() {
  formDialog.title = '新增'
  formDialog.visible = true
  formDialog.loading = false
  formDialog.formData = {}
}

function editFn(row: any) {
  formDialog.title = '编辑'
  formDialog.loading = false
  formDialog.formData = { ...row }
  formDialog.visible = true
}

function cancelFn() {
  formDialog.visible = false
  formDialog.formData = {}
  formRef.value?.resetFields()
}

function submitFn() {
  if (!formRef.value) return
  formDialog.loading = true
  formRef.value.validate((valid: boolean) => {
    if (!valid) { formDialog.loading = false; return }
    const api = formDialog.formData.id ? updateRole : createRole
    api(formDialog.formData).then(
      () => {
        ElMessage.success(formDialog.formData.id ? '修改成功' : '新增成功')
        formDialog.visible = false
        formDialog.loading = false
        searchFn(true)
      },
      (error: any) => {
        ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
        formDialog.loading = false
      }
    )
  })
}

function delFn(row: any) {
  ElMessageBox.confirm('此操作将删除该记录, 是否继续?', '提示', { type: 'warning' }).then(() => {
    removeRole({ id: row.id }).then(
      () => { ElMessage.success('删除成功'); searchFn(true) },
      (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
    )
  })
}

function batchDelFn(rows: any[]) {
  if (!rows || rows.length === 0) { ElMessage.warning('请选择要删除的记录'); return }
  ElMessageBox.confirm('此操作将删除该记录, 是否继续?', '提示', { type: 'warning' }).then(() => {
    Promise.all(rows.map((row) => removeRole({ id: row.id }))).then(
      () => { ElMessage.success('删除成功'); searchFn(true) },
      (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
    )
  })
}

searchFn()
</script>
