import type { BasicTableProps, VxeGridInstance } from '@/components/VxeTable';
import { CustomerBillParam } from '@/api/accountPeriod/accountPeriodModel';
import { useDropDownData } from '@/hooks/useDropDownData';
import { ref, reactive, computed, onBeforeMount, unref, Ref } from 'vue';
import { useQueryList } from '@/hooks/useQueryList';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { api_customerBillList, api_customerBillReportDownload } from '@/api/accountPeriod/accountPeriod';
import { resCodeSuccess } from '@/utils/useReturnData';
import { ListIitem } from '@/api/base/BaseDataModel';
import { formatDate, getCurrentDateAndPretDate } from '@/utils/dateTimeStr';
import { useRouter } from 'vue-router';
import { usePersonnel } from '@/store/list_personnel';
import { useApiDownTemplate } from '@/hooks/useApiDownTemplate';
import { isArrayLength } from '@/utils/is';
import { useMessage } from '@/hooks/useMessage';

const { createMessage } = useMessage()
/**
 * 客户账单基础数据处理
 * @returns 
 */
function useCustomerBill(customerBillOptions: BasicTableProps, customerBillTableRef: Ref<VxeGridInstance | undefined>) {
    const { push } = useRouter()
    const { 
        storeDropDownData, 
        customertList, 
        accountPeriodTypeList,
        branchCompanyCustomers,
        currencyList
    } = useDropDownData()
    const storePersonnel = usePersonnel()
    // 业务员
    const getSalesmanUsesList = computed(() => storePersonnel.getSalesmanUsesList)
    const customerBillFormRef = ref()
    const customerBillParams = reactive<CustomerBillParam>({
        customerId: undefined,
        salesmanId: undefined,
        accountPeriod: undefined,
        billDate: undefined,
        status: undefined,
        beginDate: undefined,
        endDate: undefined,
        currencyCode: undefined,
        haveExpenditure: true,
        isInterceptCustomers: undefined,
        dateType: 0,
        pageNum: 1,
        pageSize: 10,
        total: 10,
    })
    const customerBillState = reactive({
        loading: false,
        statusList: [
            { value: 0, label: '未还清' },
            { value: 1, label: '已还清' },
        ] as ListIitem[],
        dateTypeList: [
            { value: 0, label: '账期起始时间' },
            { value: 1, label: '账单日期' },
            { value: 2, label: '还款日期' },
        ] as ListIitem[],
        isInterceptCustomersList: [
            { value: true, label: '是' },
            { value: false, label: '否' },
        ],
        dateArr: [] as string[]
    })
    // 初始化
    const initList = async () => {
        try {
            customerBillState.loading = true
            customerBillOptions.loading = true
            const res = await api_customerBillList(listParams)
            if (resCodeSuccess(res)) {
                customerBillOptions.data = res.data.records
                customerBillParams.total = res.data.total
            }
        } finally {
            customerBillState.loading = false
            customerBillOptions.loading = false
        }
    }
    // 重置
    const { resetForm } = useEleFormValidate()
    const resetParams = () => {
        resetForm(customerBillFormRef.value)
        customerBillParams.dateType = 0
        const { formattedDate, lastWeekDate } = getCurrentDateAndPretDate()
        customerBillParams.beginDate = formattedDate
        customerBillParams.endDate = formattedDate
        customerBillState.dateArr = [formattedDate, formattedDate]
    }
    // 清空时间
    const clearDate = () => {
        customerBillParams.beginDate = undefined
        customerBillParams.endDate = undefined
        customerBillState.dateArr = []
    }
    onBeforeMount(() => {
        storeDropDownData.addCustomertList()
        storeDropDownData.addAccountPeriodTypeList()
        storeDropDownData.addBranchCompanyCustomers()
        storePersonnel.addGetSalesmanUserList()
        storeDropDownData.addCurrencyList()
        const { formattedDate, lastWeekDate } = getCurrentDateAndPretDate()
        customerBillParams.beginDate = formattedDate
        customerBillParams.endDate = formattedDate
        customerBillState.dateArr = [formattedDate, formattedDate]
    })
    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<CustomerBillParam>(initList, resetParams, customerBillParams)
    // 起始时间、结束时间
    const changeDate = (date: Date[]) => {
        if (date && date.length > 0) {
            customerBillParams.beginDate = formatDate(date[0])
            customerBillParams.endDate = formatDate(date[1])
        } else {
            clearDate()
        }
    }
    // 跳转明细
    const hanleGoDetail = (row: Recordable) => {
        push({
            name: 'userMoneyDetail',
            state: {
                customerId: row.customerId,
                periodBeginDate: row.periodBeginDate,
                periodEndDate: row.periodEndDate,
            },
            params: {
                customerId: row.customerId,
            }
        })
    }
    // 客户账单报表下载
    const { templateLoading: customerBillReportLoading, hanleOpenDownload: downloadCustomerBillReport } = useApiDownTemplate(api_customerBillReportDownload)
    const reportDownloadBtn = () => {
        downloadCustomerBillReport(customerBillParams)
    }

    // 向上取整
    const ceilToDecimals = (num, decimals) => {
        const factor = Math.pow(10, decimals)
        return Math.ceil(num * factor) / factor
    }
    // 汇总
    const summaryShowRef = ref<{ show: Fn }>()
    const summaryBtn = () => {
        const $table = unref(customerBillTableRef)
        if(!$table) return
        const checkData = $table.getCheckboxRecords()
        if (!isArrayLength(checkData)) {
            createMessage.warning('请勾选需要汇总的数据！')
            return
        }
        const checkCustomerId = checkData.every(item => item.customerId === checkData[0].customerId)
        if (!checkCustomerId) {
            createMessage.warning('只能勾选同一客户数据！')
            return
        }
        const summaryData = new Map()
        checkData.forEach((item) => {
            isArrayLength(item.customerBillCurrencyCodeDetailDtoList) && item.customerBillCurrencyCodeDetailDtoList.forEach((item2) => {
                if (summaryData.has(item2.currencyCode)) {
                    const sumData = summaryData.get(item2.currencyCode)
                    sumData.paymentSum = ceilToDecimals(sumData.paymentSum + item2.payment, 2)
                    sumData.incomeSum = ceilToDecimals(sumData.incomeSum + item2.income, 2)
                    sumData.expenditureSum = ceilToDecimals(sumData.expenditureSum + item2.expenditure, 2)
                } else {
                    summaryData.set(
                        item2.currencyCode, 
                        { 
                            paymentSum: item2.payment,
                            incomeSum: item2.income,
                            expenditureSum: item2.expenditure,
                        }
                    )
                }
            })
        })
        const targetData = Array.from(summaryData, ([currencyCode, data]) => ({ currencyCode, ...data }));
        unref(summaryShowRef)?.show(targetData)
    }
    
    return {
        customerBillFormRef,
        customerBillParams,
        customerBillState,
        customertList, 
        accountPeriodTypeList, 
        sizeChange, 
        currentChange, 
        searchBtn, 
        resetBtn,
        changeDate,
        clearDate,
        hanleGoDetail,
        getSalesmanUsesList,
        branchCompanyCustomers,
        reportDownloadBtn,
        customerBillReportLoading,
        summaryBtn,
        currencyList,
        summaryShowRef
    }
}

export {
    useCustomerBill
}