import { ListIitem } from "@/api/base/BaseDataModel";
import { api_getRoleDataPermission, api_getUserDataPermission, api_roleDataPermissionDelete, api_userDataPermissionDelete } from "@/api/dataPermission/dataPermission";
import { DataPermissionDto } from "@/api/dataPermission/dataPermissionModel";
import { SelectNode } from "@/api/dept/DeptModel";
import type { BasicTableProps, VxeGridInstance } from "@/components/VxeTable";
import { useEleFormValidate } from "@/hooks/useEleFormValidate";
import { useStateSystemType } from "@/store/list_systemType";
import { DialogModel } from "@/type/BastType";
import { flattenMenuArray } from "@/utils";
import { cloneDeep } from "@/utils/cloneDeep";
import { deal_FindItemName } from "@/utils/dealFindData";
import { validateFieldType } from "@/utils/feeSeting/validate";
import { isArrayLength } from "@/utils/is";
import { resCodeSuccess, useReturnData } from "@/utils/useReturnData";
import { ref, reactive, computed, unref, onMounted, nextTick, Ref } from "vue";

const { resData } = useReturnData()
/**
 * 数据权限设置
 * @returns
 */
function useDataPermissionAdd(
    dialog: DialogModel,
    onClose: Fn,
    onShow: Fn,
    setLoading: Fn,
    emit: Fn,
    props: Recordable
) {
    const storeSystemType = useStateSystemType();
    const dataPermissionsetSetFormRef = ref();
    const dataPermissionsetSetForm = reactive<DataPermissionDto>({
        id: undefined,
        permissionName: "",
        menuId: "",
        entityName: "",
        dataBaseType: undefined,
        tableName: "",
    });
    const dataPermissionSetState = reactive({
        rulesSet: {
            permissionName: [
                { required: true, message: "请输入权限名称", trigger: "blur" },
            ],
            menuId: [{ required: true, message: "请选择菜单", trigger: "change" }],
            entityName: [
                { required: true, message: "请输入实体名称", trigger: "blur" },
            ],
            dataBaseType: [
                { required: true, message: "请选择数据库类型", trigger: "change" },
            ],
            tableName: [{ required: true, message: "请输入表名", trigger: "blur" }],
        },
        loading: false,
        parentName: "",
    });
    // col宽度百分比
    const setFormItemWidth = computed(() => {
        return { width: `calc(100% - 32px)` };
    });
    const parentName = computed(() =>
        deal_FindItemName(dataPermissionsetSetForm.menuId, props.menuList)
    );

    onMounted(() => {
        storeSystemType.addDataBaseTypeList();
    });

    const initData = (data) => {
        dialog.title = "编辑数据权限";
        nextTick(() => {
            Object.keys(data).forEach((key) => {
                if (dataPermissionsetSetForm.hasOwnProperty(key)) {
                    if (data[key] || Number(data[key]) >= 0) {
                        dataPermissionsetSetForm[key] = data[key];
                    }
                }
            });
            dataPermissionSetState.parentName = unref(parentName);
        });
    };
    //选中上级的数据
    const select = (node: SelectNode) => {
        dataPermissionsetSetForm.menuId = node.id;
        dataPermissionSetState.parentName = node.name;
    };
    const show = (data) => {
        dialog.title = "新增数据权限";
        if (data && data.id) initData(data);
        onShow();
    };
    // 校验表单
    const { formValidate, resetForm } = useEleFormValidate();
    const onclose = () => {
        dataPermissionsetSetForm.id = undefined;
        dataPermissionSetState.parentName = "";
        resetForm(unref(dataPermissionsetSetFormRef));
        onClose();
    };
    const confirm = async () => {
        const isValidate = await formValidate(unref(dataPermissionsetSetFormRef));
        if (!isValidate) return;
        setLoading(true);
        emit("saveConfirm", dataPermissionsetSetForm, onclose, setLoading);
    };

    return {
        dataPermissionSetState,
        dataPermissionsetSetForm,
        dataPermissionsetSetFormRef,
        setFormItemWidth,
        select,
        show,
        onclose,
        confirm,
        storeSystemType,
    };
}

enum DataPermissionType {
    /**
     * 用户
     */
    USER = 'user',
    /**
     * 角色
     */
    ROLE = 'role'
}

