<template>
    <vxe-modal v-model="dialogVisible" :title="title" show-zoom resize show-footer destroy-on-close transfer @hide="close" :width="width" :z-index="1002">
        <template #default>
            <div class="over-auto" style="height: 80vh;">
                <div class="pd-16 bg-#f7f7f7 mb-16">
                    <div class="mb-10 d-flex">
                        <div class="flex1 ov-hd">
                            <el-tag class="mr-8" type="success" effect="dark">求购</el-tag>
                            <span class="f-s-16 f-w-5 c-333">{{ info?.name }}</span>
                            <span class="f-s-12 c-333">（{{ selectDictLabel(dm_medicine_find_type, info?.type) }}）</span>
                        </div>
                        <div class="c-999 f-s-14">{{ formatDateRelative(info?.createTime) }}发布</div>
                    </div>
                    <div>具体需求：{{ info?.needsDetail }}</div>
                </div>
                <div class="info-title f-s-16 c-333 f-w-5 mb-10">供应信息</div>
                <el-form class="ov-hd" ref="formRef" :model="form" :rules="rules" label-width="auto" label-position="top">
                    <div class="f-s-14 c-333 f-w-5 mb-10">报价信息</div>
                    <el-form-item label="价格" prop="price">
                        <div class="flex1 ov-hd">
                            <el-input class="mr-20" style="width: 200px;" type="number" v-model="form.price" placeholder="请输入含税单价" clearable>
                                <template #prefix>¥</template>
                                <template #suffix>/{{ info?.unit }}</template>
                            </el-input>
                            <el-checkbox v-model="form.priceType" true-value="1" false-value="0">具体再议</el-checkbox>
                        </div>
                    </el-form-item>
                    <el-form-item label="价格补充说明" prop="remark">
                        <el-input type="textarea" :rows="3" maxlength="300" show-word-limit v-model="form.remark" placeholder="可对价格有效期或其他需要特别说明的价格等事项进行补充~" clearable />
                    </el-form-item>
                    <div class="h-1 bg-#f7f7f7 mg2-10-0"></div>
                    <el-form-item label="原料图" prop="images">
                        <imageUpload v-model="form.images" :limit="50" isString :isShowTip="false"></imageUpload>
                    </el-form-item>
                    <el-form-item label="原料优势" prop="tags">
                        <el-select v-model="form.tags" multiple filterable allow-create default-first-option :reserve-keyword="false" placeholder="请输入或选择您的原料优势" style="width: 320px">
                            <el-option v-for="item in tabs" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="检验报告" prop="reportType">
                        <el-radio-group v-model="form.reportType">
                            <el-radio v-for="item in solon_report_type" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="+form.reportType" prop="report">
                        <FileUpload v-model="form.report" format="array" :fileType="['pdf', 'png', 'jpg', 'jpeg']" :limit="10" :fileSize="100"></FileUpload>
                    </el-form-item>
                    <el-form-item v-if="form.reportType && form.reportType == 0">
                        <div>
                            <div>
                                <el-checkbox true-value="1" false-value="0" v-model="form.providePha" label="后期可根据需要提供《中国药典》检测报告" />
                            </div>
                            <div>
                                <el-checkbox true-value="1" false-value="0" v-model="form.provideMetal" label="后期可根据需要提供重金属/农残专项检测报告" />
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="是否提供样品" prop="provideSample">
                        <el-radio-group v-model="form.provideSample">
                            <el-radio v-for="item in yes_no" :key="item.value" :label="item.value">
                                {{ item.label }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="+form.provideSample" label="样品费用" prop="sampleFree">
                        <el-radio-group v-model="form.sampleFree">
                            <el-radio v-for="item in solon_sample_free" :key="item.value" :label="item.value">
                                {{ item.label }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="+form.provideSample && +form.sampleFree" label="样品含税单价" prop="samplePrice">
                        <el-input class="mr-20" style="width: 200px;" v-model="form.samplePrice" type="number" placeholder="请输入样品含税单价" clearable>
                            <template #prefix>¥</template>
                            <template #suffix>/kg</template>
                        </el-input>
                    </el-form-item>
                    <div class="h-1 bg-#f7f7f7 mg2-10-0"></div>
                    <div class="f-s-14 c-333 f-w-5 mb-10">企业信息</div>
                    <el-row :gutter="16">
                        <el-col :span="12">
                            <el-form-item label="企业名称" prop="cpyName">
                                <el-input v-model="form.cpyName" placeholder="请输入企业名称" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="仓库所在地" prop="warehouseAddress">
                                <AreaCascader v-model="form.warehouseAddress" :zlevel="2" @change="changeAddress"></AreaCascader>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系人姓名" prop="contactName">
                                <el-input v-model="form.contactName" placeholder="请输入联系人姓名" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系电话" prop="tel">
                                <el-input v-model="form.tel" placeholder="请输入联系电话" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </template>
        <template #footer>
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="submitForm">确认修改</el-button>
        </template>
    </vxe-modal>
</template>

<script setup name="create-supply-info" lang="ts">
import { httpRequests } from '@/utils/httpRequests';
import { propTypes } from '@/utils/propTypes';
import { formatDateRelative } from '@/utils/ruoyi';
import { AreaCascader } from '@/views/components';
import { FormInstance } from 'element-plus';
const emit = defineEmits(['update:show', 'close', 'success']);
const props = defineProps({
    show: propTypes.bool.def(false),
    title: propTypes.string.def('填写供应信息'),
    width: propTypes.number.def(760),
    info: propTypes.any.def(null),
    dict: propTypes.any.def(null)
});
const { dm_medicine_find_type, yes_no, solon_sample_free, solon_report_type } = toRefs(props.dict);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const dialogVisible = ref(props.show);
const form = ref<any>({
    price: undefined,
    priceType: 0, // 0-有具体价格，1-具体再议
    remark: '',
    images: '',
    tags: [],
    reportType: '',
    report: [],
    provideSample: 0, // 0-不提供样品，1-提供样品
    sampleFree: '', // 样品费用
    samplePrice: undefined,
    cpyName: '',
    warehouseAddress: '',
    contactName: '',
    tel: ''
});
const rules = reactive<any>({
    price: [
        {
            validator: (rule: any, value: any, callback: any) => {
                // 具体再议时，跳过价格必填与格式校验
                if (+form.value.priceType) return callback();
                const v = String(value ?? '').trim();
                if (!v) return callback(new Error('请输入价格'));
                // 最多两位小数的正数
                if (!/^\d+(?:\.\d{1,2})?$/.test(v)) return callback(new Error('最多保留两位小数'));
                const num = Number(v);
                if (!(num > 0)) return callback(new Error('价格必须大于0'));
                return callback();
            },
            trigger: ['change', 'blur']
        }
    ],
    images: [{ required: true, message: '请上传原料图片', trigger: 'change' }],
    cpyName: [{ required: true, message: '请输入企业名称', trigger: 'change' }],
    warehouseAddress: [{ required: true, message: '请输入仓库所在地', trigger: 'change' }],
    contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'change' }],
    tel: [
        { required: true, message: '请输入联系电话', trigger: 'change' },
        { pattern: /(^1\d{10}$)|(^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$)/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ]
});
const changeAddress = (value: any) => {
    form.value.warehouseAddressName = value?.name;
};
const formRef = ref<FormInstance>();
const close = () => {
    formRef.value?.resetFields();
    emit('update:show', false);
    emit('close', false);
};
const tabs = ref<any>([
    { label: '符合GAP要求', value: '符合GAP要求' },
    { label: '绿色食品认证', value: '绿色食品认证' },
    { label: '三无一全认定', value: '三无一全认定' },
    { label: '地理标志产品', value: '地理标志产品' },
    { label: '有机认证', value: '有机认证' }
]);
const submitForm = async () => {
    try {
        await formRef.value?.validate();
        proxy?.$modal.loading('修改中...');
        const params = {
            ...form.value,
            findId: props.info?.id,
            tags: form.value?.tags?.toString(),
            samplePrice: form.value?.samplePrice || 0,
            price: form.value?.price || 0
        }
        const res = await httpRequests.post('/solon/medicine-response/addForPc', params).finally(() => {
            proxy?.$modal.closeLoading();
        });
        if (res?.code === 200) {
            proxy?.$modal.msgSuccess('修改成功');
            emit('success', true);
            close();
        }
    } catch (error) {
        console.error(error);
    }
};

watch(
    () => props.show,
    (val) => {
        dialogVisible.value = val;
    }
);
</script>
<style lang="scss" scoped>
// 右上角定位三角形文字，背景主题色，颜色白色
</style>
