import {useInjectGlobalLoading} from "@/views/hooks/useGlobalLoading.js";
import {injectLocal, provideLocal} from "@vueuse/core";
import {getPaperClasses, getPaperClassRecords} from "@/api/dz/papers.js";
import {listToMap} from "@/utils/index.js";
import consts from "@/utils/consts.js";

const key = Symbol('PaperList')

const defaultOptions = {
    formDefine: {},
    ruleDefine: {},
    exportPath: '',
    downloadPath: '',
    queryRef: 'queryRef',
    formRef: 'formRef',
    rowKey: 'id'
}
export const useProvidePaperList = function (queryParams, opts = defaultOptions) {
    const options = {...defaultOptions, ...opts}
    const {proxy} = getCurrentInstance()
    const {loading} = useInjectGlobalLoading()

    const list = ref([])
    const open = ref(false)
    const showSearch = ref(true)
    const ids = ref([])
    const single = ref(true)
    const multiple = ref(true)
    const total = ref(0)

    const classList = ref([])

    const data = reactive({
        form: {...options.formDefine},
        page: {
            pageNum: 1,
            pageSize: 10
        },
        rules: {...options.ruleDefine}
    })

    const {page, form, rules} = toRefs(data)

    // 取消按钮
    function cancel() {
        open.value = false
        reset()
    }

    // 表单重置
    function reset() {
        form.value = {
            ...options.formDefine
        }
        proxy.resetForm(options.formRef)
    }

    /** 搜索按钮操作 */
    function handleQuery() {
        page.value.pageNum = 1
        getList()
    }

    /** 重置按钮操作 */
    function resetQuery() {
        proxy.resetForm(options.queryRef)
        handleQuery()
    }

    // 多选框选中数据
    function handleSelectionChange(selection) {
        ids.value = selection.map(item => item[options.rowKey])
        single.value = selection.length != 1
        multiple.value = !selection.length
    }

    const handleDownload = function (paper) {
        // TODO: 还不确定抽象方式，稍后再做
        proxy.download(options.downloadPath, {
            paperId: paper.id
        }, `${paper.paperName}_${new Date().getTime()}.xlsx`)
    }

    function getList() {
        loading.value = true

        const query = {
            ...page.value,
            ...toValue(queryParams)
        }
        getPaperClassRecords(query).then(response => {
            // 自动补全组卷类型名称
            const buildTypeMap = listToMap(consts.enums.buildTypes, i => i.id, i => i.name)
            response.rows.forEach(r => {
                if (r.buildTypeName) return
                r.buildTypeName = buildTypeMap[r.buildType] || r.buildType
            })
            list.value = response.rows
            total.value = response.total
        }).finally(() => loading.value = false)
    }

    onMounted(() => getList())
    onMounted(async () => {
        const res = await getPaperClasses()
        classList.value = res.data
    })

    const payload = {
        queryParams, form, rules,
        open, showSearch, ids, single, multiple,
        total, list, classList,
        handleQuery, resetQuery, handleSelectionChange, reset, cancel, getList
    }
    provideLocal(key, payload)
    return payload
}

export const useInjectPaperList = function () {
    return injectLocal(key)
}