<!-- 交易服务-出境检测-提交申请/修改 -->
<template>
    <app-drawer class="customs-exit-edit" title="出境申请" :width="960" v-model:show="show" :loading="loading"
        :refresh="refresh">
        <div class="customs-exit-edit__info">
            <p>*若货物由广州钻石交易中心经快递发送，快递员揽件时即视为委托方已收货，广州钻石交易中心不承担后续货物安全责任。</p>
            <p>本表将作为委托方委托广州钻石交易中心办理出境检测业务申请使用，敬请务必如实填写公司信息、货物资料，并盖章确认。广州钻石交易中心根据此表确认信息，作为接受委托办理该批货物出境检测业务的凭证，仅对数量负责。</p>
        </div>
        <el-form ref="formRef" class="el-form--horizontal" label-width="170px" :model="formData" :rules="formRules">
            <el-form-item :class="formData.GZCJAccountType === 2 ? 'el-form-item--row' : ''" label="用户类型"
                prop="GZCJAccountType">
                <el-radio-group v-model="formData.GZCJAccountType" @change="clearList">
                    <el-radio :label="item.value" v-for="(item, index) in gzcjAccountTypeList" :key="index">
                        {{ item.label }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="送检账户" prop="GZCJAccount" v-if="formData.GZCJAccountType === 1">
                <el-input placeholder="请输入" v-model="formData.GZCJAccount" />
            </el-form-item>
            <el-form-item label="公司名称(中文)" prop="CompanyNameCN">
                <el-input placeholder="请输入" v-model="formData.CompanyNameCN" />
            </el-form-item>
            <el-form-item label="公司名称(英文)" prop="CompanyNameEn">
                <el-input placeholder="请输入" v-model="formData.CompanyNameEn" />
            </el-form-item>
            <el-form-item class="el-form-item--row" label="地址(中文)" prop="AddressCN">
                <el-input placeholder="请输入" v-model="formData.AddressCN" />
            </el-form-item>
            <el-form-item class="el-form-item--row" label="地址(英文)" prop="AddressEN">
                <el-input placeholder="请输入" v-model="formData.AddressEN" />
            </el-form-item>
            <el-form-item label="联系人姓名" prop="ContactName">
                <el-input placeholder="请输入" v-model="formData.ContactName" />
            </el-form-item>
            <el-form-item label="联系人职位" prop="ContactPosition">
                <el-input placeholder="请输入" v-model="formData.ContactPosition" />
            </el-form-item>
            <el-form-item label="联系人电话" prop="ContactPhoneNo">
                <el-input placeholder="请输入" v-model="formData.ContactPhoneNo" />
            </el-form-item>
            <el-form-item label="邮箱" prop="Email">
                <el-input placeholder="请输入" v-model="formData.Email" />
            </el-form-item>
            <el-form-item label="货物品类" prop="GZCJCategoryType">
                <el-select v-model="formData.GZCJCategoryType">
                    <el-option :label="item.label" :value="item.value" v-for="(item, index) in getGZCJCategoryTypeList()"
                        :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item label="成品钻石加工国" prop="ProcessingCountry">
                <el-input placeholder="请输入" v-model="formData.ProcessingCountry" />
            </el-form-item>
            <el-form-item label="天然钻石毛坯原产地" prop="ZSOrigin">
                <el-input placeholder="请输入" v-model="formData.ZSOrigin" />
            </el-form-item>
            <el-form-item label="完成检测后收货方式" prop="GZCJDeliveryType">
                <el-select v-model="formData.GZCJDeliveryType">
                    <el-option :label="item.label" :value="item.value" v-for="(item, index) in getGZCJDeliveryTypeList()"
                        :key="index" />
                </el-select>
            </el-form-item>
        </el-form>
        <div class="customs-exit-edit__table"
            v-if="formData.GZCJAccountType === 2 ? !!formData.GZCJCategoryType : !!formData.GZCJAccountType">
            <app-table :data="formData.GZCJCategoryDetails" :columns="columns" :max-height="400" border>
                <template #toolbar>
                    <el-upload accept=".xlsx,.xls" :show-file-list="false" :auto-upload="false" @change="handleExcel">
                        <el-button size="small">导入</el-button>
                    </el-upload>
                    <el-button size="small" @click="openEdit()">新增</el-button>
                    <el-button size="small" @click="clearList()">清空</el-button>
                </template>
                <!-- 形状 -->
                <template #GZCJShapeType="{ value }">
                    {{ getGZCJShapeTypeName(value) }}
                </template>
                <!-- 刻印服务(证书号/ 其他/ 无) -->
                <template #GZCJMarkType="{ value }">
                    {{ getGZCJMarkTypeName(value) }}
                </template>
                <!-- 是否披露处理 -->
                <template #GZCJPublishType="{ value }">
                    {{ getGZCJPublishTypeName(value) }}
                </template>
                <!-- 服务类别 -->
                <template #GZCJServiceType="{ value }">
                    {{ getGZCJServiceTypeName(value) }}
                </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(true)">保存草稿</el-button>
            <el-button type="primary" @click="onSubmit()">提交申请</el-button>
        </template>
        <component :is="componentMap.get(componentId)" v-bind="{ formData, detail }" @update="onUpdate"
            @closed="closeComponent" v-if="componentId" />
    </app-drawer>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, defineAsyncComponent, PropType } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules, UploadFile } from 'element-plus'
