<!-- 集采交易-我的集采-集采申请 -->
<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="140px" :model="formData" :rules="formRules">
            <el-form-item label="商品名称" prop="WRStandardName">
                <el-input placeholder="请输入" v-model="formData.WRStandardName" />
            </el-form-item>
            <el-form-item label="钻石类型" prop="YSZSCategory">
                <el-radio-group v-model="formData.YSZSCategory">
                    <el-radio :label="item.value" v-for="(item, index) in getYSZSCategoryList()" :key="index">
                        {{ item.label }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="集采数量(克拉)" prop="PresaleQty">
                <el-input-number placeholder="请输入" :min="0" :max="maxValue" :precision="2" v-model="formData.PresaleQty" />
            </el-form-item>
            <el-form-item label="履约方式" prop="PerformanceTemplateID">
                <component :is="PerformanceTemplate" v-model="formData.PerformanceTemplateID" />
            </el-form-item>
            <el-form-item label="最小采购单位" prop="MinBuyQty">
                <el-input placeholder="请添加采集价格" :value="minQty" disabled />
            </el-form-item>
            <el-form-item label="最低成团量" prop="MinSuccessQty">
                <el-input-number placeholder="请输入" :min="0" :max="maxValue" :precision="2"
                    v-model="formData.MinSuccessQty" />
            </el-form-item>
            <el-form-item label="最大采购单位" prop="MaxBuyQty">
                <el-input-number placeholder="请输入" :min="0" :max="maxValue" :precision="2" v-model="formData.MaxBuyQty" />
            </el-form-item>
            <el-form-item label="采购保证金(%)" prop="BuyMarginValue">
                <el-input-number type="number" placeholder="请输入" :min="0" :max="1000" :precision="2"
                    v-model="formData.BuyMarginValue" />
            </el-form-item>
            <el-form-item label="集采日期" prop="PreDate">
                <el-date-picker type="daterange" placeholder="请选择" range-separator="至" start-placeholder="开始"
                    end-placeholder="结束" v-model="datePickerValue" />
            </el-form-item>
            <el-form-item class="el-form-item--row" label="集采价格" prop="GZCenterPurchasePriceLists">
                <app-table :data="formData.GZCenterPurchasePriceLists" :columns="columns" :max-height="400" border
                    showToolbar>
                    <template #toolbar>
                        <el-button-group>
                            <el-button size="small" @click="openEdit()">新增</el-button>
                            <el-button size="small" @click="formData.GZCenterPurchasePriceLists = []">清空</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>
            </el-form-item>
        </el-form>
        <h3 class="g-details__title">钻石参考信息</h3>
        <el-form class="el-form--horizontal" label-width="140px" :model="formData" :rules="formRules">
            <el-form-item label="形状" prop="ZSShapeTypeStr" v-if="formData.YSZSCategory === YSZSCategory.Diamonds">
                <el-input placeholder="请输入" v-model="formData.ZSShapeTypeStr" />
            </el-form-item>
            <el-form-item label="颜色" prop="ZSColorTypeStr">
                <el-input placeholder="请输入" v-model="formData.ZSColorTypeStr" />
            </el-form-item>
            <el-form-item label="尺寸" prop="SizeStr">
                <el-input placeholder="请输入" v-model="formData.SizeStr" />
            </el-form-item>
            <el-form-item label="抛光" prop="ZSPolishTypeStr" v-if="formData.YSZSCategory === YSZSCategory.Diamonds">
                <el-input placeholder="请输入" v-model="formData.ZSPolishTypeStr" />
            </el-form-item>
            <el-form-item label="净度" prop="ZSClarityTypeStr">
                <el-input placeholder="请输入" v-model="formData.ZSClarityTypeStr" />
            </el-form-item>
            <template v-if="formData.YSZSCategory === YSZSCategory.Diamonds">
                <el-form-item label="对称" prop="ZSSymmetryTypeStr">
                    <el-input placeholder="请输入" v-model="formData.ZSSymmetryTypeStr" />
                </el-form-item>
                <el-form-item label="切工" prop="ZSCutTypeStr">
                    <el-input placeholder="请输入" v-model="formData.ZSCutTypeStr" />
                </el-form-item>
                <el-form-item label="荧光" prop="ZSFluorescenceTypeStr">
                    <el-input placeholder="请输入" v-model="formData.ZSFluorescenceTypeStr" />
                </el-form-item>
            </template>
            <template v-if="formData.YSZSCategory === YSZSCategory.Rough">
                <el-form-item label="成品率" prop="YieldRate">
                    <el-input placeholder="请输入" v-model="formData.YieldRate" />
                </el-form-item>
                <el-form-item label="数量描述" prop="QtyDesc">
                    <el-input placeholder="请输入" v-model="formData.QtyDesc" />
                </el-form-item>
                <el-form-item label="重量描述" prop="WeightDesc">
                    <el-input placeholder="请输入" v-model="formData.WeightDesc" />
                </el-form-item>
                <el-form-item label="生产方式" prop="YSProductionMode">
                    <el-select v-model="formData.YSProductionMode">
                        <el-option :label="item.label" :value="item.value"
                            v-for="(item, index) in getYSProductionModeList()" :key="index" />
                    </el-select>
                </el-form-item>
            </template>
            <el-form-item class="el-form-item--row" label="图片" prop="PictureUrls">
                <app-upload :file-types="['image']" :limit="5" type-message="请选择正确的图片类型" @change="onUploadChange" />
            </el-form-item>
            <el-form-item class="el-form-item--row" label="备注" prop="Remark">
                <el-input type="textarea" maxlength="120" v-model="formData.Remark" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="onCancel(false)" plain>取消</el-button>
            <el-button type="primary" @click="onSubmit">提交</el-button>
        </template>
        <component :is="PriceEdit" v-bind="{ selectedRow }" @update="onUpdate" @closed="showEdit = false" v-if="showEdit" />
    </app-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, defineAsyncComponent, computed, PropType, onMounted } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { formatDate } from '@/filters'
