<!-- 
    TODO 系统工具 / 费用测试
 -->
<template>
    <div class="p-4 query-customer-feetest">
        <el-form :inline="true" :model="customerFeeQueryParam" class="fesset-from">
            <BaseFormItem
                ref="queryCustomerRef"
                :schemas="schemasFormFeeset"
                :data-source="customerFeeQueryParam"
                :id="stateCustomerFeeTest.id"
                :item-mg-right="20"
                @change-form="hanleChangeForm"
            >
                <template #orderId>
                    <el-input v-model="stateCustomerFeeTest.orderId" placeholder="输入订单号，回车"
                        @keyup.enter="queryOrderFeeMethod" />
                </template>
            </BaseFormItem>
            <!-- <el-row>
                <el-col v-bind="schemasFormFeeset[0].propsCol">
                    <el-form-item :label-width="100" label="订单号：">
                        <el-input v-model="stateCustomerFeeTest.orderId" placeholder="输入订单号，回车"
                        @keyup.enter="queryOrderFeeMethod" />
                    </el-form-item>
                </el-col>
                <template v-for="schema in schemasFormFeeset" :key="schema.field">
                    <el-col v-bind="schema.propsCol">
                        <el-form-item :prop="schema.field" :label-width="schema.labelWidth" :label="schema.label">
                            <template v-if="schema.component === 'Select'">
                                <el-select v-model="customerFeeQueryParam[schema.field]" v-bind="schema"
                                    :collapse-tags="true"
                                    :style="{ minWidth: schema.minWidth ? schema.minWidth + 'px' : '' }">
                                    <template v-if="isArrayLength(schema.options as never)">
                                        <el-option v-for="item in schema.options" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </template>
                                </el-select>
                            </template>
                            <template v-else-if="schema.component === 'Input'">
                                <el-input v-model="customerFeeQueryParam[schema.field]" v-bind="schema"
                                    :style="{ minWidth: schema.minWidth ? schema.minWidth + 'px' : '' }" />
                            </template>
                            <template v-else-if="schema.component === 'DatePicker'">
                                <el-date-picker value-format="YYYY-MM-DD" style="width: 100%;"
                                    v-model="customerFeeQueryParam[schema.field]" type="date" />
                            </template>
                        </el-form-item>
                    </el-col>
                </template>
            </el-row> -->
            <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 #productId="scope">
                <div v-if="scope.$index >= 0" class="single-line">
                    {{ dealProductIdToName(scope.row.productId, productList) }}
                </div>
            </template>
            <template #action="scope">
                <el-button type="primary " class="add-columns" link @click="hanleViewDetails(scope.row)">明细</el-button>
            </template>
        </BaseTable>
        <customerFeetestDetail ref="customerFeetestDetailRef" />
    </div>
</template>
<script lang="ts" setup name="customerfeetest">
import { Plus, Delete } from '@element-plus/icons-vue'
import { CustomerFeeQueryParam, WeightVolume } from '@/api/customerfee/CustomerFeeSetModel';
import type { FormSchema } from '@/components/Form/src/types';
import { useDropDownData } from '@/hooks/useDropDownData';
import { ref, reactive, unref, onBeforeMount, onMounted } from 'vue';
import { BaseTable, useTable } from '@/components/Table';
import { BaseTableProps } from '@/components/Table/src/types';
import customerFeetestDetail from './customerFeetestDetail.vue';
import BaseFormItem from "@/components/BaseFormItem/BaseFormItem.vue";
import { api_OrderFeeQueryParam, getCustomerFeeQueryApi } from '@/api/customerfee/customerfeeset';
import { dealProductIdToName, deal_flat_flattenObject, deal_flat_initFlattenObj } from '@/utils/dealData';
import { useReturnData } from '@/utils/useReturnData';
import { useErrorConfirm } from '@/utils/useErrorConfirm';
import { useDeleteCache } from '@/hooks/useDeleteCache';