import { read, utils } from 'xlsx'
import { useComponent } from '@/hooks/component'
import { validateRules } from '@/constants/regex'
import { enumStore } from '@/stores'
import { getGZCJAccountTypeList, getGZCJCategoryTypeList, getGZCJDeliveryTypeList, getGZCJShapeTypeName, getGZCJPublishTypeName, getGZCJMarkTypeName, getGZCJServiceTypeName } from '@/constants/customs'
import { useCJJCOrderApply } from '@/business/customs/exit'
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.GZCJJCOrderRsp>
    }
})

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

const { componentId, openComponent, closeComponent } = useComponent()
const { loading, formData, formSubmit } = useCJJCOrderApply(props.selectedRow)
const show = ref(true)
const refresh = ref(false)
const formRef = ref<FormInstance>()
const gzcjAccountTypeList = getGZCJAccountTypeList()
const detail = ref<Proto.GZCJCategoryDetail>() // 当前选择的货物明细

const columns = computed<Ermcp.TableColumn[]>(() => {
    switch (formData.GZCJAccountType) {
        case 1: {
            return [
                { prop: 'GZNo', label: '货物编号' },
                { prop: 'GZCJShapeType', label: '形状', width: 200 },
                { prop: 'Weight', label: '重量ct' },
                { prop: 'Amount', label: '参考货值USD' },
                { prop: 'ColorInfo', label: '彩钻信息' },
                { prop: 'Remark', label: '其他' },
                { prop: 'operate', label: '操作', width: 160, fixed: 'right' }
            ]
        }
        case 2: {
            return [
                { prop: 'GZNo', label: '货物编号' },
                { prop: 'GZCJShapeType', label: '形状', width: 200 },
                { prop: 'Weight', label: '重量ct' },
                { prop: 'Amount', label: '参考货值USD' },
                { prop: 'GZCJMarkType', label: '刻印服务(证书号/ 其他/ 无)', width: 220 },
                { prop: 'GZCJPublishType', label: '是否披露处理' },
                { prop: 'GZCJServiceType', label: '服务类别' },
                { prop: 'OriginCertNo', label: '原证书号' },
                { prop: 'ColorInfo', label: '彩钻信息' },
                { prop: 'Remark', label: '其他' },
                { prop: 'operate', label: '操作', width: 160, fixed: 'right' }
            ]
        }
    }
    return []
})

const formRules: FormRules = {
    GZCJAccountType: [{
        required: true,
        message: '请选择用户类型'
    }],
    GZCJAccount: [{
        required: true,
        message: '请输入送检账户'
    }],
    CompanyNameCN: [{
        required: true,
        message: '请输入公司名称(中文)'
    }],
    CompanyNameEn: [{
        required: true,
        message: '请输入公司名称(英文)'
    }],
    AddressCN: [{
        required: true,
        message: '请输入地址(中文)'
    }],
    AddressEN: [{
        required: true,
        message: '请输入地址(英文)'
    }],
    ContactName: [{
        required: true,
        message: '请输入联系人姓名'
    }],
    ContactPosition: [{
        required: true,
        message: '请输入联系人职位'
    }],
    ContactPhoneNo: [{
        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('请输入联系人电话'))
            }
        }
    }],
    Email: [{
        required: true,
        trigger: 'blur',
        validator: (rule, value, callback) => {
            if (value) {
                if (validateRules.email.validate(value)) {
                    callback()
                } else {
                    callback(new Error(validateRules.email.message))
                }
            } else {
                callback(new Error('请输入邮箱'))
            }
        }
    }],
    GZCJCategoryType: [{
        required: true,
        message: '请选择货物品类'
    }],
    ProcessingCountry: [{
        required: true,
        message: '请输入成品钻石加工国'
    }],
    ZSOrigin: [{
        required: true,
        message: '请输入天然钻石毛坯原产地'
    }],
    GZCJDeliveryType: [{
        required: true,
        message: '请选择完成检测后收货方式'
    }],
}

