<!-- 
    TODO 系统工具 / 成本费用测试
 -->
<template>
    <div class="p-4 query-customer-feetest">
        <el-form :inline="true" :model="providerFeeQueryParam" class="fesset-from">
            <BaseFormItem
                ref="queryCustomerRef"
                :schemas="schemasFormFeeset"
                :data-source="providerFeeQueryParam"
                :item-mg-right="20"
                @change-form="hanleChangeForm"
            >
                <template #orderId>
                    <el-input v-model="stateCustomerFeeTest.orderId" placeholder="输入订单号，回车"
                        @keyup.enter="queryOrderFeeMethod" />
                </template>
            </BaseFormItem>
            <BaseTable @register="registerFormTable">
                <!-- 自定义插槽 -->
                <template #weight="scope">
                    <template v-if="scope.$index >= 0">
                        <el-input v-model="scope.row.weight"
                            oninput="value = value.replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g, '$1')" />
                    </template>
                </template>
                <template #volume="scope">
                    <template v-if="scope.$index >= 0">
                        <el-input v-model="scope.row.volume"
                            oninput="value = value.replace(/^\D*(\d*(?:\.\d{0,3})?).*$/g, '$1')" />
                    </template>
                </template>
                <template #length="scope">
                    <template v-if="scope.$index >= 0">
                        <el-input v-model="scope.row.length"
                            oninput="value = value.replace(/^\D*(\d*(?:\.\d{0,3})?).*$/g, '$1')" />
                    </template>
                </template>
                <template #width="scope">
                    <template v-if="scope.$index >= 0">
                        <el-input v-model="scope.row.width"
                            oninput="value = value.replace(/^\D*(\d*(?:\.\d{0,3})?).*$/g, '$1')" />
                    </template>
                </template>
                <template #height="scope">
                    <template v-if="scope.$index >= 0">
                        <el-input v-model="scope.row.height"
                            oninput="value = value.replace(/^\D*(\d*(?:\.\d{0,3})?).*$/g, '$1')" />
                    </template>
                </template>
                <!-- 表格头部插槽 -->
                <template #header-action>
                    <el-button type="primary" class="add-columns" link :icon="Plus" @click="hanleAddColumns" />
                </template>
                <template #action="scope">
                    <el-button type="danger" class="add-columns" link :icon="Delete" @click="hanleDeleteColumns(scope)" />
                </template>
            </BaseTable>
            <div class="query">
                <el-button type="primary" @click="hanleQuery" :loading="stateCustomerFeeTest.loadingQuery">查询</el-button>
            </div>
        </el-form>
        <div class="title">计费结果:</div>
        <BaseTable @register="registerResultTable">
            <template #action="scope">
                <el-button type="primary " class="add-columns" link @click="hanleViewDetails(scope.row)">明细</el-button>
            </template>
        </BaseTable>
        <queryProviderFeeDetail ref="queryProviderFeeDetailRef" />
    </div>
</template>
<script lang="ts" setup name="queryproviderfee">
import { Plus, Delete } from '@element-plus/icons-vue'
import { WeightVolume } from '@/api/customerfee/CustomerFeeSetModel';
import type { FormSchema } from '@/components/Form/src/types';
import { useDropDownData } from '@/hooks/useDropDownData';
import { ref, reactive, computed, unref, onBeforeMount } from 'vue';
import { BaseTable, useTable } from '@/components/Table';
import { BaseTableProps } from '@/components/Table/src/types';
import queryProviderFeeDetail from './queryProviderFeeDetail.vue';
import BaseFormItem from "@/components/BaseFormItem/BaseFormItem.vue";
import { api_OrderFeeQueryParam } from '@/api/customerfee/customerfeeset';
import { deal_flat_flattenObject, deal_flat_initFlattenObj } from '@/utils/dealData';
import { useReturnData } from '@/utils/useReturnData';
import { useErrorConfirm } from '@/utils/useErrorConfirm';
import { useDeleteCache } from '@/hooks/useDeleteCache';
import { useFeesetList } from '@/store/list_feeset';
import { api_costFee_costFeeQuery } from '@/api/costFeeSet/costFeeSet';
import { CostFeeQueryParam } from '@/api/costFeeSet/costFeeSetModel';

