<script setup lang="ts">
import AForm from '@/components/AForm/index.vue'
import { FormConfigType } from '@/components/AForm/type'
import { ToolbarConfigType } from '@/components/AToolbar/type'
import { ColumnConfigType } from '@/components/ATable/type'
import { StrAnyObj, StrAnyObjArr } from '@/typings'
import { useHandleData } from '@/utils/useHandleData'
import { getPageApi, getDetailApi, addApi, editApi, deleteApi } from '@/api/system/role'
import menuScope from './menuScope.vue'
import dataScope from './dataScope.vue'
import userAuth from './userAuth.vue'
import userUnAuth from './userUnAuth.vue'
import { useUserStore } from '@/stores/modules/user'

const userStore = useUserStore()

const queryRef = ref<InstanceType<typeof AForm>>()
const formRef = ref<InstanceType<typeof AForm>>()
const menuScopeRef = ref<InstanceType<typeof menuScope>>()
const dataScopeRef = ref<InstanceType<typeof dataScope>>()
const userAuthRef = ref<InstanceType<typeof userAuth>>()
const userUnAuthRef = ref<InstanceType<typeof userUnAuth>>()

const showQuery = ref<boolean>(true)
const selectKeys = ref<string[]>([])
const pageTotal = ref<number>(0)

const queryData = ref<StrAnyObj>({ pageNum: 1, pageSize: 10 })
const tableData = ref<StrAnyObjArr>([])
const formData = ref<StrAnyObj>({ status: 1, sort: 1, builtin: 0 })

const dialogTitle = ref<string>('')
const dialogVisible = ref<boolean>(false)

const queryConfig: FormConfigType[] = [
  {
    type: 'input',
    prop: 'name',
    label: '角色名称'
  },
  {
    type: 'input',
    prop: 'code',
    label: '角色编码'
  },
  {
    type: 'select',
    prop: 'builtin',
    label: '系统内置',
    dict: 'yes_no',
    if: () => userStore.superAdmin
  },
  {
    type: 'select',
    prop: 'status',
    label: '状态',
    dict: 'enable_disable'
  }
]

const toolbarConfig: ToolbarConfigType[] = [
  {
    common: 'search',
    click() {
      queryData.value.pageNum = 1
      getPage()
    }
  },
  {
    common: 'reset',
    click() {
      queryRef.value?.resetFields()
      getPage()
    }
  },
  {
    common: 'add',
    permissions: 'sysRole:add',
    click() {
      dialogVisible.value = true
      dialogTitle.value = '新增'
    }
  },
  {
    common: 'delete',
    permissions: 'sysRole:delete',
    disabled() {
      return selectKeys.value.length == 0
    },
    click() {
      handleRemove(selectKeys.value)
    }
  }
]

const columnConfig: ColumnConfigType[] = [
  {
    prop: 'name',
    label: '角色名称'
  },
  {
    prop: 'code',
    label: '角色编码'
  },
  {
    prop: 'builtin',
    label: '系统内置',
    dict: 'yes_no',
    if: () => userStore.superAdmin
  },
  {
    prop: 'status',
    label: '状态',
    dict: 'enable_disable'
  },
  {
    prop: 'sort',
    label: '排序'
  },
  {
    prop: 'remark',
    label: '备注',
    showOverflowTooltip: true
  },
  {
    width: 570,
    handleConfig: [
      {
        icon: 'menu',
        text: '菜单权限',
        permissions: 'sysRole:editMenuScope',
        if: (row) => userStore.superAdmin || row.builtin === 0,
        click(row) {
          menuScopeRef.value?.open(row)
        }
      },
      {
        icon: 'data-analysis',
        text: '数据权限',
        permissions: 'sysRole:editDataScope',
        if: (row) => userStore.superAdmin || row.builtin === 0,
        click(row) {
          dataScopeRef.value?.open(row)
        }
      },
      {
        icon: 'folder-add',
        text: '授权用户',
        permissions: 'sysRole:authUser',
        if: (row) => userStore.superAdmin || row.builtin === 0,
        click(row) {
          userAuthRef.value?.open(row)
        }
      },
      {
        icon: 'folder-delete',
        text: '取消授权',
        permissions: 'sysRole:unAuthUser',
        if: (row) => userStore.superAdmin || row.builtin === 0,
        click(row) {
          userUnAuthRef.value?.open(row)
        }
      },
      {
        common: 'update',
        permissions: 'sysRole:edit',
        if: (row) => userStore.superAdmin || row.builtin === 0,
        click(row) {
          dialogVisible.value = true
          dialogTitle.value = '编辑'
          getDetailApi({ id: row.id }).then((resp: StrAnyObj) => {
            formData.value = resp
          })
        }
      },
      {
        common: 'delete',
        permissions: 'sysRole:delete',
        if: (row) => userStore.superAdmin || row.builtin === 0,
        click(row) {
          handleRemove([row.id])
        }
      }
    ]
  }
]