/**
 * 用户数据权限设置
 * @returns
 */
function useDataPermissionSet(
    onClose: Fn,
    onShow: Fn,
    emit: Fn,
    props: Recordable,
    setLoading: Fn
) {
    const dataPermissionTableRef = ref<VxeGridInstance>()
    const assignAuthorityDataRef = ref<{ show: Fn }>();
    // 数据权限表格配置
    const dataPermissionOptions = reactive<BasicTableProps>({
        id: "financial_billList_table",
        border: true,
        keepSource: true,
        showOverflow: true,
        height: 520,
        loading: false,
        stripe: true,
        rowConfig: { isHover: true, keyField: "_id" },
        editConfig: {
            trigger: "click",
            mode: "row",
            autoClear: false,
            showIcon: false,
            showAsterisk: false,
        },
        editRules: {
            dataPermissionId: [{ message: '请选择权限名称', validator: validateFieldType }],
            dataPermissionType: [{ message: '请选择数据权限', validator: validateFieldType }],
        },
        columnConfig: { resizable: true },
        cellStyle: { height: "38px", padding: 0 },
        columns: [
            { type: "seq", title: "序号", width: 65 },
            {
                field: "dataPermissionId",
                title: "权限名称",
                minWidth: 110,
                editRender: {},
                slots: {
                    default: "default_dataPermissionId",
                    edit: "edit_dataPermissionId",
                },
            },
            {
                field: "dataPermissionType",
                title: "数据权限",
                minWidth: 110,
                editRender: {},
                slots: {
                    default: "default_dataPermissionType",
                    edit: "edit_dataPermissionType",
                },
            },
            {
                field: "dataPermissionDepartmentDtoList",
                title: "部门选择",
                minWidth: 180,
                editRender: {},
                slots: {
                    default: "default_dataPermissionDepartment",
                    edit: "edit_dataPermissionDepartment",
                },
            },
            {
                width: 68,
                align: "center",
                slots: { default: "default_action", header: "header_action" },
            },
        ],
        data: [],
    });
    const dataPermissionSetState = reactive({
        currentRowData: {} as Recordable,
        departmentName: "",//当前行激活显示的数据
    });
    // 
    const storeSystemType = useStateSystemType();
    //获取部门树数据
    const getLeftTreeData = computed(() => storeSystemType.getLeftTreeData);
    const flattenDepartmentList = computed(() => {
        return flattenMenuArray<ListIitem>(unref(getLeftTreeData))
    })
    const getDataPermissionList = computed(() => {
        return storeSystemType.getDataPermissionList.map((item) => {
            if (Number(item.value) >= 0) item.value = Number(item.value)
            return item
        })
    })
    onMounted(() => {
        storeSystemType.addDataPermissionList();
        storeSystemType.addDataPermissionTypeList();
    });
    const getDataType = computed(() => props.dataType)
    // 初始化数据
    const initData = async (params) => {
        dataPermissionSetState.currentRowData = params
        // 用户数据
        if (unref(getDataType) === DataPermissionType.USER) {
            const res = await api_getUserDataPermission({
                userId: params.id,
                dataPermissionId: params.dataPermissionId,
            });
            if (resCodeSuccess(res)) dataPermissionOptions.data = res.data;
        } else {
            // 角色数据
            const res = await api_getRoleDataPermission({
                roleId: params.id,
                dataPermissionId: params.dataPermissionId,
            });
            if (resCodeSuccess(res)) dataPermissionOptions.data = res.data;
        }
    };
    const show = (data) => {
        initData(data);
        onShow();
    };
    const onclose = () => {
        dataPermissionOptions.data = [];
        unref(dataPermissionTableRef)?.clearEdit()
        onClose();
    };
    // 保存
    const onconfirm = async () => {
        const $table = unref(dataPermissionTableRef)
        const isValidate = await $table?.validate(true)
        if (!isValidate) {
            setLoading(true)
            const currentRowData = dataPermissionSetState.currentRowData
            const newDataPermissionList = cloneDeep(dataPermissionOptions.data) as Recordable[]
            if (dataPermissionOptions.data && isArrayLength(dataPermissionOptions.data)) {
                newDataPermissionList.map((item) => {
                    if (currentRowData.id) {
                        // 用户 、角色
                        unref(getDataType) === DataPermissionType.USER ? 
                        item.userId = currentRowData.id : item.roleId = currentRowData.id;
                    }
                    if (item._id) delete item._id
                })
            }
            emit("saveConfirm", newDataPermissionList, onclose, setLoading);
        }
    };
    // 添加/删除
    const hanleAdd = () => {
        dataPermissionOptions.data?.push({
            dataPermissionDepartmentDtoList: [],
        });
    };
    const hanleDelete = async (scoped) => {
        if (scoped.row.id) {
            // 用户
            if (unref(getDataType) === DataPermissionType.USER) {
                const res = await api_userDataPermissionDelete({ id: scoped.row.id })
                resData(res, '删除成功')
            } else {
                // 角色
                const res = await api_roleDataPermissionDelete({ id: scoped.row.id })
                resData(res, '删除成功')
            }
        }
        const index = scoped.rowIndex
        dataPermissionOptions.data?.splice(index, 1);
    };
    const selectDepartment = (row) => {
        unref(assignAuthorityDataRef)?.show(
            row,
            unref(getLeftTreeData)
        );
    };
    // 显示部门
    const getDepartmentName = (departmentDtoList: Recordable[]): string => {
        if (!isArrayLength(departmentDtoList)) return ''
        const departmentNames: string[] = [];
        const departmentList = unref(flattenDepartmentList);
        for (const item of departmentDtoList) {
            const findObj = departmentList.find((fn) => fn.value === item.departmentId);
            if (findObj) {
                departmentNames.push(findObj.label);
            }
        }
        const departmentNamesStr = departmentNames.join(',')
        return departmentNamesStr
    };
    // 部门选择
    const changeChecked = (data) => {
        dataPermissionOptions.data?.map((item) => {
            if (item._id === data._id) {
                Object.assign(item, {
                    dataPermissionDepartmentDtoList: data.dataPermissionDepartmentDtoList,
                });
                dataPermissionSetState.departmentName = getDepartmentName(data.dataPermissionDepartmentDtoList);
            }
        });
    };
    // 点击表格是否显示当前部门文本
    const hanleCellClick = (scope) => {
        const $table = unref(dataPermissionTableRef)
        if (!$table) return
        const isEditByRow = $table.isEditByRow(scope.row)
        if (isEditByRow) return
        dataPermissionSetState.departmentName = getDepartmentName(scope.row.dataPermissionDepartmentDtoList);
    }

    return {
        dataPermissionOptions,
        dataPermissionTableRef,
        show,
        onclose,
        onconfirm,
        hanleAdd,
        hanleDelete,
        storeSystemType,
        assignAuthorityDataRef,
        selectDepartment,
        dataPermissionSetState,
        getDataPermissionList,
        getLeftTreeData,
        changeChecked,
        getDepartmentName,
        hanleCellClick
    };
}