import { regular } from '@/constants/regex'
import { maxValue } from '@/constants/common'
import { getYSProductionModeList, getYSZSCategoryList, YSZSCategory } from '@/constants/presale'
import { gzCenterPurchaseApply, queryPresaleorderapplyprice } from '@/services/api/presale'
import AppDrawer from '@pc/components/base/drawer/index.vue'
import AppUpload from '@pc/components/base/upload/index.vue'
import AppTable from '@pc/components/base/table/index.vue'

const props = defineProps({
    selectedRow: {
        type: Object as PropType<Ermcp.GZWrPreSaleApplyRsp>
    }
})

// 履约模板
const PerformanceTemplate = defineAsyncComponent(() => import('@pc/components/modules/performance/index.vue'))
// 价格编辑
const PriceEdit = defineAsyncComponent(() => import('./price-edit.vue'))

const formRef = ref<FormInstance>()
const show = ref(true)
const refresh = ref(false)
const loading = ref(false)
const showEdit = ref(false)
const datePickerValue = ref<string[]>([]) // 选中的日期
const selectedRow = ref<Proto.GZCenterPurchasePrice>() // 当前选择的价格明细

const formData = reactive<Partial<Proto.GZCenterPurchaseApplyReq>>({
    BuyMarginAlgorithm: 1, // 买方保证金方式,必填
    GZCenterPurchasePriceLists: [],
})

// 最小采购单位
const minQty = computed(() => formData.GZCenterPurchasePriceLists![0]?.Qty)

const columns: Ermcp.TableColumn[] = [
    { prop: 'StepIndex', label: '序号' },
    { prop: 'Qty', label: '数量' },
    { prop: 'Price', label: '价格(元/克拉)' },
    { prop: 'operate', label: '操作', width: 160, fixed: 'right' }
]

const formRules: FormRules = {
    WRStandardName: [{
        required: true,
        message: '请输入商品名称'
    }],
    YSZSCategory: [{
        required: true,
        message: '请选择钻石分类'
    }],
    PerformanceTemplateID: [{
        required: true,
        message: '请选择履约方式'
    }],
    PresaleQty: [{
        required: true,
        message: '请输入集采数量',
        pattern: regular.positive.reg
    }],
    MinSuccessQty: [{
        required: true,
        message: '请输入最低成团量',
        pattern: regular.positive.reg
    }],
    MaxBuyQty: [{
        required: true,
        message: '请输入最大采购单位',
        pattern: regular.positive.reg
    }],
    BuyMarginValue: [{
        required: true,
        message: '请输入采购保证金比例',
        pattern: regular.positive.reg
    }],
    PreDate: [{
        required: true,
        validator: (rule, value, callback) => {
            if (datePickerValue.value && datePickerValue.value.length === 2) {
                callback()
            } else {
                callback(new Error('请选择预售日期'))
            }
        }
    }],
    GZCenterPurchasePriceLists: [{
        required: true,
        validator: (rule, value, callback) => {
            if (formData.GZCenterPurchasePriceLists?.length) {
                callback()
            } else {
                callback(new Error('请添加集采价格'))
            }
        }
    }],
}

