import { ListIitem } from '@/api/base/BaseDataModel';
import { api_addDataPermission, api_deleteDataPermission, api_editDataPermission, api_getDataPermissionList } from '@/api/dataPermission/dataPermission';
import { DataPermissionDto, DataPermissionParam } from '@/api/dataPermission/dataPermissionModel';
import { ActionOptions } from '@/components/DropDownButtons/type';
import type { BasicTableProps } from '@/components/VxeTable';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useMessage } from '@/hooks/useMessage';
import { useQueryList } from '@/hooks/useQueryList';
import { EditType } from '@/type/BaseEnum';
import { flattenMenuArray } from '@/utils';
import { cloneDeep } from '@/utils/cloneDeep';
import timeFiltering from '@/utils/timeFiltering';
import { resCodeSuccess, useReturnData } from '@/utils/useReturnData';
import { Delete, Edit } from "@element-plus/icons-vue";
import { reactive, ref, unref, computed } from 'vue';
import useMenuTable from '../menu/useMenuTable';

const { resData } = useReturnData()
const { createConfirm } = useMessage()
/**
 * 数据权限列表数据处理
 * @returns 
 */
function useDataPermission(dataPermissionListOptions: BasicTableProps) {
    const dataPermissionListFormRef = ref()
    const dataPermissionAddRef = ref<{ show: Fn }>()
    const dataPermissionListState = reactive({
        loading: false,
    })
    const dataPermissionListParams = reactive<DataPermissionParam>({
        permissionName: undefined,
        menuId: undefined,
        entityName: undefined,
        tableName: undefined,
        pageNum: 1,
        pageSize: 10,
        total: 0
    })

    // 初始化数据
    const initList = async () => {
        const res = await api_getDataPermissionList(listParams)
        if(resCodeSuccess(res)) {
            dataPermissionListOptions.data = res.data.records
            dataPermissionListParams.total = res.data.total
        }
    }
    // 删除
    const deleteDataPermission = async (id) => {
        const res = await api_deleteDataPermission({ id })
        const resCode = resData(res, "删除成功")
        if(resCode !== 500) initList()
    }

    // 校验表单
    const { resetForm } = useEleFormValidate();
    const resetParams = () => {
        resetForm(unref(dataPermissionListFormRef))
    }
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<DataPermissionParam>(initList, resetParams, dataPermissionListParams)
    const hanleAdd = () => unref(dataPermissionAddRef)?.show()
    // 操作
    const handleClickChange = (row) => {
        const data = cloneDeep(row)
        switch (data.types) {
            case EditType.EDIT:
                unref(dataPermissionAddRef)?.show(data)
                break;
            case EditType.DELETE:
                createConfirm({
                    type: "warning",
                    message: "系统提示",
                    cancelButtonText: "取消",
                    confirmButtonText: "确定",
                    beforeClose: (action, instance, done) => {
                        if (action === "confirm") {
                            deleteDataPermission(data.id)
                        }
                        done()
                    },
                })
                break;
        }
    }
    // 新增、编辑
    const hanleSaveConfirm = async (params: DataPermissionDto, onclose: Fn, setLoading) => {
        try {
            if(params.id) {
                const res = await api_editDataPermission(params)
                const resCode = resData(res, '编辑成功')
                if(resCode !== 500) {
                    onclose()
                    initList()
                }
            } else {
                const res = await api_addDataPermission(params)
                const resCode = resData(res, '新增成功')
                if(resCode !== 500) {
                    onclose()
                    initList()
                }
            }
        } finally {
            setLoading(false)
        }
    }

    //表格数据获取
    const { menuTable } = useMenuTable()
    //菜单数据
    const menuList = computed(() => {
        return flattenMenuArray<ListIitem>(menuTable.list)
    })

    return {
        dataPermissionListState,
        dataPermissionListParams,
        dataPermissionListFormRef,
        dataPermissionAddRef,
        sizeChange, 
        currentChange, 
        searchBtn, 
        resetBtn,
        hanleAdd,
        handleClickChange,
        hanleSaveConfirm,
        menuList
    }
}

/**
 * 配置数据
 * @param params 
 */
function useDataPermissionModel() {
    // 数据权限表格配置
    const dataPermissionListOptions = reactive<BasicTableProps>({
        id: 'dataPermission_list_table',
        border: true,
        keepSource: true,
        showOverflow: true,
        height: 520,
        loading: false,
        stripe: true,
        rowConfig: { isHover: true, keyField: 'id' },
        columnConfig: { resizable: true },
        columns: [
            { type: "seq", title: '序号', width: 65 },
            { field: 'permissionName', title: '权限名称', minWidth: 120 },
            // { field: 'menuId', title: '菜单', minWidth: 100, slots: { default: 'menuId' } },
            { field: 'entityName', title: '实体名', minWidth: 110 },
            { field: 'dataBaseTypeName', title: '数据库类型', minWidth: 140 },
            { field: 'tableName', title: '表名', minWidth: 100 },
            {
                field: 'createTime',
                title: '创建时间',
                minWidth: 110,
                formatter: ({ row }) => {
                    return timeFiltering(row.createTime)
                }
            },
            { field: 'createUserName', title: '创建人', minWidth: 110 },
            { title: '操作', slots: { default: 'actions' }, width: 135, fixed: 'right' }
        ],
        data: []
    })

    // 操作类别 
    const dataPermissionActionOptions: ActionOptions[] = [
        {
            value: EditType.EDIT,
            label: "编辑",
            icon: Edit,
            color: "#02ABE8",
            permissions: ['sys:dataPermission:edit']
        },
        {
            value: EditType.DELETE,
            label: "删除",
            type: "danger",
            icon: Delete,
            permissions: ['sys:dataPermission:delete']
        },
    ]
    
    return {
        dataPermissionListOptions,
        dataPermissionActionOptions
    }
}

export {
    useDataPermission,
    useDataPermissionModel
}