import { api_getLadingBillMainByPId } from '@/api/lading/lading';
import { LadingBillMainDto } from '@/api/lading/ladingModle';
import type { FormSchema } from '@/components/Form/src/types';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { usePersonnel } from '@/store/list_personnel';
import { DialogModel } from '@/type/BastType';
import { cloneDeep } from '@/utils/cloneDeep';
import { deal_SetObjectData } from '@/utils/dealData';
import { deal_FindItemName } from '@/utils/dealFindData';
import { isNumber, isString } from '@/utils/is';
import { ref, reactive, unref, computed, onMounted } from 'vue';

/**
 * 处理提单新增、编辑
 */
function useLadingBillSet(dialog: DialogModel, onClose: Fn, onShow: Fn, emit) {
    const {
        storeDropDownData,
        countryList,
        customertList,
        portInfoList,
        allProvidersList,
        companyEntityTypeList,
        airBusinessTypeList,
        airCompanyList,
        branchCompanyCustomers
    } = useDropDownData()
    const storePersonnel = usePersonnel()
    const salesmanUsesList = computed(() => storePersonnel.getSalesmanUsesList)
    const ladingBillSetFormRef = ref()
    // 表单
    const basisListRef = ref<{ reset: Fn }>()
    const bookingRef = ref<{ reset: Fn }>()
    const calculateCostRef = ref<{ reset: Fn }>()
    const propsCol = {
        md: 12,
        lg: 8,
        llg: 6,
        xl: 6
    }
    const inputRegex = /^\d*\.?\d{0,3}$/
    // 基础表单
    const ladingBillSetForm = reactive<LadingBillMainDto>({
        id: undefined,
        stakeholder: undefined,
        stakeholderName: undefined,
        businessType: undefined,
        bookingTime: "",
        takeOffTime: "",
        bookingNumber: "",
        waybillNumber: "",
        customerId: undefined,
        airlinesId: undefined,
        bookingAgentId: undefined,
        departurePort: "",
        transitPort: "",
        destinationPort: "",
        countryId: undefined,
        zipCode: "",
        address: "",
        salesmanId: undefined,
        sellingPrice: undefined,
        costPrice: undefined,
        settlementPrice: undefined,
        orderNumber: undefined,
        weight: undefined,
        volume: undefined,
        bookingRemark: "",
        packageNumber: undefined,
        grossWeight: undefined,
        feeVolume: undefined,
        volumeWeight: undefined,
        feeWeight: undefined,
        allocationRatio: undefined,
        receivableWeight: undefined,
        payableWeight: undefined,
        feeRemark: undefined,
        branchOfficeCode: "",
        customerName: undefined
    })
    const ladingBillSetState = reactive<{
        basisList: FormSchema[],
        booking: FormSchema[],
        calculateCost: FormSchema[],
        rulesLadingBillSet: Recordable
    }>({
        basisList: [
            {
                field: "businessType",
                component: "Select",
                label: "业务类型:",
                labelWidth: 100,
                propsCol,
                options: airBusinessTypeList,
                componentProps: {
                    clearable: true,
                },
            },
            {
                field: "bookingTime",
                component: "DatePicker",
                label: "订舱时间:",
                labelWidth: 100,
                propsCol,
            },
            {
                field: "takeOffTime",
                component: "DatePicker",
                label: "起飞时间:",
                labelWidth: 100,
                propsCol,
            },
            {
                field: "bookingNumber",
                component: "Input",
                label: "订舱号:",
                labelWidth: 100,
                propsCol,
            },
            {
                field: "waybillNumber",
                component: "Input",
                label: "提单号:",
                labelWidth: 100,
                propsCol,
            },
            {
                field: "customerId",
                component: "SelectV2",
                label: "客户:",
                labelWidth: 100,
                propsCol,
                options: customertList,
                componentProps: {
                    filterable: true,
                    clearable: true,
                    popperClass: "customerId-w",
                    // onChange: (val) => {
                    //     const findData = unref(customertList).find(item => item.value === String(val))
                    //     ladingBillSetForm.customerName = findData?.label
                    // }
                }
            },
            {
                field: "airlinesId",
                component: "Select",
                label: "航司名称:",
                labelWidth: 100,
                propsCol,
                options: airCompanyList,
                componentProps: {
                    filterable: true,
                    clearable: true,
                }
            },
            {
                field: "bookingAgentId",
                component: "SelectV2",
                label: "订舱代理:",
                labelWidth: 100,
                propsCol,
                options: allProvidersList,
                componentProps: {
                    filterable: true,
                    clearable: true,
                    popperClass: "booking-agentId-w"
                }
            },
            {
                field: "departurePort",
                component: "Select",
                label: "始发港:",
                labelWidth: 100,
                propsCol,
                options: portInfoList,
                componentProps: {
                    filterable: true,
                    clearable: true,
                }
            },
            {
                field: "transitPort",
                component: "Select",
                label: "中转港:",
                labelWidth: 100,
                propsCol,
                options: portInfoList,
                componentProps: {
                    filterable: true,
                    clearable: true,
                }
            },
            {
                field: "destinationPort",
                component: "Select",
                label: "目的港:",
                labelWidth: 100,
                propsCol,
                options: portInfoList,
                componentProps: {
                    filterable: true,
                    clearable: true,
                }
            },
            {
                field: "countryId",
                component: "SelectV2",
                label: "国家/地区:",
                labelWidth: 110,
                propsCol,
                options: countryList,
                componentProps: {
                    // multiple: true,
                    filterable: true,
                    clearable: true,
                    popperClass: "countryId-w"
                }
            },
            {
                field: "zipCode",
                component: "Input",
                label: "邮编:",
                labelWidth: 100,
                propsCol,
            },
            {
                field: "address",
                component: "Input",
                label: "地址:",
                labelWidth: 100,
                propsCol,
            },
            {
                field: "salesmanId",
                component: "SelectV2",
                label: "业务员:",
                labelWidth: 100,
                propsCol,
                options: salesmanUsesList,
                componentProps: {
                    filterable: true,
                    clearable: true,
                    popperClass: "salesmanId-w"
                }
            },
            {
                field: "branchOfficeCode",
                component: "Select",
                label: "分公司:",
                labelWidth: 100,
                propsCol,
                options: branchCompanyCustomers,
            },
        ],
        booking: [
            {
                field: "sellingPrice",
                component: "Input",
                label: "卖价:",
                labelWidth: 100,
                propsCol,
                inputRegex,
            },
            {
                field: "costPrice",
                component: "Input",
                label: "成本价:",
                labelWidth: 100,
                propsCol,
                inputRegex,
            },
            {
                field: "settlementPrice",
                component: "Input",
                label: "结算价:",
                labelWidth: 100,
                propsCol,
                inputRegex,
            },
            {
                field: "orderNumber",
                component: "Input",
                label: "件数:",
                labelWidth: 100,
                propsCol,
                inputRegex: /^(?:\+?[1-9]\d*)?$/,
            },
            {
                field: "weight",
                component: "Input",
                label: "重量:",
                labelWidth: 100,
                propsCol,
                inputRegex,
            },
            {
                field: "volume",
                component: "Input",
                label: "体积:",
                labelWidth: 100,
                propsCol,
                inputRegex,
            },
            {
                field: "bookingRemark",
                component: "Input",
                label: "备注:",
                labelWidth: 100,
                inputRegex,
                propsCol: {
                    md: 24,
                    lg: 16,
                    llg: 12,
                    xl: 12
                },
            },
        ],
        calculateCost: [
            {
                field: "packageNumber",
                component: "Input",
                label: "包装件数:",
                labelWidth: 100,
                propsCol,
                inputRegex: /^(?:\+?[1-9]\d*)?$/,
            },
            {
                field: "grossWeight",
                component: "Input",
                label: "毛重(KG):",
                labelWidth: 100,
                propsCol,
                inputRegex,
            },
            {
                field: "feeVolume",
                component: "Input",
                label: "体积(CBM):",
                labelWidth: 100,
                propsCol,
                inputRegex,
            },
            {
                field: "volumeWeight",
                component: "Input",
                label: "体积重(KG):",
                labelWidth: 100,
                propsCol,
                inputRegex,
            },
            {
                field: "feeWeight",
                component: "Input",
                label: "计费重(KG):",
                labelWidth: 100,
                propsCol,
                inputRegex,
            },
            {
                field: "allocationRatio",
                component: "Input",
                label: "分配比例(%):",
                labelWidth: 100,
                propsCol,
                inputRegex,
            },
            {
                field: "receivableWeight",
                component: "Input",
                label: "应收计费重:",
                labelWidth: 100,
                propsCol,
                inputRegex,
            },
            {
                field: "payableWeight",
                component: "Input",
                label: "应付计费重:",
                labelWidth: 100,
                propsCol,
                inputRegex,
            },
            {
                field: "feeRemark",
                component: "Input",
                label: "备注:",
                labelWidth: 100,
                propsCol: {
                    md: 24,
                    lg: 16,
                    llg: 12,
                    xl: 12
                },
            },
        ],
        rulesLadingBillSet: {
            stakeholder: [{ required: true, message: '请选择主体类型', trigger: 'change' }],
            bookingTime: [{ required: true, message: '请选择订舱时间', trigger: 'change' }],
            takeOffTime: [{ required: true, message: '请选择起飞时间', trigger: 'change' }],
            bookingNumber: [{ required: true, message: '请输入订舱号', trigger: 'blur' }],
            customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
            airlinesId: [{ required: true, message: '请选择航司名称', trigger: 'change' }],
            salesmanId: [{ required: true, message: '请选择业务员', trigger: 'change' }],
            branchOfficeCode: [{ required: true, message: '请选择分公司编号', trigger: 'change' }],
            sellingPrice: [{ required: true, message: '请输入卖价', trigger: 'blur' }],
            costPrice: [{ required: true, message: '请输入成本价', trigger: 'blur' }],
            settlementPrice: [{ required: true, message: '请输入结算价', trigger: 'blur' }],
            orderNumber: [{ required: true, message: '请输入件数', trigger: 'blur' }],
            weight: [{ required: true, message: '请输入重量', trigger: 'blur' }],
            volume: [{ required: true, message: '请输入体积', trigger: 'blur' }],
        }
    })
    // 校验表单
    const { formValidate, resetForm } = useEleFormValidate();

    // 显示
    const show = (id: number) => {
        id ? dialog.title = "编辑提单" : dialog.title = "新增提单"
        if (id) initFormData(id)
        onShow()
    }

    // 隐藏
    const onclose = () => {
        unref(basisListRef)?.reset()
        unref(bookingRef)?.reset()
        unref(calculateCostRef)?.reset()
        resetForm(ladingBillSetFormRef.value)
        onClose()
    }
    // 更新表单数据
    const changeLadingBillSetForm = (data: LadingBillMainDto) => {
        const cloneData = cloneDeep(data) as LadingBillMainDto
        Object.keys(ladingBillSetForm).forEach((key) => {
            if (isString(cloneData[key]) || isNumber(cloneData[key])) {
                ladingBillSetForm[key] = cloneData[key];
            }
        })
        ladingBillSetForm.id = data.id
        // Object.assign(ladingBillSetForm, { ...cloneData, stakeholder: ladingBillSetForm.stakeholder })
    }
    // 初始化表单值
    const initFormData = async (id: number) => {
        const res = await api_getLadingBillMainByPId({ id })
        if (res && res.code == 200) {
            const data = cloneDeep(res.data)
            if (data.customerId) data.customerId = String(data.customerId)
            if (data.salesmanId) data.salesmanId = String(data.salesmanId)
            if (data.bookingAgentId) data.bookingAgentId = String(data.bookingAgentId)
            changeLadingBillSetForm(data)
            // Object.assign(ladingBillSetForm, { ...data })
        }
    }
    // 处理参数
    const dealParams = () => {
        if (ladingBillSetForm.customerId) {
            const label = deal_FindItemName(String(ladingBillSetForm.customerId), unref(customertList))
            ladingBillSetForm.customerName = label
        }
        const label = deal_FindItemName(Number(ladingBillSetForm.stakeholder), unref(companyEntityTypeList))
        ladingBillSetForm.stakeholderName = label
        const params = cloneDeep(ladingBillSetForm)
        return params
    }
    // 确定
    const confirm = async () => {
        const isValidate = await formValidate(ladingBillSetFormRef.value)
        if (!isValidate) return
        // 获取参数
        const params = dealParams()
        // console.log(params, ":params");
        emit('saveConfirm', params, onclose)
    }

    onMounted(() => {
        storeDropDownData.addPortInfoList()
    })

    return {
        show,
        onclose,
        confirm,
        changeLadingBillSetForm,
        ladingBillSetFormRef,
        ladingBillSetForm,
        ladingBillSetState,
        basisListRef,
        bookingRef,
        calculateCostRef,
        companyEntityTypeList
    }
}

export {
    useLadingBillSet
}