// 打开价格编辑
const openEdit = (row?: Proto.GZCenterPurchasePrice) => {
    selectedRow.value = row
    showEdit.value = true
}

// 删除价格记录
const deleteRecord = (index: number) => {
    formData.GZCenterPurchasePriceLists?.splice(index, 1)
    formData.GZCenterPurchasePriceLists?.forEach((e, i) => e.StepIndex = i + 1) // 重置序列
}

// 更新价格数据
const onUpdate = (item: Proto.GZCenterPurchasePrice) => {
    const list = formData.GZCenterPurchasePriceLists ?? []
    const findQty = list.findIndex((e) => e.Qty === item.Qty)
    if (findQty > -1) {
        list[findQty] = item
    } else {
        const findIndex = list.findIndex((e) => e.StepIndex === item.StepIndex)
        if (findIndex > -1) {
            list[findIndex] = item
        } else {
            const n = list.length
            item.StepIndex = n + 1
            list[n] = item
        }
    }
    // 重新排序
    formData.GZCenterPurchasePriceLists = formData.GZCenterPurchasePriceLists?.sort(((a, b) => a.Qty - b.Qty))
    formData.GZCenterPurchasePriceLists?.forEach((e, i) => e.StepIndex = i + 1)
    formRef.value?.validateField('GZCenterPurchasePriceLists')
}

const onUploadChange = (files: { filePath: string }[]) => {
    formData.PictureUrls = files.map((e) => e.filePath).join(',')
}

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

const onSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            const [startDate, endDate] = datePickerValue.value
            formData.StartDate = formatDate(startDate, 'YYYY-MM-DD')
            formData.EndDate = formatDate(endDate, 'YYYY-MM-DD')
            formData.MinBuyQty = minQty.value

            loading.value = true
            gzCenterPurchaseApply({
                ...formData,
                BuyMarginValue: (formData.BuyMarginValue ?? 0) / 100
            }).then(() => {
                ElMessage.success('提交成功')
                onCancel(true)
            }).catch((err) => {
                ElMessage.error('提交失败：' + err)
            }).finally(() => {
                loading.value = false
            })
        }
    })
}

onMounted(() => {
    if (props.selectedRow) {
        ({
            wrstandardname: formData.WRStandardName,
            yszscategory: formData.YSZSCategory,
            presaleqty: formData.PresaleQty,
            performancetemplateid: formData.PerformanceTemplateID,
            minbuyqty: formData.MinBuyQty,
            minsuccessqty: formData.MinSuccessQty,
            maxbuyqty: formData.MaxBuyQty,
            buymarginvalue: formData.BuyMarginValue,
            zsshapetypestr: formData.ZSShapeTypeStr,
            zscolortypestr: formData.ZSColorTypeStr,
            sizestr: formData.SizeStr,
            zsclaritytypestr: formData.ZSClarityTypeStr,
            zspolishtypestr: formData.ZSPolishTypeStr,
            zssymmetrytypestr: formData.ZSSymmetryTypeStr,
            zscuttypestr: formData.ZSCutTypeStr,
            zsfluorescencetypestr: formData.ZSFluorescenceTypeStr,
            yieldrate: formData.YieldRate,
            qtydesc: formData.QtyDesc,
            weightdesc: formData.WeightDesc,
            remark: formData.Remark,
        } = props.selectedRow)

        formData.YSProductionMode = props.selectedRow.ysproductionmode || undefined
        datePickerValue.value = [props.selectedRow.startdate, props.selectedRow.enddate]

        queryPresaleorderapplyprice({
            applyid: props.selectedRow.presaleapplyid
        }).then((res) => {
            formData.GZCenterPurchasePriceLists = res.data.map((e) => ({
                StepIndex: e.stepindex,
                Qty: e.qty,
                Price: e.price,
            }))
        })
    }
})
</script>