const formConfig: FormConfigType[] = [
  {
    type: 'input',
    prop: 'name',
    label: '角色名称',
    rule: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'code',
    label: '角色编码',
    disabled() {
      return formData.value.id != undefined
    },
    rule: [{ required: true, message: '角色编码不能为空', trigger: 'blur' }]
  },
  {
    type: 'radio',
    prop: 'builtin',
    label: '系统内置',
    dict: 'yes_no',
    if: () => userStore.superAdmin,
    rule: [{ required: true, message: '系统内置不能为空', trigger: 'blur' }]
  },
  {
    type: 'radio',
    prop: 'status',
    label: '状态',
    dict: 'enable_disable',
    rule: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
  },
  {
    type: 'inputNumber',
    prop: 'sort',
    label: '排序',
    min: 0,
    precision: 0,
    rule: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'remark',
    label: '备注',
    itemType: 'textarea',
    rows: 5
  }
]

onMounted(() => {
  getPage()
})

function getPage() {
  getPageApi(queryData.value).then((resp) => {
    tableData.value = resp.records
    pageTotal.value = resp.total
  })
}

function tableSelectionChange(item: StrAnyObjArr) {
  selectKeys.value = item.map((item) => item.id)
}

function formSubmit() {
  formRef.value?.validate(() => {
    if (formData.value.id) {
      editApi(formData.value).then(() => {
        dialogVisible.value = false
        ElMessage.success('修改成功')
        getPage()
      })
    } else {
      addApi(formData.value).then(() => {
        dialogVisible.value = false
        ElMessage.success('新增成功')
        getPage()
      })
    }
  })
}

function formClosed() {
  formRef.value?.resetFields()
}

function handleRemove(idList: string[]) {
  useHandleData('是否确认删除？', () => {
    deleteApi({ idList }).then(() => {
      ElMessage.success('删除成功')
      getPage()
    })
  })
}
</script>

<template>
  <div>
    <el-card v-if="showQuery">
      <a-form ref="queryRef" v-model="queryData" :config="queryConfig" :span="6"> </a-form>
    </el-card>

    <a-table
      selection
      :data="tableData"
      :page-total="pageTotal"
      :toolbar-config="toolbarConfig"
      :column-config="columnConfig"
      v-model:showQuery="showQuery"
      v-model:page-num="queryData.pageNum"
      v-model:page-size="queryData.pageSize"
      @page-num-change="getPage"
      @page-size-change="getPage"
      @selection-change="tableSelectionChange"
    >
    </a-table>

    <a-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      @submit="formSubmit"
      @closed="formClosed"
    >
      <a-form ref="formRef" v-model="formData" :config="formConfig" :span="24"> </a-form>
    </a-dialog>

    <menu-scope ref="menuScopeRef" />
    <data-scope ref="dataScopeRef" />
    <user-auth ref="userAuthRef" />
    <user-un-auth ref="userUnAuthRef" />
  </div>
</template>
