import { api_deOverseasReportdownload, api_DownloadCompanyProfit, api_FangCangMoneyReportdownload, api_jianAiMoneyReportdownload, api_UserBalance, api_UserMoneyDetail, api_xbAndKpReportdownload, api_XiKeMoneyReportdownload, api_YingChiMoneyReportdownload } from '@/api/usermoneysum/apiUserMoneySum';
import { UserMoneyDetailParam } from '@/api/usermoneysum/apiUserMoneySumModel';
import { ActionOptions } from '@/components/DropDownButtons/type';
import { BasicTableProps } from '@/components/VxeTable';
import { useApiDownTemplate } from '@/hooks/useApiDownTemplate';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useMessage } from '@/hooks/useMessage';
import { useQueryList } from '@/hooks/useQueryList';
import { usePersonnel } from '@/store/list_personnel';
import { FeeReportTemplateType } from '@/type/BaseBusinessFeeseType';
import { BaseFeesetAction } from '@/type/BaseFeesetAction';
import { getMonthStartAndEndDates } from '@/utils/dateTimeStr';
import { format, isArray, isArrayLength, isBoolean, isNumber, roundToDecimals } from '@/utils/is';
import { useErrorConfirm } from '@/utils/useErrorConfirm';
import { useReturnData } from '@/utils/useReturnData';
import { Tickets, DocumentChecked } from "@element-plus/icons-vue";
import { ref, reactive, unref, computed, onMounted, onBeforeMount, onActivated } from 'vue';

const { createMessage, createConfirm } = useMessage()
const { report } = useErrorConfirm()
const { resData } = useReturnData()
/**
 * 查看客户总账
 */
