import type { BasicTableProps } from '@/components/VxeTable';
import { UserMoneyDetailParam } from '@/api/usermoneysum/apiUserMoneySumModel';
import { ActionOptions } from '@/components/DropDownButtons/type';
import { useDropDownData } from '@/hooks/useDropDownData';
import { usePersonnel } from '@/store/list_personnel';
import { BaseFeesetAction } from '@/type/BaseFeesetAction';
import { DocumentChecked } from "@element-plus/icons-vue";
import { useQueryList } from '@/hooks/useQueryList';
import { useReturnData } from '@/utils/useReturnData';
import { useErrorConfirm } from '@/utils/useErrorConfirm';
import { useMessage } from '@/hooks/useMessage';
import { ref, reactive, unref, computed, onBeforeMount, onMounted, onActivated } from 'vue';
import { getMonthStartAndEndDates } from '@/utils/dateTimeStr';
import { isArray, isBoolean } from '@/utils/is';
import { api_downloadMoneyRecharge, api_UserBalance, api_UserMoneyDetail } from '@/api/usermoneysum/apiUserMoneySum';
import { useApiDownTemplate } from '@/hooks/useApiDownTemplate';
import { ListIitem } from '@/api/base/BaseDataModel';

const { createMessage, createConfirm } = useMessage()
const { report } = useErrorConfirm()
const { resData } = useReturnData()
/**
 * 充值记录
 * @returns 
 */
