import { api_moneyDetailCompareDownload, api_moneyDetailCompareReCount, api_pageMoneyCompareList } from '@/api/moneyCompare/moneyCompare';
import { MoneyDetailCompareParam } from '@/api/moneyCompare/moneyCompareModel';
import type { BasicTableProps, VxeGridInstance } from '@/components/VxeTable';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useMessage } from '@/hooks/useMessage';
import { useQueryList } from '@/hooks/useQueryList';
import { usePersonnel } from '@/store/list_personnel';
import { formatDate, getStartDayAndNextDay } from '@/utils/dateTimeStr';
import { downloadByData } from '@/utils/download';
import { isArray, isArrayLength } from '@/utils/is';
import { resCodeSuccess, useReturnData } from '@/utils/useReturnData';
import { ref, reactive, computed, unref, onBeforeMount } from 'vue';

const { resData } = useReturnData()
const { createMessage } = useMessage()
/**
 * 费用比较 列表
 * @returns 
 */
function useMoneyCompareList(moneyCompareListOptions: BasicTableProps) {
    const { 
        productList,
        storeDropDownData, 
        customertList, 
    } = useDropDownData()
    const storePersonnel = usePersonnel()
    const salesmanUsesList = computed(() => storePersonnel.getSalesmanUsesList)
    const searchFormRef = ref()
    const moneyCompareParams = reactive<MoneyDetailCompareParam>({
        customerId: undefined,
        exceptCustomerIdList: [],
        productId: undefined,
        exceptProductIdList: [],
        orderIdList: [],
        differenceFeeAmount: undefined,
        beginTime: undefined,
        endTime: undefined,
        salesmanId: undefined,
        recountByLastFee: false,
        currentDate: undefined,
        pageNum: 1,
        pageSize: 10,
        total: 0
    })
    const moneyCompareState = reactive({
        loading: false,//加载loading
        differenceFlagList: [
            { value: true, label: '是' },
            { value: false, label: '否' },
        ],//是否有差异
        dateArr: [],//起始-结束时间
        isOrderIdList: false,//显示/隐藏输入框框
        inputMultiOrders: '',//单号文本框1
        inputOrders: '',//单号文本框2
        reportType: 0,//报表类型
        exportLoading: false,//导出loading
        recalculationLoading: false,//重算loading
    })
    // 今天时间与明天时间
    const [currentFormattedDate, endFormattedDate] = getStartDayAndNextDay()
    onBeforeMount(() => {
        moneyCompareParams.currentDate = endFormattedDate
        storeDropDownData.addCustomertList()
        storeDropDownData.addProductList()
        storePersonnel.addGetSalesmanUserList()
    })
    // 初始化列表
    const initList = async () => {
        try {
            moneyCompareState.loading = true
            moneyCompareListOptions.loading = true
            listParams.currentDate = undefined
            const res = await api_pageMoneyCompareList(listParams)
            if (resCodeSuccess(res)) {
                moneyCompareListOptions.data = res.data.records
                moneyCompareParams.total = res.data.total
            }
        } finally {
            moneyCompareState.loading = false
            moneyCompareListOptions.loading = false
        }
    }
    // 导出
    const downloadBtn = async () => {
        moneyCompareState.exportLoading = true
        try {
            const res = await api_moneyDetailCompareDownload({
                customerId: moneyCompareParams.customerId,
                salesmanId: moneyCompareParams.salesmanId,
                differenceFlag: moneyCompareParams.differenceFlag,
                productId: moneyCompareParams.productId,
                orderIdList: moneyCompareParams.orderIdList,
                differenceFeeAmount: moneyCompareParams.differenceFeeAmount,
                beginTime: moneyCompareParams.beginTime,
                endTime: moneyCompareParams.endTime,
                recountByLastFee: moneyCompareParams.recountByLastFee,
                currentDate: moneyCompareParams.currentDate,
            })
            if (res) {
                // 获取接口表格响应的头
                const header = res.headers['content-disposition'].split("''")
                // 转中文
                const fileName = decodeURIComponent(header[1])
                // 通过blod导出模板
                downloadByData(res.data, fileName)
                moneyCompareState.exportLoading = false
            }
        } catch (error) {
            moneyCompareState.exportLoading = false
        }
    }
    const moneyCompareTableRef = ref<VxeGridInstance>()
    // 重算
    const recalculationBtn = async () => {
        const $table = unref(moneyCompareTableRef)
        if(!$table) return
        const checkData = $table.getCheckboxRecords()
        const orderIdList = checkData.map(item => item.orderId)
        // 优选取勾选复选框订单
        const getOrderIdList = orderIdList.length > 0 ? orderIdList : moneyCompareParams.orderIdList
        const isFlag = getOrderIdList && getOrderIdList.length > 0 ? false : (!moneyCompareParams.beginTime && !moneyCompareParams.endTime)
        if (isFlag) {
            createMessage.warning('请选起始时间与结束时间！')
            return
        }
        try {
            moneyCompareState.recalculationLoading = true
            const res = await api_moneyDetailCompareReCount({ 
                customerId: moneyCompareParams.customerId,  
                salesmanId: moneyCompareParams.salesmanId,
                productId: moneyCompareParams.productId,
                orderIdList: getOrderIdList,
                beginTime: moneyCompareParams.beginTime,
                endTime: moneyCompareParams.endTime,
                recountByLastFee: moneyCompareParams.recountByLastFee,
                currentDate: moneyCompareParams.currentDate,
            })
            const resCode = resData(res, '操作成功')
            if (resCode == 500) return
            searchBtn()
        } finally {
            moneyCompareState.recalculationLoading = false
        }
    }
    const { resetForm } = useEleFormValidate()
    // 重置
    const resetParams = () => {
        hanlClearOrderIdList()
        resetForm(searchFormRef.value)
        moneyCompareParams.orderIdList = []
        moneyCompareState.dateArr = []
        moneyCompareParams.currentDate = endFormattedDate
    }
    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<MoneyDetailCompareParam>(initList, resetParams, moneyCompareParams)
    
    // 起始-结束时间
    const changeDate = (dates: Date[]) => {
        if(isArray(dates)) {
            moneyCompareParams.beginTime = formatDate(dates[0])
            moneyCompareParams.endTime = formatDate(dates[1])
        } else {
            moneyCompareParams.beginTime = undefined
            moneyCompareParams.endTime = undefined
        }
    }
    // 费用明细
    const queryExpenseItemDetailRef = ref<{ show: Fn }>()
    const hanleViewDetail = (row) => {
        unref(queryExpenseItemDetailRef)?.show({ ...row, recountByLastFee: moneyCompareParams.recountByLastFee })
    }

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

    return {
        searchFormRef,
        moneyCompareParams,
        moneyCompareState,
        moneyCompareTableRef,
        sizeChange, 
        currentChange, 
        searchBtn, 
        resetBtn,
        downloadBtn,
        recalculationBtn,
        productList,
        customertList, 
        salesmanUsesList,
        changeDate,
        queryExpenseItemDetailRef,
        hanleViewDetail,
        multiOrdersRef,
        hanlClearOrderIdList,
        confirmMultiOrders,
        changeOrders,
        focusOrderId,
        afterEnterOrders,
    }
}

export {
    useMoneyCompareList
}