function userMoneySumDetailList(usermoneyGridOptions: BasicTableProps) {
    const {
        storeDropDownData,
        customertList,
        currencyList,
        customerTypeList,
        operatingTypeList,
        feeDataTypeList,
        branchCompanyCustomers,
        productList,
        countryList,
        reportModelTypeList,
        reportQueryDateTypeList,
        accountPeriodTypeList,
        allPaymentPlatformList
    } = useDropDownData()
    const storePersonnel = usePersonnel()
    // 业务员
    const getSalesmanUsesList = computed(() => storePersonnel.getSalesmanUsesList)
    // 修改不显示充值类型操作类型
    const getOperatingTypeList = computed(() => {
        return unref(operatingTypeList).filter(item => item.value !== 0)
    })
    // 表单数据
    const queryUserMoneySumDetailForm = reactive<UserMoneyDetailParam>({
        orderIdList: [],//单号
        customerId: undefined,//客户编号
        customerName: undefined,//客户名称
        currencyCode: undefined,//币种
        operatingType: undefined,//操作类型
        customerType: undefined,//费用类型
        productId: undefined,//产品编号
        orgId: undefined,//分公司编号
        orgName: undefined,
        countryCode: undefined,//国家/地区编号
        transactionNumber: undefined,//交易号
        validData: true,//有效数据
        subjectType: undefined,//主体类型
        dateArr: null,////起始时间与结束时间
        beginDate: undefined,//起始时间
        endDate: undefined,//结束时间
        billDate: undefined,//账单时间
        reportQueryDateType: 0,//时间类型 1 充值时间 0 创建时间
        salesmanId: undefined,//账期类型
        accountPeriod: undefined,//业务员
        consumeFlag: 1,
        pageNum: 1,
        pageSize: 10,
        total: 10,
    })
    // 列表数据
    const dealData = reactive({
        mainList: [],
        validData: [
            {
                value: true,
                label: '有效数据'
            },
            {
                value: false,
                label: '全部数据'
            }
        ],
        loading: false,
        isOrderIdList: false,//显示/隐藏输入框框
        inputMultiOrders: '',//单号文本框1
        inputOrders: '',//单号文本框2
        reportType: 0,//报表类型
    })
    // 操作类别
    const actionOptions: ActionOptions[] = [
        {
            value: BaseFeesetAction.DETAIL,//状态
            label: "明细",//文本
            type: "primary",//按钮样式
            icon: Tickets,//按钮图标
            permissions: []
        },
        // {
        //     value: BaseFeesetAction.BALANCED,
        //     label: "平账",
        //     type: "success",
        //     icon: DocumentChecked,
        //     permissions: ['sys:userMoneyDetail:balance']
        // },
    ]
    const queryExpenseItemDetailRef = ref<{ show: Fn }>()

    // 接收传递的参数
    const getStateData = () => {
        // 接收另一个页面传递的参数
        const state = history.state
        if (state.customerId) {
            queryUserMoneySumDetailForm.reportQueryDateType = 0
            // 客户编号
            queryUserMoneySumDetailForm.customerId = String(state.customerId)
            // 客户名称
            hanleCustomer(queryUserMoneySumDetailForm.customerId)
            history.state.customerId = undefined
        }
        if(state.periodBeginDate && state.periodEndDate) {
            queryUserMoneySumDetailForm.dateArr = [state.periodBeginDate, state.periodEndDate]
            queryUserMoneySumDetailForm.beginDate = state.periodBeginDate
            queryUserMoneySumDetailForm.endDate = state.periodEndDate
            history.state.periodBeginDate = undefined
            history.state.periodEndDate = undefined
        }
    }
    onBeforeMount(() => {
        initStartAndEndDates()
        getStateData()
        storePersonnel.addGetSalesmanUserList()
        storeDropDownData.addAccountPeriodTypeList()
    })
    onActivated(() => {
        const state = history.state
        if (state.customerId) {
            initStartAndEndDates()
            getStateData()
            searchBtn()
        }
    })
    // 获取客户名称
    const hanleCustomer = (val) => {
        const findObj = unref(customertList).find(item => item.value === val)
        queryUserMoneySumDetailForm.customerName = findObj?.label
    }
    // 分公司名称
    const changeBranchCompanyName = (val) => {
        const findObj = unref(branchCompanyCustomers).find(item => item.value === val)
        queryUserMoneySumDetailForm.orgName = findObj?.label
    }

    // 细刻模板
    const { templateLoading: XiKeLoading, hanleOpenDownload: downloadXiKeMoney } = useApiDownTemplate(api_XiKeMoneyReportdownload)
    // 英驰模板
    const { templateLoading: YingChiLoading, hanleOpenDownload: downloadYingChi } = useApiDownTemplate(api_YingChiMoneyReportdownload)
    // 方仓模板
    const { templateLoading: FangCangLoading, hanleOpenDownload: downloadFangCang } = useApiDownTemplate(api_FangCangMoneyReportdownload)
    // 分公司利润报表
    const { templateLoading: BranchProfitLoading, hanleOpenDownload: downloadBranchProfit } = useApiDownTemplate(api_DownloadCompanyProfit)
    // 简爱
    const { templateLoading: JianAiLoading, hanleOpenDownload: downloadJianAi } = useApiDownTemplate(api_jianAiMoneyReportdownload)
    // 小包账单模版
    const { templateLoading: xbAndKpReportLoading, hanleOpenDownload: downloadXbAndKpReport } = useApiDownTemplate(api_xbAndKpReportdownload)
    // 德国海外仓模板
    const { templateLoading: deOverseasReportLoading, hanleOpenDownload: downloadDeOverseasReport } = useApiDownTemplate(api_deOverseasReportdownload)

    const downLonading = computed(() => {
        return XiKeLoading.value || YingChiLoading.value || FangCangLoading.value || BranchProfitLoading.value || JianAiLoading.value || xbAndKpReportLoading.value || deOverseasReportLoading.value
    })
    // 重置表单
    const resetParams = () => {
        dealData.reportType = 0
        hanlClearOrderIdList()
        for (const key of Object.keys(queryUserMoneySumDetailForm)) {
            if (isBoolean(queryUserMoneySumDetailForm[key])) {
                queryUserMoneySumDetailForm[key] = true;
            } else if (isArray(queryUserMoneySumDetailForm[key])) {
                queryUserMoneySumDetailForm[key] = [];
            } else {
                // 否则设置为undefined
                queryUserMoneySumDetailForm[key] = undefined;
            }
        }
        queryUserMoneySumDetailForm.total = 0
        queryUserMoneySumDetailForm.reportQueryDateType = 0
        queryUserMoneySumDetailForm.consumeFlag = 1
        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 {
            await flatDate()//时间处理
            // 具体单号，交易号的查询条件
            if (await verifyForm(listParams, 'orderIdList') || 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 {
            dealData.loading = true
            usermoneyGridOptions.loading = true
            const res = await api_UserMoneyDetail(listParams)
            if (res.code == 200) {
                usermoneyGridOptions.data = res.data.records
                queryUserMoneySumDetailForm.total = res.data.total;
            }
        } catch (error) {
            report(error)
        } finally {
            dealData.loading = false
            usermoneyGridOptions.loading = false
        }
    }
    // 获取客户、单号总计金额
    const getFeeTotalAmount = computed(() => {
        if (
            usermoneyGridOptions.data &&
            listParams.customerId
        ) {
            const isEvery = usermoneyGridOptions.data.every(item => item.customerId === Number(listParams.customerId))
            return isEvery ? usermoneyGridOptions.data.reduce((acc, item) => roundToDecimals(acc + item.feeAmount, 2), 0) : 0;
        }
        if (
            usermoneyGridOptions.data &&
            listParams.orderIdList &&
            isArrayLength(listParams.orderIdList)
        ) {
            const orderId = listParams.orderIdList ? listParams.orderIdList[0] : ''
            const isEvery = usermoneyGridOptions.data.every(item => item.orderId === orderId)
            return isEvery ? usermoneyGridOptions.data.reduce((acc, item) => roundToDecimals(acc + item.feeAmount, 2), 0) : 0
        }
        return 0
    })

    // 扁平化起始结束时间
    const flatDate = async () => {
        // 初始化当月的起始时间与结束时间
        listParams.dateArr = null
        const dateArr = queryUserMoneySumDetailForm.dateArr
        if (dateArr?.length === 2) {
            const [beginDate, endDate] = dateArr
            queryUserMoneySumDetailForm.beginDate = beginDate
            queryUserMoneySumDetailForm.endDate = endDate
            listParams.beginDate = beginDate
            listParams.endDate = endDate
            const params = { ...queryUserMoneySumDetailForm, dateArr: null }
            return params
        } else {
            queryUserMoneySumDetailForm.beginDate = undefined
            queryUserMoneySumDetailForm.endDate = undefined
            listParams.beginDate = undefined
            listParams.endDate = undefined
            return queryUserMoneySumDetailForm
        }
    }
    // 初始化默认时间
    const initStartAndEndDates = () => {
        const [beginDate, endDate] = startAndEndDates
        queryUserMoneySumDetailForm.dateArr = startAndEndDates
        queryUserMoneySumDetailForm.beginDate = beginDate
        queryUserMoneySumDetailForm.endDate = endDate
        listParams.beginDate = beginDate
        listParams.endDate = endDate
    }

    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<UserMoneyDetailParam>(initList, resetParams, queryUserMoneySumDetailForm)
    const exportBillBtn = async () => {
        const params = await flatDate()
        // 导出币种默认值
        if (!params.currencyCode) params.currencyCode = "CNY"
        if (!isNumber(params.reportQueryDateType)) {
            createMessage.warning('时间类型不能为空！')
            return false
        }
        if (dealData.reportType === FeeReportTemplateType.BRANCH_STATEMENT) {
            const isVerify = await Promise.all([verifyForm(params, 'beginDate'), verifyForm(params, 'orgId')])
            const isFlag = isVerify.every(item => item)
            if (!isFlag) {
                createMessage.warning('分公司或查询时间不能为空！')
                return false
            }
            // 分公司利润报表
            downloadBranchProfit(params)
        } else {
            // verifyForm(params, 'billDate'), //账单时间 账单时间不能为空！
            const isVerify = await Promise.all([verifyForm(params, 'customerId')])
            const isFlag = isVerify.every(item => item)
            if (!isFlag) {
                createMessage.warning('客户编号不能为空！')
                return false
            }
            params.reportModelType = dealData.reportType
            if (dealData.reportType >= 0 && dealData.reportType <= 4) {
                // 细刻相同模版
                downloadXiKeMoney(params)
            } else if (dealData.reportType >= 5 && dealData.reportType <= 6) {
                // 方仓相同模版
                downloadFangCang(params)
            } else if(dealData.reportType == 9) {
                // 简爱模板
                downloadJianAi(params);
            } else if(dealData.reportType == 10) {
                // 小包账单模版
                downloadXbAndKpReport(params);
            } else if(dealData.reportType == 11) {
                // 德国海外仓模板
                downloadDeOverseasReport(params);
            } else {
                // 英驰相同模版
                downloadYingChi(params)
            }
        }
    }
    // 平账
    const hanleBalanced = async (data) => {
        const res = await api_UserBalance(data)
        resData(res, '平账成功！')
    }
    // 操作
    const handleClickChange = async (data) => {
        // debugger
        switch (data.types) {
            case BaseFeesetAction.DETAIL://明细
                unref(queryExpenseItemDetailRef)?.show(data)
                break;
            case BaseFeesetAction.BALANCED://平账
                createConfirm({
                    type: "warning",
                    title: "系统提示",
                    message: "是否进行平账?",
                    cancelButtonText: "取消",
                    confirmButtonText: "确定",
                    beforeClose: (action, instance, done) => {
                        if (action === "confirm") {
                            hanleBalanced(data)
                        }
                        done()
                    },
                })
                break;
            default:
                break;
        }
    }

    // 显示小提示框输入单号
    const multiOrdersRef = ref()
    // const orderIdListhide = () => dealData.isOrderIdList = false
    // const showOrderIdList = () => dealData.isOrderIdList = true
    // 清除单号按钮
    const hanlClearOrderIdList = () => {
        // orderIdListhide()
        dealData.inputMultiOrders = ''
        dealData.inputOrders = ''
        queryUserMoneySumDetailForm.orderIdList = []
    }
    // 确定单号按钮
    const confirmMultiOrders = () => {
        const orders = dealData.inputMultiOrders.split(/,|，| |\r|\n/)
        queryUserMoneySumDetailForm.orderIdList = orders.filter(item => item)
        dealData.inputOrders = orders.join(',')
        // orderIdListhide()
    }
    // 回车事件
    // const confirmMultiEnterOrders = () => {
    //     if (dealData.inputOrders.length > 0) {
    //         dealData.inputMultiOrders = format(dealData.inputOrders, '\n')
    //         confirmMultiOrders()
    //         orderIdListhide()
    //     }
    // }
    // popover显示结束事件
    const afterEnterOrders = () => {
        if (!unref(multiOrdersRef)) return
        multiOrdersRef.value?.focus()
    }
    // change事件
    const changeOrders = (val) => {
        if (!val) hanlClearOrderIdList()
    }
    // 单号聚焦事件
    const focusOrderId = async () => {
        afterEnterOrders()
    }

    onMounted(() => {
        storeDropDownData.addCurrencyList()
        storeDropDownData.addCustomertList()
        storeDropDownData.addOperatingTypeList()
        storeDropDownData.addCustomerTypeList()
        storeDropDownData.addFeeDataTypeList()
        storeDropDownData.addBranchCompanyCustomers()
        storeDropDownData.addProductList()
        storeDropDownData.addCountryList()
        storeDropDownData.addReportModelTypeList()
        storeDropDownData.addReportQueryDateTypeList()
        storeDropDownData.addAllPaymentPlatformList()
    })

    return {
        queryUserMoneySumDetailForm,
        dealData,
        listParams,
        actionOptions,
        queryExpenseItemDetailRef,
        downLonading,
        searchBtn,
        resetBtn,
        exportBillBtn,
        hanleCustomer,
        sizeChange,
        currentChange,
        handleClickChange,
        hanlClearOrderIdList,
        confirmMultiOrders,
        changeOrders,
        multiOrdersRef,
        focusOrderId,
        afterEnterOrders,
        changeBranchCompanyName,
        customertList,
        currencyList,
        customerTypeList,
        getOperatingTypeList,
        feeDataTypeList,
        branchCompanyCustomers,
        productList,
        countryList,
        reportModelTypeList,
        reportQueryDateTypeList,
        getSalesmanUsesList,
        accountPeriodTypeList,
        allPaymentPlatformList,
        getFeeTotalAmount,
    }
}

export {
    userMoneySumDetailList
}