// 删除缓存
const instance = useDeleteCache()
const {
    storeDropDownData,
    deliverChannelList,
    allProvidersList,
    packageTypeList,
    portInfoList,
    countryList,
    specialFeeItemList,
    currencyList, 
    feeQueryTypeList
} = useDropDownData()
const storeFeesetList = useFeesetList()
// 费项列表
const feeItemCategoryList = computed(() => storeFeesetList.getFeeItemCategoryList)
// 成本费用使用部门
const costFeeQueryDepartmentList = computed(() => storeFeesetList.getCostFeeQueryDepartmentList)
const { resData } = useReturnData()
const { report } = useErrorConfirm()
// 客户费用计费请求参数
const providerFeeQueryParam = reactive({} as CostFeeQueryParam)
// 基础数据
const stateCustomerFeeTest = reactive({
    loadingQuery: false,//查询loading
    orderId: '',//订单号
})
const queryProviderFeeDetailRef = ref<{ show: (details: Recordable) => void }>()
// 重量体积表格
const tableCustomerFeeQuery: BaseTableProps = reactive({
    height: 280,
    maxHeight: 280,
    border: true,
    columns: [
        {
            prop: "weight",
            label: "重量（kg）",
            slot: true,
            slotName: "weight"
        },
        {
            prop: "volume",
            label: "体积（cm³）",
            slot: true,
            slotName: "volume"
        },
        {
            prop: "length",
            label: "长度（cm）",
            slot: true,
            slotName: "length"
        },
        {
            prop: "width",
            label: "宽度（cm）",
            slot: true,
            slotName: "width"
        },
        {
            prop: "height",
            label: "高度（cm）",
            slot: true,
            slotName: "height"
        },
        {
            prop: "action",
            label: "操作",
            width: 60,
            slot: true,
            slotHeader: true,
            slotName: 'action'
        },
    ],
    dataSource: [],
});
// 注册新增表格-控件
const [registerFormTable] = useTable(tableCustomerFeeQuery)

