import type { BasicTableProps } from '@/components/VxeTable';
import { BranchProfitDetailParam } from '@/api/report/branchModle';
import { useQueryList } from '@/hooks/useQueryList';
import { addDays, formatDate, getCurrentDateAndPretDate, getFormatDate } from '@/utils/dateTimeStr';
import { ref, reactive, unref, computed, onBeforeMount } from 'vue';
import { resCodeSuccess } from '@/utils/useReturnData';
import { api_branchProfitDetailReportList, api_branchProfitdownload } from '@/api/report/branch';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useApiDownTemplate } from '@/hooks/useApiDownTemplate';
import { useDropDownData } from '@/hooks/useDropDownData';
import { usePersonnel } from '@/store/list_personnel';
import { ListIitem } from '@/api/base/BaseDataModel';
import { nextTick } from 'process';

/**
 * 分公司利润表
 * @returns 
 */
function useBranchIncomeStatement(branchIncomeStatementOptions: BasicTableProps) {
    const searchFormRef = ref()
    const branchIncomeStatementParams = reactive<BranchProfitDetailParam>({
        orderId: undefined,
        beginDate: undefined,
        endDate: undefined,
        productId: undefined,
        customerId: undefined,
        customerIdList: [],
        orgId: undefined,
        salesmanId: undefined,
        orderIdList: [],
        dataType: 0,
        reportQueryDateType: 0,
        profitStatus: undefined,
        pageNum: 1,
        pageSize: 20,
        total: 20,
    })
    const branchIncomeStatementState = reactive({
        timerArray: [] as Recordable,
        loading: false,
        dataTypeList: [
            { value: 0, label: '正常数据' },
            { value: 1, label: '异常数据' },
        ] as ListIitem[],
        isOrderIdList: false,//显示/隐藏输入框框
        inputMultiOrders: '',//单号文本框1
        inputOrders: '',//单号文本框2
    })
    const { 
        storeDropDownData, 
        customertList, 
        productList,
        branchCompanyCustomers,
        profitStatusList,
        reportQueryDateTypeList
    } = useDropDownData()
    const storePersonnel = usePersonnel()
    // 业务员
    const getSalesmanUsesList = computed(() => storePersonnel.getSalesmanUsesList)
    onBeforeMount(() => {
        storeDropDownData.addCustomertList()
        storeDropDownData.addProductList()
        storeDropDownData.addBranchCompanyCustomers()
        storePersonnel.addGetSalesmanUserList()
        storeDropDownData.addProfitStatusList()
        storeDropDownData.addReportQueryDateTypeList()
        changeTimerArray([
            startDate,
            endDate
        ])
    })

    const endDate = addDays(new Date(), -1)
    const startDate = addDays(endDate, -30)
    // 清空时间
    const clearDate = () => {
        branchIncomeStatementParams.beginDate = undefined
        branchIncomeStatementParams.endDate = undefined
        branchIncomeStatementState.timerArray = []
    }
    const changeTimerArray = (date?: Date[]) => {
        if (date && date.length > 0) {
            branchIncomeStatementParams.beginDate = formatDate(date[0])
            branchIncomeStatementParams.endDate = formatDate(date[1])
            branchIncomeStatementState.timerArray = [formatDate(date[0]), formatDate(date[1])]
        } else {
            clearDate()
        }
    }
    // 重置
    const { resetForm } = useEleFormValidate()
    const resetParams = () => {
        resetForm(searchFormRef.value)
        branchIncomeStatementParams.dataType = 0
        branchIncomeStatementParams.reportQueryDateType = 0
        branchIncomeStatementParams.orderIdList = []
        changeTimerArray([
            startDate,
            endDate
        ])
    }

    // 初始化
    const initList = async () => {
        try {
            branchIncomeStatementState.loading = true
            branchIncomeStatementOptions.loading = true
            const res = await api_branchProfitDetailReportList(listParams)
            if (resCodeSuccess(res)) {
                branchIncomeStatementOptions.data = res.data.records
                branchIncomeStatementParams.total = res.data.total
            }
        } finally {
            branchIncomeStatementState.loading = false
            branchIncomeStatementOptions.loading = false
        }
    }
    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<BranchProfitDetailParam>(initList, resetParams, branchIncomeStatementParams)

    // 分公司利润表导出
    const { templateLoading: branchIncomeStatementLoading, hanleOpenDownload: branchIncomeStatementDownload } = useApiDownTemplate(api_branchProfitdownload)
    const reportDownloadBtn = () => {
        branchIncomeStatementDownload(branchIncomeStatementParams)
    }

    // 显示小提示框输入单号
    const multiOrdersRef = ref()
    // 清除单号按钮
    const hanlClearOrderIdList = () => {
        branchIncomeStatementState.inputMultiOrders = ''
        branchIncomeStatementState.inputOrders = ''
        branchIncomeStatementParams.orderIdList = []
    }
    // 确定单号按钮
    const confirmMultiOrders = () => {
        const orders = branchIncomeStatementState.inputMultiOrders.split(/,|，| |\r|\n/)
        branchIncomeStatementParams.orderIdList = orders.filter(item => item)
        branchIncomeStatementState.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,
        branchIncomeStatementParams,
        branchIncomeStatementState,
        branchIncomeStatementLoading,
        changeTimerArray,
        sizeChange, 
        currentChange, 
        searchBtn, 
        resetBtn,
        reportDownloadBtn,
        customertList,
        productList,
        branchCompanyCustomers,
        profitStatusList,
        reportQueryDateTypeList,
        getSalesmanUsesList,
        multiOrdersRef,
        hanlClearOrderIdList,
        confirmMultiOrders,
        changeOrders,
        focusOrderId,
        afterEnterOrders,
    }
}