/**
 * 权限名称过滤重复的数据-computed
 */
function useDataPermissionListComputed<T extends ListIitem>(tableList: BasicTableProps, permissionList: Ref<T[]>) {
    // 过滤权限类型
    const addFilterPermissionList = computed(() => {
        const PermissionId = tableList.data?.map(item => item.dataPermissionId).filter(j => String(j)) || []
        const PermissionList = unref(permissionList).filter(item => !PermissionId.includes(item.value))
        return PermissionList
    })

    // 合并当前权限类型以及过滤使用过的权限类型
    const filterOnPermissionList = (permissionId: number) => {
        const clonePermissionList = cloneDeep(unref(permissionList))
        // 过滤已选中的权限类型信息
        const filterData = clonePermissionList.filter(item => item.value === permissionId)
        // 合并没有选中的权限
        let concatPermission = [...filterData, ...unref(addFilterPermissionList)]
        return concatPermission
    }

    // 过滤权限明细-权限类型
    const oldPermissionList = computed(() => {
        const PermissionId = tableList.data?.map(item => item.dataPermissionId).filter(item2 => String(item2)) || []
        const PermissionList = unref(permissionList).filter(item => PermissionId.includes(item.value))
        return PermissionList
    })

    return {
        addFilterPermissionList,
        filterOnPermissionList,
        oldPermissionList
    }
}

export { useDataPermissionAdd, useDataPermissionSet, useDataPermissionListComputed, DataPermissionType };