const propsCol = {
    md: 12,
    lg: 6,
    llg: 5,
    xl: 4
}
// 基础表单
const schemasFormFeeset = ref<FormSchema[]>([
    {
        field: "orderId",
        component: "Slot",
        label: "订单号：",
        labelWidth: 100,
        propsCol,
    },
    {
        field: "feeQueryType",
        component: "Select",
        label: "费用查询：",
        labelWidth: 100,
        propsCol,
        options: feeQueryTypeList,
        componentProps: {
            clearable: true,
        }
    },
    {
        field: "providerId",
        component: "Select",
        label: "服务商：",
        labelWidth: 100,
        propsCol,
        options: allProvidersList,
        componentProps: {
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "feeItemCategory",
        component: "Select",
        label: "费项类型：",
        labelWidth: 100,
        propsCol,
        options: feeItemCategoryList,
        componentProps: {
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "costFeeQueryDepartment",
        component: "Select",
        label: "使用部门：",
        labelWidth: 100,
        propsCol,
        options: costFeeQueryDepartmentList,
        componentProps: {
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "productId",
        component: "Select",
        label: "产品名称：",
        labelWidth: 100,
        propsCol,
        options: deliverChannelList,
        componentProps: {
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "packageType",
        component: "Select",
        label: "包装类型：",
        labelWidth: 100,
        propsCol,
        options: packageTypeList,
        componentProps: {
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "currentDate",
        component: "DatePicker",
        label: "日期：",
        labelWidth: 100,
        propsCol,
    },
    {
        field: "destinationAddress.portCode",
        component: "Select",
        label: "口岸：",
        labelWidth: 100,
        propsCol,
        options: portInfoList,
        componentProps: {
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "destinationAddress.countryCode",
        component: "Select",
        label: "国家/地区：",
        labelWidth: 100,
        propsCol,
        options: countryList,
        componentProps: {
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "destinationAddress.zipCode",
        component: "Input",
        label: "邮编：",
        labelWidth: 100,
        propsCol,
    },
    {
        field: "destinationAddress.address",
        component: "Input",
        label: "地址：",
        labelWidth: 100,
        propsCol,
    },
    {
        field: "feeItemSpecialFlagList",
        component: "Select",
        label: "特殊费用：",
        labelWidth: 100,
        propsCol,
        options: specialFeeItemList,
        componentProps: {
            multiple: true,
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "customsFees",
        component: "Input",
        label: "报关费用：",
        labelWidth: 100,
        propsCol,
    },
    {
        field: "customsCode",
        component: "Select",
        label: "报关货币：",
        labelWidth: 100,
        propsCol,
        options: currencyList,
        componentProps: {
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "customsPageNumber",
        component: "Input",
        label: "报关页数",
        labelWidth: 100,
        propsCol,
    },
    {
        field: "lightFlag",
        component: "Select",
        label: "是否计抛：",
        labelWidth: 100,
        propsCol,
        options: [
            {
                value: 1,
                label: '是'
            },
            {
                value: 0,
                label: '否'
            }
        ]
    },
    {
        field: "weightRatio",
        component: "Input",
        label: "计抛系数：",
        labelWidth: 100,
        propsCol,
        // minWidth: 220,
    },
    {
        field: "productNumber",
        component: "Input",
        label: "品名数量",
        labelWidth: 100,
        propsCol,
    },
    {
        field: "specialPackageNumber",
        component: "Input",
        label: "异形数量",
        labelWidth: 100,
        propsCol,
    },
])

// 返回值
const tableFeeQueryResult: BaseTableProps = reactive({
    height: 340,
    maxHeight: 340,
    border: true,
    columns: [
        { prop: "productName", label: "产品名称", width: 120, showOverflowTooltip: true },
        { prop: "providerName", label: "服务商", width: 120, showOverflowTooltip: true },
        { prop: "feeItemCategoryName", label: "费项类型", width: 120, showOverflowTooltip: true },
        { prop: "totalFee", label: "总费用（CNY）", width: 130 },
        { prop: "countFeeWeight", label: "计费重量（kg）", width: 130, },
        { prop: "volumeWeight", label: "体积重量（kg）", width: 130, },
        { prop: "packageTypeName", label: "包装类型", width: 120, },
        { prop: "partitionName", label: "分区名称", width: 120, },
        { prop: "formulaDescription", label: "公式描述", minWidth: 120, },
        { prop: "message", label: "提示信息", width: 180, showOverflowTooltip: true },
        {
            prop: "action",
            label: "费用明细",
            width: 100,
            slot: true,
            slotName: 'action'
        },
    ],
    dataSource: [
        // { productId: "USLine-6" }
    ],
});
const [registerResultTable] = useTable(tableFeeQueryResult)

// 初始化列表数据
onBeforeMount(() => {
    storeDropDownData.addDeliverChannelListApi()
    storeDropDownData.addAllProvidersList()
    storeFeesetList.addFeeItemCategoryList()
    storeFeesetList.addCostFeeQueryDepartmentList()
    storeDropDownData.addPackageTypeList()
    storeDropDownData.addPortInfoList()
    storeDropDownData.addCountryList()
    storeDropDownData.addSpecialParametersList()
    storeDropDownData.addCurrencyList()
    storeDropDownData.addSpecialFeeItemList()
    storeDropDownData.addFeeQueryTypeList()
    // 初始化搜索框默认值
    const formFeeset = unref(schemasFormFeeset)
    formFeeset.forEach(item => {
        if (!providerFeeQueryParam[item.field]) {
            providerFeeQueryParam[item.field] = null
        }
    })
})

// 添加重量体积
const hanleAddColumns = () => {
    tableCustomerFeeQuery.dataSource.push({
        weight: undefined,
        volume: undefined,
        length: undefined,
        width: undefined,
        height: undefined,
    })
}
// 删除
const hanleDeleteColumns = (row: Recordable) => {
    const index = row.$index
    tableCustomerFeeQuery.dataSource.splice(index, 1)
}

// 查看明细
const hanleViewDetails = (data: Recordable) => {
    queryProviderFeeDetailRef.value?.show(data.feeItemDtoList)
    // console.log(data,":查看明细");
}

// 表单change事件
const hanleChangeForm = (data) => {
    // 合并参数
    Object.assign(providerFeeQueryParam, { ...data })
}
// 查询
const hanleQuery = async () => {
    stateCustomerFeeTest.loadingQuery = true
    const WeightVolume = tableCustomerFeeQuery.dataSource
    // 参数
    providerFeeQueryParam.weightVolumeList = WeightVolume as WeightVolume[]
    const params = deal_flat_initFlattenObj<CostFeeQueryParam>(providerFeeQueryParam,'destinationAddress')
    try {
        // console.log(providerFeeQueryParam, ":providerFeeQueryParam", params);
        const res = await api_costFee_costFeeQuery(params)
        console.log(res, "返回的数据");
        const data = resData(res)
        if (data !== 500) {
            tableFeeQueryResult.dataSource = data
        }
    } catch (error) {
        report(error)
    } finally {
        stateCustomerFeeTest.loadingQuery = false
    }
}

// 单号查询
const queryOrderFeeMethod = async () => {
    if (stateCustomerFeeTest.orderId === '') return
    const result = await api_OrderFeeQueryParam({ orderId: stateCustomerFeeTest.orderId })
    if (result.code === 200) {
        const data = result.data
        const destinationAddress = deal_flat_flattenObject({ destinationAddress: data.destinationAddress })
        Object.assign(providerFeeQueryParam, { ...data, ...destinationAddress })
        tableCustomerFeeQuery.dataSource = providerFeeQueryParam.weightVolumeList
    }
}

</script>
<style lang="scss" scoped>
.query-customer-feetest {
    .query {
        text-align: right;
        padding: 5px 0;
    }

    .title {
        padding: 5px 0;
        font-size: 15px;
    }
}

@media only screen and (min-width: 1400px) and (max-width: 1900px) {
    .el-col-lg-6 {
        display: block;
        max-width: 19.833333%;
        flex: 0 0 19.833333%;
    }
}
</style>