<!-- 保税仓业务-出仓管理-进仓信息 -->
<template>
    <app-drawer title="进仓信息" :width="860" v-model:show="show">
        <el-form ref="formRef" class="el-form--horizontal" label-width="150px" :model="formItem" :rules="formRules">
            <el-form-item label="本次扣减量(克拉)" prop="curnetweightct">
                <el-input-number placeholder="请输入" v-model="formItem.curnetweightct" :max="maxNetWeightCT"
                    :disabled="!selectedPosition" />
            </el-form-item>
            <el-form-item label="本次扣减净重(克)">
                <el-input :value="calcField.netWeight" readonly />
            </el-form-item>
            <el-form-item label="本次扣减总价">
                <el-input :value="calcField.totalPrice" readonly />
            </el-form-item>
            <el-form-item label="本次扣减货值">
                <el-input :value="calcField.value" readonly />
            </el-form-item>
        </el-form>
        <app-table ref="tableRef" :data="positionList" :columns="columns" :max-height="400" :show-toolbar="false"
            selection-type="single" border @select="onTableSelect">
            <!-- 可用净重(克拉) -->
            <template #netweight="{ row }">
                {{ row.netweightct - row.freezenetweightct }}
            </template>
        </app-table>
        <template #footer>
            <el-button @click="onCancel" plain>取消</el-button>
            <el-button type="primary" @click="onSubmit">保存</el-button>
        </template>
    </app-drawer>
</template>

<script lang="ts" setup>
import { ref, PropType, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { queryGzbscPosition } from '@/services/api/bonded'
import { useLoginStore } from '@/stores'
import AppDrawer from '@pc/components/base/drawer/index.vue'
import AppTable from '@pc/components/base/table/index.vue'

const props = defineProps({
    selectedRow: {
        type: Object as PropType<Ermcp.BScOutOrderDetailattRsp>
    },
    // 头寸列表过滤项
    filteredValue: {
        type: Array as PropType<number[]>,
        default: () => ([])
    }
})

const emit = defineEmits(['update'])
const loginStore = useLoginStore()
const show = ref(true)
const formRef = ref<FormInstance>()
const tableRef = ref()
const positionList = ref<Ermcp.GzbscPositionRsp[]>([])
const formItem = ref<Partial<Ermcp.BScOutOrderDetailattRsp>>({ detailattid: '0', ...props.selectedRow })
const selectedPosition = ref<Ermcp.GzbscPositionRsp>() // 当前选中的头寸

const columns: Ermcp.TableColumn[] = [
    { prop: 'goodsname', label: '商品名称' },
    { prop: 'customsno', label: '进口单号' },
    { prop: 'jckdate', label: '进口日期' },
    { prop: 'netweightct', label: '净重(克拉)' },
    { prop: 'freezenetweightct', label: '冻结净重(克拉)' },
    { prop: 'netweight', label: '可用净重(克拉)' },
    { prop: 'netweightgm', label: '净重(克)' },
    { prop: 'totalprice', label: '总价' },
    { prop: 'customsvalue', label: '报关总值' },
]

const formRules: FormRules = {
    curnetweightct: [{
        required: true,
        message: '请输入本次扣减量'
    }],
}

// 可用净重（克拉)
const maxNetWeightCT = computed(() => {
    if (selectedPosition.value) {
        const { netweightct = 0, freezenetweightct = 0 } = selectedPosition.value
        return (netweightct - freezenetweightct) || 0
    }
    return undefined
})

// 相关字段计算值
const calcField = computed(() => {
    const curnetweightct = formItem.value.curnetweightct ?? 0
    let netWeight = 0
    let totalPrice = 0
    let unitPrice = 0
    let value = 0

    if (curnetweightct && selectedPosition.value) {
        const { netweightct, netweightgm, totalprice, customsvalue } = selectedPosition.value
        const n = curnetweightct / netweightct
        netWeight = n * netweightgm
        totalPrice = n * totalprice
        unitPrice = totalPrice / netWeight
        value = n * customsvalue
    }

    return {
        netWeight: netWeight.toFixed(2), // 净重(克)
        totalPrice: totalPrice.toFixed(2), // 总价
        unitPrice: unitPrice.toFixed(2), // 单价(克)
        value: value.toFixed(2), // 货值
    }
})

// 勾选表格行
const onTableSelect = ([row]: Ermcp.GzbscPositionRsp[]) => {
    formItem.value.curnetweightct = undefined
    selectedPosition.value = row
}

const onCancel = () => {
    show.value = false
}

const onSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            const row = selectedPosition.value
            if (row) {
                const { detailattid, curnetweightct = 0 } = formItem.value ?? {}
                formItem.value = {
                    goodsid: Number(row.goodsid),
                    goodsname: row.goodsname,
                    customsno: row.customsno,
                    jckdate: row.jckdate,
                    netweightct: row.netweightct,
                    remainnetweightct: row.netweightct - curnetweightct,
                    customsvalue: row.customsvalue,
                    curcustomsvalue: Number(calcField.value.value),
                    remaincustomsvalue: row.customsvalue - curnetweightct,
                    detailattid,
                    curnetweightct
                }
                emit('update', formItem.value)
                onCancel()
            } else {
                ElMessage.warning('请选择商品')
            }
        }
    })
}

queryGzbscPosition({
    userid: loginStore.userId
}).then((res) => {
    const goodsId = formItem.value.goodsid
    if (goodsId) {
        positionList.value = res.data.filter((e) => e.goodsid === goodsId?.toString())
    } else {
        positionList.value = res.data.filter((e) => !props.filteredValue.includes(Number(e.goodsid)))
    }
    nextTick(() => {
        selectedPosition.value = res.data.find((e) => e.goodsid === goodsId?.toString())
        if (selectedPosition.value) {
            tableRef.value?.elTable.toggleRowSelection(selectedPosition.value)
        }
    })
})
</script>