<!-- 保税仓业务-出仓管理-提交申请 -->
<template>
    <app-drawer class="g-details" title="提交申请" v-model:show="show" :width="960" :loading="loading" :refresh="refresh">
        <h3 class="g-details__title">收货信息</h3>
        <el-form ref="formRef" class="el-form--horizontal" label-width="100px" :model="formData" :rules="formRules">
            <el-form-item label="收货方" prop="UserName">
                <el-input placeholder="请输入" v-model="formData.UserName" />
            </el-form-item>
            <el-form-item label="收货地址" prop="UserAddress">
                <el-input placeholder="请输入" v-model="formData.UserAddress" />
            </el-form-item>
            <el-form-item label="联系人" prop="ContactName">
                <el-input placeholder="请输入" v-model="formData.ContactName" />
            </el-form-item>
            <el-form-item label="联系电话" prop="ContactNum">
                <el-input placeholder="请输入" v-model="formData.ContactNum" />
            </el-form-item>
            <el-form-item label="物流公司" prop="LogisticsCompany">
                <el-input placeholder="请输入" v-model="formData.LogisticsCompany" />
            </el-form-item>
            <el-form-item label="托运单号" prop="LogisticsNo">
                <el-input placeholder="请输入" v-model="formData.LogisticsNo" />
            </el-form-item>
            <el-form-item label="出仓类型" prop="OutType">
                <el-select v-model="formData.OutType">
                    <el-option :label="item.label" :value="item.value" v-for="(item, index) in getGZBSCOutTypeList()"
                        :key="index" />
                </el-select>
            </el-form-item>
        </el-form>
        <app-table :data="orderDetailList" :columns="columns1" :max-height="400" border showToolbar>
            <template #header>
                <h3 class="g-details__title">商品信息</h3>
            </template>
            <template #toolbar>
                <el-button-group>
                    <el-button size="small" @click="openEdit('detailEdit')">新增</el-button>
                    <el-button size="small" @click="orderDetailList = []">清空</el-button>
                </el-button-group>
            </template>
            <!-- 操作 -->
            <template #operate="{ row, index }">
                <el-button-group size="small">
                    <el-button @click="openEdit('detailEdit', row)">修改</el-button>
                    <el-button @click="deleteRecord(index)">删除</el-button>
                </el-button-group>
            </template>
        </app-table>
        <app-table :data="orderDetailAttList" :columns="columns2" :max-height="400" border showToolbar>
            <template #header>
                <h3 class="g-details__title">附表信息</h3>
            </template>
            <template #toolbar>
                <el-button-group>
                    <el-button size="small" @click="openEdit('subDetailEdit')">新增</el-button>
                    <el-button size="small" @click="orderDetailAttList = []">清空</el-button>
                </el-button-group>
            </template>
            <!-- 操作 -->
            <template #operate="{ row, index }">
                <el-button-group size="small">
                    <el-button @click="openEdit('subDetailEdit', row)">修改</el-button>
                    <el-button @click="deleteSubRecord(index)">删除</el-button>
                </el-button-group>
            </template>
        </app-table>
        <template #footer>
            <el-button @click="onCancel(false)" plain>取消</el-button>
            <el-button type="primary" @click="onSubmit">提交</el-button>
        </template>
        <component :is="componentMap.get(componentId)"
            v-bind="{ selectedRow, filteredValue: orderDetailAttList.map((e) => e.goodsid) }" @update="onUpdate"
            @closed="closeComponent" v-if="componentId" />
    </app-drawer>
</template>

<script lang="ts" setup>
import { shallowRef, ref, defineAsyncComponent } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useComponent } from '@/hooks/component'
import { validate } from '@/constants/regex'
import { getGZBSCOutTypeList } from '@/constants/bonded'
import { GZBSCOrderType } from '@/constants/bonded'
import { useBscInAndOutWareHouseApply } from '@/business/bonded'
import AppDrawer from '@pc/components/base/drawer/index.vue'
import AppTable from '@pc/components/base/table/index.vue'

const componentMap = new Map<string, unknown>([
    ['detailEdit', defineAsyncComponent(() => import('../../../components/detail-edit/index.vue'))],
    ['subDetailEdit', defineAsyncComponent(() => import('./subdetail-edit/index.vue'))],
])

const { componentId, openComponent, closeComponent } = useComponent()
const { loading, formData, formSubmit } = useBscInAndOutWareHouseApply(GZBSCOrderType.Out)
const show = shallowRef(true)
const refresh = shallowRef(false)
const formRef = shallowRef<FormInstance>()
const orderDetailList = ref<Ermcp.BScinOutOrderDetailRsp[]>([]) // 明细列表
const orderDetailAttList = ref<Ermcp.BScOutOrderDetailattRsp[]>([]) // 附表列表
const selectedRow = shallowRef<Ermcp.BScinOutOrderDetailRsp | Ermcp.BScOutOrderDetailattRsp>() // 当前选择的商品信息

