import { ListIitem } from '@/api/base/BaseDataModel';
import { api_queryCustomerNetPrintFee, api_refundMoney, api_sumMoneytDownload, api_UserMoneySumList } from '@/api/usermoneysum/apiUserMoneySum';
import { ReturnMoneyParam, UserMoneySumParam } from '@/api/usermoneysum/apiUserMoneySumModel';
import { ActionOptions } from '@/components/DropDownButtons/type';
import type { BasicTableProps } from '@/components/VxeTable';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useQueryList } from '@/hooks/useQueryList';
import { isArrayLength } from '@/utils/is';
import { resCodeSuccess, useReturnData } from '@/utils/useReturnData';
import { ref, reactive, unref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Tickets, DocumentChecked, Money } from "@element-plus/icons-vue";
import { MoneySumAction } from '@/type/BaseEnum';
import { useApiDownTemplate } from '@/hooks/useApiDownTemplate';

const { resData } = useReturnData(true)
/**
 * 客户总账
 */
function userMoneySumList(moneySumListOptions: BasicTableProps) {
    const { push } = useRouter()
    const {
        storeDropDownData,
        customertList,
        currencyList,
        customerTypeList,
        operatingTypeList,
        feeDataTypeList,
        branchCompanyCustomers,
        allPaymentPlatformList
    } = useDropDownData()
    //定义列表查询的参数
    const listParm = reactive<UserMoneySumParam>({
        customerId: undefined,//客户
        currencyCode: '',//币种
        isInterceptCustomers: undefined,
        status: undefined,
        pageNum: 1,
        pageSize: 10,
        total: 0
    })
    // 列表数据
    const stateUserMoneySumList = reactive({
        customertList: [] as ListIitem[],//客户列表
        currencyList: [] as ListIitem[],//币种
        isInterceptCustomersList: [
            { value: true, label: '是' },
            { value: false, label: '否' },
        ],
        statusList: [
            { value: 0, label: '未还清' },
            { value: 1, label: '已还清' },
        ] as ListIitem[],
        loading: false,//加载
    })
    // 明细弹窗Ref
    // const userMoneySumDetailRef = ref<{ show: Fn }>()
    // 充值ref
    const rechargeAddRef = ref<{ show: Fn }>()
    const refundRef = ref<{ show: Fn }>()

    //获取客户总账查询列表
    const getUserMoneySumList = async () => {
        try {
            stateUserMoneySumList.loading = true
            moneySumListOptions.loading = true
            const res = await api_UserMoneySumList(listParams)
            if (resCodeSuccess(res)) {
                const list = res.data.records
                moneySumListOptions.data = list
                listParm.total = res.data.total;
                const customerIdList = list.map(item => item.customerId)
                getQueryCustomerNetPrintFee(customerIdList)
            }
        } finally {
            stateUserMoneySumList.loading = false
            moneySumListOptions.loading = false
        }
    }
    // 获取已打单末交货金额
    const getQueryCustomerNetPrintFee = async (customerIdList: number[]) => {
        if (customerIdList.length === 0) return
        const res = await api_queryCustomerNetPrintFee({ customerIdList })
        const customerNetPrintFeeList = resData(res)
        if (moneySumListOptions.data && moneySumListOptions.data.length > 0) {
            moneySumListOptions.data.map((data) => {
                data.expectedArrears = 0
                data.netPrintFee = 0
                const findNetPrintFee = customerNetPrintFeeList.find((item) => item.customerId === data.customerId)
                if (findNetPrintFee) {
                    const total = data.leftTotal - findNetPrintFee.netPrintFee
                    const expectedArrears = total < 0 ? total.toFixed(3) : 0
                    data.netPrintFee = findNetPrintFee.netPrintFee
                    data.expectedArrears = expectedArrears
                }
            })
        }
    }
    // 重置
    const resetParams = () => {
        listParm.customerId = undefined;
        listParm.currencyCode = '';
        listParm.isInterceptCustomers = undefined
        listParm.status = undefined
    }
    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<UserMoneySumParam>(getUserMoneySumList, resetParams, listParm)

    // 打开明细
    const handleGoDetail = (row: Recordable, name = 'userMoneyDetail') => {
        push({
            name,
            state: {
                customerId: row.customerId,
                periodBeginDate: row.periodBeginDate,
                periodEndDate: row.periodEndDate,
            },
            params: {
                customerId: row.customerId,
            }
        })
    }
    // 打开充值
    const hanleRecharge = () => unref(rechargeAddRef)?.show()
    
    const initList = () => {
        Promise.allSettled([storeDropDownData.addCustomertList(), storeDropDownData.addCurrencyList()]).then(() => {
            stateUserMoneySumList.customertList = customertList.value
            stateUserMoneySumList.currencyList = currencyList.value
        })
        storeDropDownData.addOperatingTypeList()
        storeDropDownData.addCustomerTypeList()
        storeDropDownData.addFeeDataTypeList()
        storeDropDownData.addBranchCompanyCustomers()
        storeDropDownData.addAllPaymentPlatformList()
    }
    // 充值完成
    const hanleUpdateRecharge = () => {
        getUserMoneySumList()
    }
    // 退款
    const onRefund = async (params: ReturnMoneyParam, setLoading: Fn, onclose: Fn) => {
        try {
            const res = await api_refundMoney(params)
            resData(res, '操作成功！')
            onclose()
        } finally {
            setLoading(false)
        }
    }
    // 操作
    const handleClickChange = async (data) => {
        switch (data.types) {
            case MoneySumAction.CONSUMPTION:
                handleGoDetail(data)
                break;
            case MoneySumAction.RECHARGE://平账
                handleGoDetail(data, 'customerMoneyRecharge')
                break;
            case MoneySumAction.REFUND:
                unref(refundRef)?.show(data)
                break;
            default:
                break;
        }
    }
    // 导出
    const { templateLoading: downloadUserMoneyLoading, hanleOpenDownload: downloadUserMoneyReport } = useApiDownTemplate(api_sumMoneytDownload)
    const onDownloadUserMoney = () => {
        downloadUserMoneyReport(listParm)
    }

    onMounted(initList)

    return {
        listParm,
        stateUserMoneySumList,
        rechargeAddRef,
        refundRef,
        hanleUpdateRecharge,
        sizeChange,
        currentChange,
        searchBtn,
        resetBtn,
        handleGoDetail,
        hanleRecharge,
        onDownloadUserMoney,
        handleClickChange,
        customertList,
        currencyList,
        customerTypeList,
        operatingTypeList,
        feeDataTypeList,
        branchCompanyCustomers,
        allPaymentPlatformList,
        downloadUserMoneyLoading,
        onRefund
    }
}

