import { api_addLadingBillMain, api_deleteLadingBillMain, api_editLadingBillFeeSet, api_editLadingBillMain, api_getLadingBillFeeQuery, api_ladingBillMainList, api_ladingBillMoneyCustomerBill, api_ladingBillMoneySave, api_ladingBillUpdateState } from '@/api/lading/lading';
import { CustomerBillDto, LadingBillFeeQueryResultDto, LadingBillFeeSetDto, LadingBillMainDto, LadingBillMainParam, LadingBillMoneyDto, LadingBillUpdateState } from '@/api/lading/ladingModle';
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 useResizeHeight from '@/hooks/useResizeHeight';
import { useFeesetList } from '@/store/list_feeset';
import { usePersonnel } from '@/store/list_personnel';
import { useStateType } from '@/store/list_StateType';
import { BaseLadingActions, BaseLadingSearchActions } from '@/type/BaseLading';
import { cloneDeep } from '@/utils/cloneDeep';
import { formatDateTime, strFormatDateTime } from '@/utils/dateFormate';
import { isArrayLength } from '@/utils/is';
import { resCodeSuccess, useReturnData } from '@/utils/useReturnData';
import { ref, reactive, computed, watchEffect, unref, onMounted } from 'vue';

const { resData } = useReturnData()
const { createConfirm, createMessage } = useMessage()
/**
 * 提单列表数据处理
 */