/**
 * 客户账单表格配置
 * @returns 
 */
function useBranchIncomeStatementModel() {
    // 基础数据
    const branchIncomeStatementGridOptions = reactive<BasicTableProps>({
        id: 'branch_income_statement_table',
        border: true,
        keepSource: true,
        showOverflow: true,
        height: 520,
        loading: false,
        rowConfig: { isHover: true },
        rowClassName: ({ row }) => {
            if (row.profit < 0) {
                return 'class-profit'
            }
        },
        columnConfig: {
            resizable: true
        },
        columns: [
            { field: 'orderPieces', title: '票数', width: 70, headerClassName: 'orderInformation' },
            { field: 'orderId', title: '单号', minWidth: 160, headerClassName: 'orderInformation' },
            { field: 'trackingNumber', title: '跟踪号', minWidth: 170, headerClassName: 'orderInformation' },
            { field: 'receiveTime', title: '收货时间', minWidth: 150, headerClassName: 'orderInformation' },
            { field: 'createTime', title: '生成时间', minWidth: 150, headerClassName: 'orderInformation' },
            { field: 'productName', title: '渠道名称', minWidth: 110, headerClassName: 'orderInformation' },
            { field: 'countryName', title: '目的国家', minWidth: 100, headerClassName: 'orderInformation' },
            { field: 'deliveryChannel', title: '派送渠道名称', minWidth: 120, headerClassName: 'orderInformation' },
            { field: 'customerName', title: '客户简称', minWidth: 120, headerClassName: 'orderInformation' },
            { field: 'orgName', title: '分公司名称', minWidth: 95, headerClassName: 'orderInformation' },
            { field: 'salesmanName', title: '业务员', minWidth: 80, headerClassName: 'orderInformation' },
            { field: 'customerRevenue', title: '总计收入', minWidth: 90, headerClassName: 'customerIncome' },
            { field: 'customerCountFeeWeight', title: '计费重量', minWidth: 90, headerClassName: 'customerIncome' },
            { field: 'customerFreightFee', title: '运费', minWidth: 90, headerClassName: 'customerIncome' },
            { field: 'customerSurcharge', title: '附加费', minWidth: 90, headerClassName: 'customerIncome' },
            { field: 'customerTaxFee', title: '税费', minWidth: 90, headerClassName: 'customerIncome' },
            { field: 'customerSundryFees', title: '杂费', minWidth: 90, headerClassName: 'customerIncome' },
            { field: 'customerRemoteFees', title: '偏远费', minWidth: 90, headerClassName: 'customerIncome' },
            { field: 'customerFeeVersion', title: '计费版本', minWidth: 200, headerClassName: 'customerIncome' },
            { field: 'orgFeeAmount', title: '总计结算价成本', minWidth: 130, headerClassName: 'branchSettlement' },
            { field: 'orgCountFeeWeight', title: '计费重量', minWidth: 90, headerClassName: 'branchSettlement' },
            { field: 'orgFreightFee', title: '运费', minWidth: 90, headerClassName: 'branchSettlement' },
            { field: 'orgSurcharge', title: '附加费', minWidth: 90, headerClassName: 'branchSettlement' },
            { field: 'orgTaxFee', title: '税费', minWidth: 90, headerClassName: 'branchSettlement' },
            { field: 'orgSundryFees', title: '杂费', minWidth: 90, headerClassName: 'branchSettlement' },
            { field: 'orgRemoteFees', title: '偏远费', minWidth: 90, headerClassName: 'branchSettlement' },
            { field: 'orgFeeVersion', title: '计费版本', minWidth: 200, headerClassName: 'branchSettlement' },
            { field: 'salesAmount', title: '销售承担费用', minWidth: 110, headerClassName: 'branchProfit' },
            { field: 'profit', title: '分公司利润', minWidth: 95, headerClassName: 'branchProfit' },
            // { 
            //     field: 'orderInformation', 
            //     align: 'center',
            //     title: '订单基础信息', 
            //     headerClassName: 'orderInformation',
            //     children: []
            // },
            // { 
            //     field: 'customerIncome', 
            //     title: '客户收入', 
            //     align: 'center',
            //     headerClassName: 'customerIncome',
            //     children: []
            // },
            // { 
            //     field: 'branchSettlement', 
            //     title: '分公司结算', 
            //     align: 'center',
            //     headerClassName: 'branchSettlement',
            //     children: []
            // },
            // { 
            //     field: 'branchProfit', 
            //     title: '分公司利润', 
            //     align: 'center',
            //     headerClassName: 'branchProfit',
            //     children: []
            // }
        ],
        data: []
    })

    return {
        branchIncomeStatementGridOptions
    }
}

export {
    useBranchIncomeStatement,
    useBranchIncomeStatementModel
}