/**
 * 客户总账表格配置
 */
function userMoneySumListModel() {
    const moneySumListOptions = reactive<BasicTableProps>({
        id: 'moneysumList_table',
        border: true,
        keepSource: true,
        showOverflow: true,
        height: 520,
        loading: false,
        stripe: true,
        rowConfig: { isHover: true, keyField: 'id' },
        columnConfig: { resizable: true },
        columns: [
            { type: "seq", title: '序号', width: 60 },
            { field: 'customerName', title: '客户', minWidth: 200 },
            { field: 'salesmanUserName', title: '业务员', width: 90 },
            { field: 'isInterceptCustomers', title: '是否拦截', minWidth: 90, slots: { default: 'isInterceptCustomers' } },
            { field: 'currencyCode', title: '币种', minWidth: 110 },
            { field: 'rechargeTotal', title: '充值总额', minWidth: 110 },
            {
                field: 'consumptionTotal',
                title: '消费总额',
                minWidth: 110,
                formatter: ({ row }) => {
                    return !row.consumptionTotal ? 0 : row.consumptionTotal
                }
            },
            { field: 'leftTotal', title: '剩余总额', minWidth: 120 },
            { field: 'netPrintFee', title: '已打单末交货', minWidth: 120 },
            { field: 'expectedArrears', title: '预计欠费', minWidth: 110 },
            { field: 'lastUpdateTime', title: '最新更新时间', minWidth: 150 },
            { field: 'createTime', title: '创建时间', minWidth: 150 },
            { field: 'createUserName', title: '创建人', minWidth: 90 },
            { title: '操作', width: 135, fixed: 'right', slots: { default: 'actions' } },
        ],
        data: []
    }) 

    // 操作类别
    const actionOptions: ActionOptions[] = [
        {
            value: MoneySumAction.CONSUMPTION,//状态
            label: "消费明细",//文本
            type: "primary",//按钮样式
            icon: Tickets,//按钮图标
            permissions: []
        },
        {
            value: MoneySumAction.RECHARGE,
            label: "充值明细",
            type: "success",
            icon: DocumentChecked,
            permissions: []
        },
        {
            value: MoneySumAction.REFUND,
            label: "退款",
            type: "warning",
            icon: Money,
            permissions: ["sys:userMoneyDetail:refundMoney"]
        },
    ]

    return {
        moneySumListOptions,
        actionOptions
    }
}

export {
    userMoneySumList,
    userMoneySumListModel
}