function useLadingList(ladingListOptions: BasicTableProps) {
    // 表格自适应屏幕高度 
    const { tableHeight } = useResizeHeight()
    // 计算表格的容器的高度
    watchEffect(() => {
        unref(tableHeight) > 520 && (ladingListOptions.height = unref(tableHeight))
    })
    // 提单列表ref
    const ladingBillListRef = ref()
    // table ref
    const ladingListTableRef = ref<VxeGridInstance>()
    // 提单类型ref
    const ladingBillSetRef = ref<{ show: Fn }>()
    // 提单费用设置ref
    const ladingBillMoneySetRef = ref<{ show: Fn }>()
    // 提单费用试算结果ref
    const lillMoneyCountResultRef = ref<{ show: Fn }>()
    // 提单费用列表
    const ladingBillMoneyListRef = ref<{ show: Fn }>()
    // 批量更新状态
    const ladingBillStateUpdateRef = ref<{ show: Fn }>()
    // 提单账单预览
    const ladingPreviewBillRef = ref<{ show: Fn }>()
    const ladingBillImportRef = ref<{ show: Fn }>()
    const ladingBillListParams = reactive<LadingBillMainParam>({
        pageNum: 1,
        pageSize: 10,
        total: 10
    })
    const loadingBillState = reactive({
        searchType: 0,
        dateArr: [],//起始与结束时间
        loading: false,
        ladingCostTrialList: [] as LadingBillFeeQueryResultDto[],
        customerBillData: {} as CustomerBillDto
    })
    // 下拉列表数据
    const { storeDropDownData, customertList, allProvidersList, companyEntityTypeList, airCompanyList } = useDropDownData()
    const storeFeesetList = useFeesetList()
    const storePersonnel = usePersonnel()
    const storeStateType = useStateType()
    const salesmanUsesList = computed(() => storePersonnel.getSalesmanUsesList)
    onMounted(() => {
        storeFeesetList.addFeeItemCategoryList()
        storeDropDownData.addCountryList()
        storeDropDownData.addFeeSetTypeList()
        storeDropDownData.addCustomertList()
        storePersonnel.addGetSalesmanUserList()
        storeDropDownData.addAllProvidersList()
        storeDropDownData.addAirCompanyListApi()
        storeDropDownData.addAirBusinessTypeListApi()
        storeStateType.addBookingStateList()
        storeStateType.addOperateStateList()
        storeStateType.addReceivableStateList()
        storeStateType.addPayStateList()
        storeDropDownData.addCompanyEntityTypeListApi()
        storeDropDownData.addDeliverChannelListApi()
        storeDropDownData.addBranchCompanyCustomers()
        storeStateType.addLadingBillDateTypeList()
        storeStateType.addLadingBillStateTypeList()
    })
    // 校验表单
    const { resetForm } = useEleFormValidate();
    // 初始化列表、分页数据
    const initList = async () => {
        loadingBillState.loading = true
        // 起始时间、结束时间参数
        const dateArr = loadingBillState.dateArr
        if (isArrayLength(dateArr)) {
            listParams.beginDate = formatDateTime(dateArr[0])
            listParams.endDate = formatDateTime(dateArr[1])
        }
        const res = await api_ladingBillMainList(listParams)
        if (res && res.code == 200) {
            ladingListOptions.data = res.data.records
            ladingBillListParams.total = res.data.total;
        }
        loadingBillState.loading = false
    }
    const resetParams = () => {
        listParams.beginDate = undefined
        listParams.endDate = undefined
        resetForm(unref(ladingBillListRef))
        loadingBillState.dateArr = []
    }
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<LadingBillMainParam>(initList, resetParams, ladingBillListParams)
    // 账单预览
    const initBillView = async (mainId: number) => {
        const res = await api_ladingBillMoneyCustomerBill({ mainId })
        if (resCodeSuccess(res)) {
            loadingBillState.customerBillData = res.data
            unref(ladingPreviewBillRef)?.show()
        }
    }
    // 删除提单
    const deleteBill = async (id: number) => {
        const deleteRes = await api_deleteLadingBillMain({ id })
        const deleteCode = resData(deleteRes, '操作成功')
        if (deleteCode !== 500) initList()
    }
    const showladingBillSet = (id?: number) => unref(ladingBillSetRef)?.show(id)
    const handleClickChange = (row) => {
        const data = cloneDeep(row)
        switch (data.types) {
            // 编辑提单
            case BaseLadingActions.BILL_EDIT:
                showladingBillSet(data.id)
                break;
            // 费用编辑
            case BaseLadingActions.EXPENSE_EDITOR:
                unref(ladingBillMoneySetRef)?.show({ ...data, ladingBillMainId: data.id })
                break;
            // 费用试算
            case BaseLadingActions.COST_TRIAL_CALCULATION:
                costTrialCalculation({ ...data, ladingBillMainId: data.id })
                break;
            // 费用明细
            case BaseLadingActions.FEESET_DETAILS:
                unref(ladingBillMoneyListRef)?.show({ id: data.id })
                break;
            // 账单预览
            case BaseLadingActions.BILL_PREVIEW:
                initBillView(data.id)
                break;
            // 删除提单
            case BaseLadingActions.DELETE_BILL_LADING:
                createConfirm({
                    type: "warning",
                    title: "系统提示",
                    message: "确定删除该数据吗?",
                    cancelButtonText: "取消",
                    confirmButtonText: "确定",
                    beforeClose: (action, instance, done) => {
                        // console.log(action,"==> cancel , confirm ", instance, ";action, instance");
                        if (action === "confirm") {
                            // 删除
                            deleteBill(data.id)
                        }
                        done()
                    },
                })
                break;
            default:
                break;
        }
    }
    // 新增
    const hanleAdd = () => showladingBillSet()
    // 账单下载
    const hanleDownload = () => {

    }
    // 导入
    const hanleImport = () => {
        unref(ladingBillImportRef)?.show()
    }
    // 提单费用试算
    const costTrialCalculation = async (params: LadingBillFeeSetDto) => {
        const res = await api_getLadingBillFeeQuery({ ladingBillMainId: params.ladingBillMainId })
        if (!resCodeSuccess(res)) return
        loadingBillState.ladingCostTrialList = res.data
        unref(lillMoneyCountResultRef)?.show(params)
    }
    // 批量-按钮组
    const hanleChangeSearch = (row: Recordable) => {
        switch (row.types) {
            // 批量导入
            case BaseLadingSearchActions.IMPORT:

                break;
            // 批量状态更新
            case BaseLadingSearchActions.STATUS_UPDATE:
                const ladingListTable = unref(ladingListTableRef)
                if (!ladingListTable) return
                const checkboxData = ladingListTable.getCheckboxRecords()
                const ids = checkboxData.map(item => item.id)
                if (!isArrayLength(ids)) {
                    createMessage.warning("请选择批量操作的数据！")
                    return
                }
                unref(ladingBillStateUpdateRef)?.show(ids)
                break;
            default:
                break;
        }
    }
    // 新增或编辑提单
    const hanleSaveConfirm = async (params: LadingBillMainDto, onclose: Fn) => {
        params.bookingTime = strFormatDateTime(params.bookingTime)
        params.takeOffTime = strFormatDateTime(params.takeOffTime)
        if (params.id) {
            // 编辑
            const res = await api_editLadingBillMain(params)
            const resCode = resData(res, "编辑成功")
            if (resCode !== 500) {
                initList()
                onclose()
            }
        } else {
            // 添加
            const res = await api_addLadingBillMain(params)
            const resCode = resData(res, "添加成功")
            if (resCode !== 500) {
                initList()
                onclose()
            }
        }
    }

    // 编辑提单费用设置
    const hanleSaveBillSet = async (params: LadingBillFeeSetDto) => {
        if (params.ladingBillMainId) {
            // 编辑
            const res = await api_editLadingBillFeeSet(params)
            const resCode = resData(res, "编辑成功")
            if (resCode !== 500) initList()
        }
    }
    // 提单费用试算
    const hanleSaveFeeCalculate = async (params: LadingBillFeeSetDto) => {
        costTrialCalculation(params)
    }
    // 保存提单费用
    const hanleSaveBaseFee = async (params: LadingBillMoneyDto[], onclose: Fn) => {
        const res = await api_ladingBillMoneySave(params)
        const resCode = resData(res, "保存成功")
        if (resCode !== 500) {
            onclose()
            // initList()
        }
    }
    // 批量状态更新
    const hanleSaveUpdate = async (params: LadingBillUpdateState, onclose: Fn) => {
        const res = await api_ladingBillUpdateState(params)
        const resCode = resData(res, "批量修改成功")
        if (resCode !== 500) {
            onclose()
            initList()
        }
    }

    return {
        ladingListTableRef,
        ladingBillListRef,
        ladingBillSetRef,
        ladingBillImportRef,
        ladingBillMoneySetRef,
        ladingBillStateUpdateRef,
        lillMoneyCountResultRef,
        ladingBillMoneyListRef,
        ladingPreviewBillRef,
        ladingBillListParams,
        loadingBillState,
        handleClickChange,
        hanleChangeSearch,
        searchBtn,
        resetBtn,
        sizeChange,
        currentChange,
        hanleAdd,
        hanleDownload,
        hanleImport,
        hanleSaveConfirm,
        hanleSaveBillSet,
        hanleSaveFeeCalculate,
        hanleSaveBaseFee,
        hanleSaveUpdate,
        customertList,
        allProvidersList,
        salesmanUsesList,
        storeStateType,
        companyEntityTypeList,
        airCompanyList
    }
}

export {
    useLadingList
}