<!-- 保税仓业务-进仓管理-提交申请 -->
<template>
    <app-drawer class="bonded-inbound-apply" title="提交申请" v-model:show="show" :width="960" :loading="loading"
        :refresh="refresh">
        <h3 class="bonded-inbound-apply__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>
        <div class="bonded-inbound-apply__table">
            <app-table :data="orderDetailList" :columns="columns" :max-height="400" border>
                <template #header>
                    <h3 class="bonded-inbound-apply__title">商品信息</h3>
                </template>
                <template #toolbar>
                    <el-button-group>
                        <el-button size="small" @click="openEdit()">新增</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(row)">修改</el-button>
                        <el-button @click="deleteRecord(index)">删除</el-button>
                    </el-button-group>
                </template>
            </app-table>
        </div>
        <template #footer>
            <el-button @click="onCancel(false)" plain>取消</el-button>
            <el-button type="primary" @click="onSubmit">提交</el-button>
        </template>
        <component :is="DetailEdit" v-bind="{ selectedRow }" @update="onUpdate" @closed="showEdit = false"
            v-if="showEdit" />
    </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 { validateRules } from '@/constants/regex'
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 DetailEdit = defineAsyncComponent(() => import('../../../components/detail-edit/index.vue'))

const { loading, formData, formSubmit } = useBscInAndOutWareHouseApply(GZBSCOrderType.In)
const show = shallowRef(true)
const refresh = shallowRef(false)
const formRef = shallowRef<FormInstance>()
const showEdit = shallowRef(false)
const orderDetailList = ref<Ermcp.BScinOutOrderDetailRsp[]>([]) // 明细列表
const selectedRow = shallowRef<Ermcp.BScinOutOrderDetailRsp>() // 当前选择的商品明细

const columns: 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 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) {
                if (validateRules.phone.validate(value)) {
                    callback()
                } else {
                    callback(new Error(validateRules.phone.message))
                }
            } else {
                callback(new Error('请输入联系电话'))
            }
        }
    }],
}

// 打开商品编辑
const openEdit = (row?: Ermcp.BScinOutOrderDetailRsp) => {
    selectedRow.value = row
    showEdit.value = true
}

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

// 更新商品数据
const onUpdate = (item: Ermcp.BScinOutOrderDetailRsp) => {
    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
    }
}

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, // 备注,选填
            }))
            formSubmit().then(() => {
                ElMessage.success('提交成功')
                onCancel(true)
            }).catch((err) => {
                ElMessage.error('提交失败：' + err)
            })
        }
    })
}
</script>

<style lang="less">
@import './index.less';
</style>