const columns1: Ermcp.TableColumn[] = [
    { prop: 'goodsname', label: '商品名称' },
    { prop: 'goodsspec', label: '规格' },
    { prop: 'rawdetail', label: '成品对应原料明细', width: 160 },
    { prop: 'backagenum', label: '件数' },
    { prop: 'netweightct', label: '净重(克拉)' },
    { prop: 'netweightgm', label: '净重(克)' },
    { prop: 'bagweightgm', label: '连袋重(克)' },
    { prop: 'prepricegm', label: '单价(克)' },
    { prop: 'totalprice', label: '总价' },
    { prop: 'currencydes', label: '币种' },
    { prop: 'customsvalue', label: '报关总值' },
    { prop: 'origincountry', label: '原产国' },
    { prop: 'remark', label: '备注' },
    { prop: 'operate', label: '操作', width: 160, fixed: 'right' }
]

const columns2: Ermcp.TableColumn[] = [
    { prop: 'goodsname', label: '商品名称' },
    { prop: 'customsno', label: '进口单号' },
    { prop: 'jckdate', label: '进口日期' },
    { prop: 'netweightct', label: '净重(克拉)' },
    { prop: 'curnetweightct', label: '本次扣减量(克拉)', width: 160 },
    { prop: 'remainnetweightct', label: '结余量(克拉)' },
    { prop: 'customsvalue', label: '报关总值' },
    { prop: 'curcustomsvalue', label: '本次扣减货值' },
    { prop: 'remaincustomsvalue', label: '结余货值' },
    { prop: 'operate', label: '操作', width: 160, fixed: 'right' }
]

const formRules: FormRules = {
    UserName: [{
        required: true,
        message: '请输入发货方'
    }],
    UserAddress: [{
        required: true,
        message: '请输入发货地址'
    }],
    ContactName: [{
        required: true,
        message: '请输入联系人'
    }],
    ContactNum: [{
        required: true,
        trigger: 'blur',
        validator: (rule, value, callback) => {
            if (value) {
                const message = validate(value, 'phone')
                message ? callback(new Error(message)) : callback()
            } else {
                callback(new Error('请输入联系电话'))
            }
        }
    }],
    OutType: [{
        required: true,
        message: '请选择出仓类型'
    }],
}

// 打开商品编辑
const openEdit = (name: string, row?: Ermcp.BScinOutOrderDetailRsp | Ermcp.BScOutOrderDetailattRsp) => {
    selectedRow.value = row
    openComponent(name)
}

// 删除商品记录
const deleteRecord = (index: number) => {
    orderDetailList.value.splice(index, 1)
    orderDetailList.value.forEach((e, i) => e.detailid = (i + 1).toString()) // 重置序列
}

// 删除附表记录
const deleteSubRecord = (index: number) => {
    orderDetailAttList.value.splice(index, 1)
    orderDetailAttList.value.forEach((e, i) => e.detailattid = (i + 1).toString()) // 重置序列
}

// 更新商品数据
const onUpdate = (item: Ermcp.BScinOutOrderDetailRsp | Ermcp.BScOutOrderDetailattRsp) => {
    if ('detailid' in item) {
        const list = orderDetailList.value
        const index = list.findIndex((e) => e.detailid === item.detailid)
        if (index > -1) {
            list[index] = item
        } else {
            const n = list.length
            item.detailid = (n + 1).toString()
            list[n] = item
        }
    }
    if ('detailattid' in item) {
        const list = orderDetailAttList.value
        const index = list.findIndex((e) => e.detailattid === item.detailattid)
        if (index > -1) {
            list[index] = item
        } else {
            const n = list.length
            item.detailattid = (n + 1).toString()
            list[n] = item
        }
    }
}

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

const onSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            formData.BSCGoodsListDetails = orderDetailList.value.map((e) => ({
                GoodsID: e.goodsid, // 商品ID,必填
                GoodsSpec: e.goodsspec, // 规格,必填
                RawDetail: e.rawdetail, // 原料明细,必填
                BackageNum: e.backagenum, // 件数,必填
                NetWeightCT: e.netweightct, // 净重(克拉),必填
                NetWeightGM: e.netweightgm, // 净重(克),必填
                BagWeightGM: e.bagweightgm, // 连袋重(克),必填
                PrePriceGM: e.prepricegm, // 单价(克),必填
                TotalPrice: e.totalprice, // 总价,必填
                CurrencyDes: e.currencydes, // 币种,必填
                CustomsValue: e.customsvalue, // 报关总值,必填
                OriginCountry: e.origincountry, // 原产国,必填
                Remark: e.remark, // 备注,选填
            }))
            formData.BSCOutWareHouseSchedules = orderDetailAttList.value.map((e) => ({
                GoodsID: e.goodsid, // 商品ID,必填
                CustomsNo: e.customsno, // 报关单号,必填
                JCKDate: e.jckdate, // 进口日期,必填
                CurNetWeightCT: e.curnetweightct, // 本次扣减量(克拉),必填
            }))
            formSubmit().then(() => {
                ElMessage.success('提交成功')
                onCancel(true)
            }).catch((err) => {
                ElMessage.error('提交失败：' + err)
            })
        }
    })
}
</script>