<!-- 预售大厅-我的预售-预售申请 -->
<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="150px" :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="PerformanceTemplateID">
                <component :is="PerformanceTemplate" v-model="formData.PerformanceTemplateID" />
            </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="UnitPrice">
                <el-input-number placeholder="请输入" :min="0" :max="maxValue" :precision="2" v-model="formData.UnitPrice" />
            </el-form-item>
            <el-form-item label="最小采购单位" prop="MinBuyQty">
                <el-input-number placeholder="请输入" :min="0" :max="maxValue" :precision="2" v-model="formData.MinBuyQty" />
            </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>
        <h3 class="g-details__title">钻石参考信息</h3>
        <el-form class="el-form--horizontal" label-width="140px" :model="formData" :rules="formRules">
            <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="ZSClarityTypeStr">
                <el-input placeholder="请输入" v-model="formData.ZSClarityTypeStr" />
            </el-form-item>
            <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>
            <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>
    </app-drawer>
</template>

<script lang="ts" setup>
import { shallowRef, reactive, defineAsyncComponent, 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, YSZSCategory } from '@/constants/presale'
import { gzPresaleApply } from '@/services/api/presale'
import AppDrawer from '@pc/components/base/drawer/index.vue'
import AppUpload from '@pc/components/base/upload/index.vue'

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

// 履约模板
const PerformanceTemplate = defineAsyncComponent(() => import('@pc/components/modules/performance/index.vue'))

const formRef = shallowRef<FormInstance>()
const show = shallowRef(true)
const refresh = shallowRef(false)
const loading = shallowRef(false)
const datePickerValue = shallowRef<string[]>([]) // 选中的日期

const formData = reactive<Partial<Proto.GZPresaleApplyReq>>({
    YSZSCategory: YSZSCategory.Rough,
    BuyMarginAlgorithm: 1, // 买方保证金方式,必填
})

const formRules: FormRules = {
    WRStandardName: [{
        required: true,
        message: '请输入商品名称'
    }],
    PerformanceTemplateID: [{
        required: true,
        message: '请选择履约方式'
    }],
    PresaleQty: [{
        required: true,
        message: '请输入预售总量',
        pattern: regular.positive.reg
    }],
    UnitPrice: [{
        required: true,
        message: '请输入预售价格',
        pattern: regular.positive.reg
    }],
    MinBuyQty: [{
        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('请选择预售日期'))
            }
        }
    }],
}

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')

            loading.value = true
            gzPresaleApply({
                ...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,
            performancetemplateid: formData.PerformanceTemplateID,
            presaleqty: formData.PresaleQty,
            unitprice: formData.UnitPrice,
            minbuyqty: formData.MinBuyQty,
            minsuccessqty: formData.MinSuccessQty,
            maxbuyqty: formData.MaxBuyQty,
            buymarginvalue: formData.BuyMarginValue,
            zscolortypestr: formData.ZSColorTypeStr,
            sizestr: formData.SizeStr,
            zsclaritytypestr: formData.ZSClarityTypeStr,
            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]
    }
})
</script>