import { api_deleteFinancialBillDetail, api_financialBillDetailList, api_financialBillDetailSave } from '@/api/financial/financialBillDetailList/financialBillDetailList';
import { FinancialBillDetailDto, FinancialBillDetailParam } from '@/api/financial/financialBillDetailList/financialBillDetailListModle';
import type { BasicTableProps } from '@/components/VxeTable';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useMessage } from '@/hooks/useMessage';
import { useQueryList } from '@/hooks/useQueryList';
import { useFeesetList } from '@/store/list_feeset';
import { useStateFinancialType } from '@/store/list_financial';
import { BaseFinancialBillDetailListActions } from '@/type/BaseFinancial';
import { FeeSetTypeListType } from '@/type/BaseLading';
import { cloneDeep } from '@/utils/cloneDeep';
import { formatDateTime } from '@/utils/dateFormate';
import { resCodeSuccess, useReturnData } from '@/utils/useReturnData';
import { ref, reactive, unref, onBeforeMount, onMounted, onActivated } from 'vue';

const { resData } = useReturnData()
const { createConfirm } = useMessage()
/**
 * 财务应付明细
 * @returns 
 */
function useFinancialBillDetailList(financialBillDetailList: BasicTableProps) {
    // 表单 ref
    const financialBillDetailListRef = ref()
    // 表格 ref
    const financialBillDetailListTableRef = ref()
    // 预设参考
    const ladingBillMoneyListRef = ref<{ show: Fn }>()
    // 新增或编辑应付明细
    const financialBillDetailSetRef = ref<{ show: Fn }>()
    const financialBillDetailListState = reactive({
        loading: false,
        disabledArr: [] as number[],//按钮组禁止
    })
    // 参数
    const financialBillDetailListParams = reactive<FinancialBillDetailParam>({
        summaryId: undefined,
        pageNum: 1,
        pageSize: 10,
        total: 10
    })
    const storeFeesetList = useFeesetList()
    const storeFinancialType = useStateFinancialType()
    const { storeDropDownData, allProvidersList, companyEntityTypeList } = useDropDownData()
    onMounted(() => {
        storeFinancialType.addBillCodeTypeList()
        storeFinancialType.addAccountTypeList()
        storeFeesetList.addFeeItemCategoryList()
        storeDropDownData.addCompanyEntityTypeListApi()
        storeDropDownData.addAllProvidersList()
        storeDropDownData.addAirCompanyListApi()
        storeDropDownData.addPortInfoList()
        storeDropDownData.addFeeItemList()
        storeDropDownData.addCurrencyList()
        storeDropDownData.addShareTypeList()
        storeDropDownData.addCountryList()
        storeDropDownData.addCalculateUnitList()
    })

    // 初始化数据
    const initList = async () => {
        try {
            financialBillDetailListState.loading = true
            if (listParams.billTime) listParams.billTime = formatDateTime(listParams.billTime)
            const res = await api_financialBillDetailList(listParams)
            if (resCodeSuccess(res)) {
                financialBillDetailList.data = res.data.records
                financialBillDetailListParams.total = res.data.total
            }
        } catch (error) {

        } finally {
            financialBillDetailListState.loading = false
        }
    }
    // 校验表单
    const { resetForm } = useEleFormValidate();
    const resetParams = () => {
        financialBillDetailListParams.summaryId = undefined
        resetForm(unref(financialBillDetailListRef))
    }
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<FinancialBillDetailParam>(initList, resetParams, financialBillDetailListParams)
    // 删除
    const deleteBill = async (id: number) => {
        const deleteRes = await api_deleteFinancialBillDetail({ id })
        const deleteCode = resData(deleteRes)
        if (deleteCode !== 500) initList()
    }
    // 明细编辑是否禁止
    const changeVisibleChange = (val, row) => {
        if (!val) return
        const editBillDetail = row.billDetailState !== 0 ? BaseFinancialBillDetailListActions.EDIT : -1
        const deleteBillDetail = row.billDetailState !== 0 ? BaseFinancialBillDetailListActions.DELETE : -1
        financialBillDetailListState.disabledArr = [editBillDetail, deleteBillDetail]
    }

    // 操作
    const handleClickChange = (row) => {
        const data = cloneDeep(row)
        switch (data.types) {
            case BaseFinancialBillDetailListActions.PREINSTALL:
                unref(ladingBillMoneyListRef)?.show({ waybillNumber: data.waybillNumber, feeSetType: FeeSetTypeListType.PAYABLE })
                break;
            case BaseFinancialBillDetailListActions.EDIT:
                unref(financialBillDetailSetRef)?.show(data)
                break;
            case BaseFinancialBillDetailListActions.DELETE:
                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 hanleSaveConfirm = async (params: FinancialBillDetailDto, onclose: Fn) => {
        const res = await api_financialBillDetailSave(params)
        const resCode = resData(res, "保存成功")
        if (resCode !== 500) {
            onclose()
            initList()
        }
    }
    // 获取传递的参数
    const getHistoryState = () => {
        // 接收另一个页面传递的参数
        const summaryId = history.state.summaryId
        if(summaryId) {
            financialBillDetailListParams.summaryId = summaryId
            history.state.summaryId = undefined
        }
    }
    onBeforeMount(() => {
        getHistoryState()
    })
    onActivated(() => {
        getHistoryState()
        searchBtn()
    })

    return {
        financialBillDetailListState,
        financialBillDetailListRef,
        financialBillDetailListTableRef,
        financialBillDetailSetRef,
        ladingBillMoneyListRef,
        financialBillDetailListParams,
        sizeChange,
        currentChange,
        searchBtn,
        resetBtn,
        handleClickChange,
        changeVisibleChange,
        hanleSaveConfirm,
        storeFeesetList,
        storeFinancialType,
        allProvidersList,
        companyEntityTypeList,
    }
}

export {
    useFinancialBillDetailList
}