// 删除缓存
const instance = useDeleteCache()
const {
    storeDropDownData,
    productList,
    branchCompanyCustomers,
    customertList,
    feeSetTypeList,
    packageTypeList,
    portInfoList,
    countryList,
    specialFeeItemList,
    currencyList, 
    feeQueryTypeList
} = useDropDownData()
const { resData } = useReturnData()
const { report } = useErrorConfirm()
// 客户费用计费请求参数
const customerFeeQueryParam: CustomerFeeQueryParam = reactive({
    feeQueryType: 1,//费用查询默认值
} as CustomerFeeQueryParam)
// 基础数据
const stateCustomerFeeTest = reactive({
    loadingQuery: false,//查询loading
    orderId: '',//订单号
    id: 0,
})
const customerFeetestDetailRef = 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
}
// propsCol: {
//             md: 4,
//             lg: 6,
//             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: false,
        }
    },
    {
        field: "productIdList",
        component: "Select",
        label: "产品名称：",
        labelWidth: 100,
        propsCol,
        options: productList,
        componentProps: {
            multiple: true,
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "orgId",
        component: "Select",
        label: "分公司：",
        labelWidth: 100,
        propsCol,
        options: branchCompanyCustomers,
        componentProps: {
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "customerId",
        component: "Select",
        label: "客户：",
        labelWidth: 100,
        propsCol,
        options: customertList,
        componentProps: {
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "feeSetType",
        component: "Select",
        label: "费用类型：",
        labelWidth: 100,
        propsCol,
        options: feeSetTypeList,
        componentProps: {
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "packageType",
        component: "Select",
        label: "包装类型：",
        labelWidth: 100,
        propsCol,
        options: packageTypeList,
        componentProps: {
            filterable: true,
            clearable: true,
        }
    },
    {
        field: "currentDate",
        component: "Datetime",
        label: "日期：",
        labelWidth: 100,
        propsCol,
        componentProps: {
            defaultTime: new Date(2000, 1, 1, 6, 0, 0),
            clearable: true,
        }
    },
    {
        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,
    },
    {
        field: "recalculate",
        component: "Select",
        label: "是否重算",
        labelWidth: 100,
        propsCol,
        options: [
            {
                value: 1,
                label: '是'
            },
            {
                value: 0,
                label: '否'
            }
        ]
    },
    {
        field: "productPiece",
        component: "Input",
        label: "产品件数",
        labelWidth: 100,
        propsCol,
        inputRegex: /^\+?[1-9]\d*$/
    },
])

// 返回值
const tableFeeQueryResult: BaseTableProps = reactive({
    height: 340,
    maxHeight: 340,
    border: true,
    columns: [
        { prop: "productId", label: "产品名称", width: 130, slot: true, slotName: "productId", showOverflowTooltip: true },
        { prop: "totalFee", label: "总费用", width: 130 },
        { prop: "currencyCode", label: "币种", width: 110 },
        { 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: "feeVersionNumber", label: "费用版本号", width: 180 },
        {
            prop: "action",
            label: "费用明细",
            width: 100,
            slot: true,
            slotName: 'action',
            fixed: "right"
        },
    ],
    dataSource: [
        // { productId: "XYYGSDO" }
    ],
});
const [registerResultTable] = useTable(tableFeeQueryResult)

// 初始化列表数据
onBeforeMount(() => {
    storeDropDownData.addProductList()
    storeDropDownData.addBranchCompanyCustomers()
    storeDropDownData.addCustomertList()
    storeDropDownData.addFeeSetTypeList()
    storeDropDownData.addPackageTypeList()
    storeDropDownData.addPortInfoList()
    storeDropDownData.addCountryList()
    storeDropDownData.addSpecialParametersList()
    storeDropDownData.addCurrencyList()
    storeDropDownData.addSpecialFeeItemList()
    storeDropDownData.addFeeQueryTypeList()
    // 初始化搜索框默认值
    const formFeeset = unref(schemasFormFeeset)
    formFeeset.forEach(item => {
        if (!customerFeeQueryParam[item.field] && item.field !== 'feeQueryType') {
            customerFeeQueryParam[item.field] = null
        }
    })
})
onMounted(() => {
    stateCustomerFeeTest.id = 2
})

// 添加重量体积
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) => {
    customerFeetestDetailRef.value?.show(data.feeItemDtoList)
    // console.log(data,":查看明细");
}

// 表单change事件
const hanleChangeForm = (data) => {
    // 合并参数
    Object.assign(customerFeeQueryParam, { ...data })
}
// 查询
const hanleQuery = async () => {
    stateCustomerFeeTest.loadingQuery = true
    const WeightVolume = tableCustomerFeeQuery.dataSource
    // 参数
    customerFeeQueryParam.weightVolumeList = WeightVolume as WeightVolume[]
    const params = deal_flat_initFlattenObj<CustomerFeeQueryParam>(customerFeeQueryParam,'destinationAddress')
    try {
        // console.log(customerFeeQueryParam, ":customerFeeQueryParam", params);
        const res = await getCustomerFeeQueryApi(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(customerFeeQueryParam, { ...data, ...destinationAddress })
        tableCustomerFeeQuery.dataSource = customerFeeQueryParam.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>