// 打开编辑
const openEdit = (row?: Proto.GZCJCategoryDetail) => {
    detail.value = row
    openComponent('detailEdit')
}

// 清空列表数据
const clearList = () => {
    formData.GZCJCategoryDetails = []
}

// 删除列表数据
const deleteRecord = (index: number) => {
    formData.GZCJCategoryDetails?.splice(index, 1)
    formData.GZCJCategoryDetails?.forEach((e, i) => e.OrderIndex = i + 1) // 重置序列
}

// 处理导入的excel表格
const handleExcel = (uploadFile: UploadFile) => {
    const fileReader = new FileReader()
    fileReader.readAsBinaryString(uploadFile.raw as Blob)
    fileReader.onload = (ev) => {
        const data = ev.target?.result
        if (data) {
            const { getEnumTypeList } = enumStore.actions
            const shapeTypeList = getEnumTypeList('GZCJShapeType')
            const markTypeList = getEnumTypeList('GZCJMarkType')
            const publishType = getEnumTypeList('GZCJPublishType')
            const serviceType = getEnumTypeList('GZCJServiceType')

            const workbook = read(data, { type: 'binary' })
            const wsname = workbook.SheetNames[0]
            const list = utils.sheet_to_json(workbook.Sheets[wsname], { header: ['Index', 'GZNo', 'GZCJShapeType', 'Weight', 'Amount', 'GZCJMarkType', 'GZCJPublishType', 'GZCJServiceType', 'OriginCertNo', 'ColorInfo', 'Remark'] })

            clearList()
            list.forEach((row, index) => {
                if (index > 0) {
                    const item: Proto.GZCJCategoryDetail = {
                        OrderIndex: 0, // 顺序,必填
                        GZNo: '', // 货物编号,必填
                        GZCJShapeType: 0, // 形状,必填
                        Weight: 0, // 重量(CT),3位小数,必填
                        Amount: 0, // 参考货值(USD),2位小数,必填
                        ColorInfo: '', // 彩钻信息
                        Remark: '', // 备注
                        GZCJMarkType: 0,// 刻印服务,必填
                        GZCJPublishType: 0,// 是否披露处理,必填
                        GZCJServiceType: 0, // 服务类别,必填
                        OriginCertNo: '', // 原证书号
                    }
                    Object.entries(row as { [key: string]: unknown }).forEach(([key, value], index) => {
                        if (index > 0 && Reflect.has(item, key)) {
                            let enumType
                            switch (key) {
                                case 'GZCJShapeType': {
                                    enumType = shapeTypeList.find((e) => e.label === value)
                                    break
                                }
                                case 'GZCJMarkType': {
                                    enumType = markTypeList.find((e) => e.label === value)
                                    break
                                }
                                case 'GZCJPublishType': {
                                    enumType = publishType.find((e) => e.label === value)
                                    break
                                }
                                case 'GZCJServiceType': {
                                    enumType = serviceType.find((e) => e.label === value)
                                    break
                                }
                                default: {
                                    enumType = { value }
                                }
                            }
                            Object.defineProperty(item, key, { value: enumType?.value ?? 0 })
                        }
                    })
                    formData.GZCJCategoryDetails?.push(item)
                }
            })
        }
    }
}

// 更新列表数据
const onUpdate = (item: Proto.GZCJCategoryDetail) => {
    const { GZCJCategoryDetails = [] } = formData
    const index = GZCJCategoryDetails.findIndex((e) => e.OrderIndex === item.OrderIndex)

    if (index > -1) {
        GZCJCategoryDetails[index] = item
    } else {
        item.OrderIndex = GZCJCategoryDetails.length + 1
        GZCJCategoryDetails.push(item)
    }
}

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

const onSubmit = (draft = false) => {
    formRef.value?.validate((valid) => {
        if (valid) {
            if (draft) {
                formData.ApplyType = props.selectedRow?.orderidstr ? 2 : 1
            } else {
                formData.ApplyType = 3
            }
            if (formData.GZCJCategoryDetails?.length) {
                formSubmit().then(() => {
                    ElMessage.success('提交成功')
                    onCancel(true)
                }).catch((err) => {
                    ElMessage.error(err)
                })
            } else {
                ElMessage.warning('请添加批次')
            }
        }
    })
}

onMounted(() => {
    const { gzcjaccounttype = gzcjAccountTypeList[0]?.value } = props.selectedRow ?? {}
    formData.GZCJAccountType = gzcjaccounttype
})
</script>

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