function userMoneyRecharge(moneyRechargeGridOptions: BasicTableProps) {
    const {
        storeDropDownData,
        customertList,
        currencyList,
        branchCompanyCustomers,
        reportQueryDateTypeList,
        allPaymentPlatformList
    } = useDropDownData()
    const storePersonnel = usePersonnel()
    // 业务员
    const getSalesmanUsesList = computed(() => storePersonnel.getSalesmanUsesList)
    // 表单数据
    const queryMoneyRechargeForm = reactive<UserMoneyDetailParam>({
        reportQueryDateType: 1,
        operatingType: 0,//操作类型-默认充值
        customerId: undefined,//客户编号
        currencyCode: undefined,//币种
        paymentType: undefined,//支付类型
        orgId: undefined,//分公司编号
        accountPeriod: undefined,//业务员
        transactionNumber: undefined,//交易号
        beginDate: undefined,//起始时间
        endDate: undefined,//结束时间
        consumeFlag: 0,//消费记录
        pageNum: 1,
        pageSize: 10,
        total: 10,
    })
    // 列表数据
    const moneyRechargeState = reactive({
        loading: false,
        dateArr: [] as Recordable,
        dateTypeList: [
            { value: 1, label: '充值时间' },
            { value: 0, label: '创建时间' },
        ] as ListIitem[]
    })
    // 操作类别
    const actionOptions: ActionOptions[] = [
        {
            value: BaseFeesetAction.BALANCED,
            label: "平账",
            type: "success",
            icon: DocumentChecked,
            permissions: ['sys:userMoneyDetail:balance']
        },
    ]
    // 接收传递的参数
    const getStateData = () => {
        // 接收另一个页面传递的参数
        const state = history.state
        if (state.customerId) {
            queryMoneyRechargeForm.customerId = String(state.customerId)
            history.state.customerId = undefined
        }
        if(state.periodBeginDate && state.periodEndDate) {
            moneyRechargeState.dateArr = [state.periodBeginDate, state.periodEndDate]
            queryMoneyRechargeForm.beginDate = state.periodBeginDate
            queryMoneyRechargeForm.endDate = state.periodEndDate
            history.state.periodBeginDate = undefined
            history.state.periodEndDate = undefined
        }
    }
    onBeforeMount(() => {
        initStartAndEndDates()
        getStateData()
        storePersonnel.addGetSalesmanUserList()
    })
    onActivated(() => {
        const state = history.state
        if (state.customerId) {
            initStartAndEndDates()
            getStateData()
            searchBtn()
        }
    })
    // 获取客户名称
    const hanleCustomer = (val) => {
        const findObj = unref(customertList).find(item => item.value === val)
        queryMoneyRechargeForm.customerName = findObj?.label
    }
    // 分公司名称
    const changeBranchCompanyName = (val) => {
        const findObj = unref(branchCompanyCustomers).find(item => item.value === val)
        queryMoneyRechargeForm.orgName = findObj?.label
    }

    // 充值记录导出
    const { templateLoading: moneyRechargeLoading, hanleOpenDownload: downloadMoneyRecharge } = useApiDownTemplate(api_downloadMoneyRecharge)
    const exportMoneyRecharge = async () => {
        // 其他条件都必须加上时间范围，并且最大时间范围不能超过一个月
        const verifys = await Promise.all([verifyForm(queryMoneyRechargeForm, 'beginDate'), verifyForm(queryMoneyRechargeForm, 'endDate')])
        if (!verifys.every(isIt => isIt)) {
            createMessage.warning('起始与结束时间不能为空！')
            return false
        }
        downloadMoneyRecharge(queryMoneyRechargeForm)
    }
    // 重置表单
    const resetParams = () => {
        for (const key of Object.keys(queryMoneyRechargeForm)) {
            if (isBoolean(queryMoneyRechargeForm[key])) {
                queryMoneyRechargeForm[key] = true;
            } else if (isArray(queryMoneyRechargeForm[key])) {
                queryMoneyRechargeForm[key] = [];
            } else {
                // 否则设置为undefined
                queryMoneyRechargeForm[key] = undefined;
            }
        }
        queryMoneyRechargeForm.total = 0
        queryMoneyRechargeForm.operatingType = 0
        queryMoneyRechargeForm.consumeFlag = 0
        initStartAndEndDates()
    }

    // 判断键值是否为空
    const verifyForm = async (obj: Recordable, key: string) => {
        if (obj.hasOwnProperty(key)) {
            const value = obj[key];
            return Array.isArray(value) && value.length > 0 || typeof value === 'string' && value.length > 0;
        }
        return false;
    }

    const startAndEndDates = getMonthStartAndEndDates()
    // 初始化列表数据
    const initList = async () => {
        try {
            // 交易号的查询条件
            if (await verifyForm(listParams, 'transactionNumber')) {
                initUserMoneyDetail()
                return false
            }
            // 其他条件都必须加上时间范围，并且最大时间范围不能超过一个月
            const verifys = await Promise.all([verifyForm(listParams, 'beginDate'), verifyForm(listParams, 'endDate')])
            if (!verifys.every(isIt => isIt)) {
                createMessage.warning('起始与结束时间不能为空！')
                return false
            }
            initUserMoneyDetail()
        } catch (error) {
            report(error)
        }
    }

    const initUserMoneyDetail = async () => {
        try {
            moneyRechargeState.loading = true
            moneyRechargeGridOptions.loading = true
            const res = await api_UserMoneyDetail(listParams)
            if (res.code == 200) {
                moneyRechargeGridOptions.data = res.data.records
                queryMoneyRechargeForm.total = res.data.total;
            }
        } catch (error) {
            report(error)
        } finally {
            moneyRechargeState.loading = false
            moneyRechargeGridOptions.loading = false
        }
    }

    // 扁平化起始结束时间
    const changeDateArr = (dateArr) => {
        if (dateArr) {
            const [beginDate, endDate] = dateArr
            queryMoneyRechargeForm.beginDate = beginDate
            queryMoneyRechargeForm.endDate = endDate
        } else {
            queryMoneyRechargeForm.beginDate = undefined
            queryMoneyRechargeForm.endDate = undefined
        }
    }
   
    // 初始化默认时间
    const initStartAndEndDates = () => {
        const [beginDate, endDate] = startAndEndDates
        moneyRechargeState.dateArr = startAndEndDates
        queryMoneyRechargeForm.beginDate = beginDate
        queryMoneyRechargeForm.endDate = endDate
    }

    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<UserMoneyDetailParam>(initList, resetParams, queryMoneyRechargeForm)

    // 平账
    const hanleBalanced = async (data) => {
        const res = await api_UserBalance(data)
        resData(res, '平账成功！')
    }
    // 操作
    const handleClickChange = async (data) => {
        // debugger
        switch (data.types) {
            case BaseFeesetAction.BALANCED://平账
                if (data.feeType === 1 || (data.hedgeFlag != null && data.hedgeFlag != "")) {
                    createMessage.warning('非原始数据或新数据不允许再次平账！')
                    return;
                }
                createConfirm({
                    type: "warning",
                    title: "系统提示",
                    message: "是否进行平账?",
                    cancelButtonText: "取消",
                    confirmButtonText: "确定",
                    beforeClose: (action, instance, done) => {
                        if (action === "confirm") {
                            hanleBalanced(data)
                        }
                        done()
                    },
                })
                break;
            default:
                break;
        }
    }
    onMounted(() => {
        storeDropDownData.addCurrencyList()
        storeDropDownData.addCustomertList()
        storeDropDownData.addBranchCompanyCustomers()
        storeDropDownData.addReportModelTypeList()
        storeDropDownData.addAllPaymentPlatformList()
    })

    return {
        queryMoneyRechargeForm,
        moneyRechargeState,
        listParams,
        actionOptions,
        searchBtn,
        resetBtn,
        moneyRechargeLoading,
        exportMoneyRecharge,
        hanleCustomer,
        sizeChange,
        currentChange,
        handleClickChange,
        changeBranchCompanyName,
        changeDateArr,
        customertList,
        currencyList,
        branchCompanyCustomers,
        reportQueryDateTypeList,
        getSalesmanUsesList,
        allPaymentPlatformList
    }
}

export {
    userMoneyRecharge
}