<template>
    <z-paging ref="paging" v-model="list" bgColor="#f7f7f7" safe-area-inset-bottom>
        <template #top>
            <ut-navbar :title="pageTitle" :fixed="false"> </ut-navbar>
        </template>
        <view class="pt-24">
            <up-form class="p-rtv" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
                <view class="bg-#fff pd-24 mb-20">
                    <!-- 加工方式 -->
                    <up-form-item borderBottom label="加工方式" required prop="processType">
                        <view class="f-s-30 c-#666 f-w-5 flex1">{{ selectDictLabel(pt_process_type, form.processType) }}</view>
                    </up-form-item>
                    <!-- 加工对象 -->
                    <up-form-item v-if="+form.processType == 2" borderBottom label="加工对象" required prop="processMedType">
                        <view class="f-s-30 c-#666 f-w-5 flex1">{{ selectDictLabel(pt_stock_type, form.processMedType) }}</view>
                    </up-form-item>
                    <!-- 加工对象 -->
                    <ut-action-sheet v-else v-model="form.processMedType" :tabs="pt_stock_type" title="选择加工对象">
                        <up-form-item borderBottom label="加工对象" required prop="processMedType">
                            <view v-if="form?.processMedType" class="f-s-30 c-#333 f-w-5 flex1">{{ selectDictLabel(pt_stock_type, form.processMedType) }}</view>
                            <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择加工对象</view>
                            <template #right>
                                <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                            </template>
                        </up-form-item>
                    </ut-action-sheet>
                    <up-form-item v-if="+form?.processMedType == 1" @click="selectMedicine" borderBottom label="加工品种" required prop="varietyId">
                        <view v-if="form.varietyName" class="f-s-30 c-333 f-w-5 flex1">{{ form.varietyName }}</view>
                        <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择加工品种</view>
                        <template #right>
                            <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                        </template>
                    </up-form-item>
                    <up-form-item v-if="+form?.processMedType == 2" @click="selectMedicine" borderBottom label="加工品种" required prop="medicineCode">
                        <view v-if="form.varietyName" class="f-s-30 c-333 f-w-5 flex1">{{ form.varietyName }}</view>
                        <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择加工品种</view>
                        <template #right>
                            <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                        </template>
                    </up-form-item>

                    <!-- 加工日期 -->
                    <up-form-item :borderBottom="false" label="加工日期" required>
                        <up-form-item :borderBottom="false" prop="processingDate">
                            <ut-datetime-picker v-model="form.processingDate" mode="date" dateFields="day" @change="changeStartTime">
                                <view class="d-flex mr-20">
                                    <up-input v-model="form.processingDate" placeholder="请选择加工开始日期" border="bottom" :customStyle="{ paddingLeft: '0rpx' }"></up-input>
                                    <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill" style="margin-left: -20rpx"></up-icon>
                                </view>
                            </ut-datetime-picker>
                        </up-form-item>
                        <up-form-item :borderBottom="false" prop="processingDateEnd">
                            <ut-datetime-picker v-model="form.processingDateEnd" mode="date" dateFields="day">
                                <view class="d-flex">
                                    <up-input v-model="form.processingDateEnd" placeholder="请选择加工结束日期" border="bottom" :customStyle="{ paddingLeft: '0rpx' }"></up-input>
                                    <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill" style="margin-left: -20rpx"></up-icon>
                                </view>
                            </ut-datetime-picker>
                        </up-form-item>
                    </up-form-item>

                    <up-form-item v-if="+form?.processType == 2" borderBottom label="是否属于趁鲜切制目录品种" required prop="freshCatalogueStatus">
                        <view class="d-flex a-c w-100%">
                            <up-radio-group v-model="form.freshCatalogueStatus">
                                <up-radio :customStyle="{ marginRight: '60rpx' }" v-for="(item, index) in yes_no" :key="index" :label="item.label" :name="item.value"></up-radio>
                            </up-radio-group>
                        </view>
                    </up-form-item>
                    <!-- 生产批号 -->
                    <up-form-item v-if="+form?.processType == 2" borderBottom label="生产批号" required prop="processCode">
                        <view class="d-flex a-c j-sb w-100%">
                            <view class="flex1 d-flex">
                                <up-input v-model="form.processCode" placeholder="请输入生产批号" border="none" clearable></up-input>
                                <up-button @click="randomCode" class="c-#fff" type="primary" style="height: 50rpx; width: 130rpx">随机生成</up-button>
                            </view>
                        </view>
                    </up-form-item>
                    <!-- 加工批号 -->
                    <up-form-item v-else borderBottom label="加工批号" required prop="processCode">
                        <view class="d-flex a-c j-sb w-100%">
                            <view class="flex1 d-flex">
                                <up-input v-model="form.processCode" placeholder="请输入加工批号" border="none" clearable></up-input>
                                <up-button @click="randomCode" class="c-#fff" type="primary" style="height: 50rpx; width: 130rpx">随机生成</up-button>
                            </view>
                        </view>
                    </up-form-item>

                    <!-- 加工执行标准 -->
                    <ut-action-sheet v-if="+form?.processType == 1" v-model="form.standardType" :tabs="pt_standard_type" title="选择加工执行标准">
                        <up-form-item borderBottom label="加工执行标准" required prop="standardType">
                            <view v-if="form?.standardType" class="f-s-30 c-#333 f-w-5 flex1">{{ selectDictLabel(pt_standard_type, form.standardType) }}</view>
                            <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择加工执行标准</view>
                            <template #right>
                                <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                            </template>
                        </up-form-item>
                    </ut-action-sheet>
                    <!-- 执行标准 -->
                    <up-form-item v-if="+form?.processType == 2" borderBottom label="执行标准" prop="standardDetailName">
                        <up-input v-model="form.standardDetailName" placeholder="请输入执行标准" border="none" clearable></up-input>
                    </up-form-item>
                    <!-- 具体标准名称 -->
                    <up-form-item v-else borderBottom label="具体标准名称" prop="standardDetailName">
                        <up-input v-model="form.standardDetailName" placeholder="请输入具体标准名称" border="none" clearable></up-input>
                    </up-form-item>

                    <!-- 加工负责人 -->
                    <up-form-item borderBottom label="加工负责人" required prop="contactName">
                        <view class="d-flex a-c j-sb w-100%">
                            <up-input style="padding-left: 0" v-model="form.contactName" placeholder="请输入加工负责人" border="none"></up-input>
                        </view>
                    </up-form-item>

                    <!-- 加工工艺及流程 -->
                    <up-form-item label="加工工艺及流程" prop="ptech">
                        <view class="w-100%">
                            <view v-if="form?.ptech?.length !== 0" class="pd-24 d-flex flex-cln bg-#FBFDFB border-#37A954 b-radius p-rtv mb-20">
                                <view class="">
                                    <template v-for="(item, index) in form?.ptech?.split(',')" :key="index">
                                        <span v-if="index !== 0" class="c-#999 f-s-32 ml-10 mr-10">→ </span>
                                        <span class="f-s-32">{{ item }}</span>
                                    </template>
                                </view>
                                <view class="d-flex">
                                    <view class="flex1"></view>
                                    <up-button type="primary" @click="goPtech" style="width: 130rpx; height: 60rpx; border-radius: 10rpx">选择工艺</up-button>
                                </view>
                            </view>
                            <Go_button v-else @click="goPtech" title="请选择加工工艺及流程" style="flex: 1" />
                        </view>
                    </up-form-item>

                    <!-- 加工图片 -->
                    <up-form-item label="加工图片" prop="imgs">
                        <ut-upload v-model="form.imgs" :max-count="9" accept="image"></ut-upload>
                    </up-form-item>

                    <!-- 加工视频 -->
                    <up-form-item label="加工视频" prop="videos">
                        <ut-upload v-model="form.videos" :max-count="9" accept="video"></ut-upload>
                    </up-form-item>
                </view>
            </up-form>
        </view>
        <template #bottom>
            <view class="pd-24 d-flex j-c gap-20 base-bottom-wrap">
                <up-button type="primary" @click="save()">确认创建</up-button>
            </view>
        </template>
    </z-paging>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, type ComponentInternalInstance } from 'vue';
import { useClientRequest } from '@/utils/request';
import { useInfoStore } from '@/store';
import Go_button from '@/components/go-button/Go_button.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_process_type, pt_stock_type, pt_standard_type, yes_no } = toRefs<any>(proxy?.useDict('pt_process_type', 'pt_stock_type', 'pt_standard_type', 'yes_no'));

const infoStore = useInfoStore();
const pageTitle = ref('创建初加工任务');

// 表单数据
const form = ref({
    // 加工方式
    processType: '',
    // 加工对象
    processMedType: '',
    // 加工品种 ID
    varietyId: null as string | null,
    medicineCode: null as string | null,
    // 加工品种名称
    varietyName: '',
    // 加工开始日期
    processingDate: '',
    // 加工结束日期
    processingDateEnd: '',
    // 加工批号
    processCode: '',
    // 执行标准类型
    standardType: '',
    // 具体标准名称
    standardDetailName: '',
    // 加工负责人
    contactName: infoStore.userInfo?.name || '',
    // 工艺流程
    ptech: '' as string,
    // 图片
    imgs: null as string | null,
    // 视频
    videos: null as string | null,
    //是否属于趁鲜切制目录品种 (0-否 1-是)
    freshCatalogueStatus: null as string | null,
});

// 自定义校验函数 - 日期结束不能早于开始
const validateDateRange = (rule: any, value: any, callback: any) => {
    if (!form.value.processingDate || !form.value.processingDateEnd) {
        callback();
        return;
    }

    const startDate = new Date(form.value.processingDate);
    const endDate = new Date(form.value.processingDateEnd);

    if (endDate < startDate) {
        callback(new Error('加工结束日期不能早于开始日期'));
        return;
    }

    callback();
};

// 自定义校验函数 - 加工批号格式
const validateProcessCode = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请生成加工批号'));
        return;
    }

    if (!/^[A-Za-z0-9_-]+$/.test(value)) {
        callback(new Error('加工批号格式不正确，只能包含字母、数字、下划线和横线'));
        return;
    }

    callback();
};

// 表单验证规则
const rules = reactive({
    processType: [{ required: true, message: '请选择加工方式' }],
    processMedType: [{ required: true, message: '请选择加工对象' }],
    processingDate: [{ required: true, message: '请选择加工开始日期' }],
    processingDateEnd: [
        { required: true, message: '请选择加工结束日期' },
        { validator: validateDateRange, trigger: 'blur' },
    ],
    varietyId: [{ required: !!(+form.value.processMedType == 1), message: '请选择加工品种' }],
    medicineCode: [{ required: !!(+form.value.processMedType == 2), message: '请选择加工品种' }],
    processCode: [
        { required: true, message: '请生成加工批号' },
        { validator: validateProcessCode, trigger: 'blur' },
    ],
    standardType: [{ required: !!(+form.value.processType == 1), message: '请选择加工执行标准' }],
    standardDetailName: [{ required: !!(+form.value.standardType == 2), message: '请选择执行标准' }],
    contactName: [{ required: true, message: '请输入加工负责人' }],
    freshCatalogueStatus: [{ required: !!(+form.value.processType == 2), message: '请选择是否属于趁鲜切制目录品种' }],
});

const paging = ref();
const list = ref();
const upFormRef = ref<any>();

// 处理开始时间变化
const changeStartTime = (value: string) => {
    form.value.processingDate = value;
    if (!form.value?.processingDateEnd) {
        form.value.processingDateEnd = form.value.processingDate;
    }
};

// 随机生成批号
const randomCode = async () => {
    const code = await useClientRequest.post('/plt-api/app/plantationTask/getBatchCode', {
        plType: 'P',
        linkType: 'R',
    });
    form.value.processCode = code.data;
};

// 跳转工艺选择页
const goPtech = () => {
    uni.$once('updatePtechTransit', function (data: any) {
        form.value.ptech = data?.data;
    });
    uni.$u.route({
        type: 'navigateTo',
        url: '/tools/pro-process-steps/index',
        params: { ptechTransit: form.value.ptech },
    });
};

// 提交表单
const save = () => {
    uni.$u.debounce(
        async () => {
            try {
                console.log('开始提交加工任务');
                await upFormRef.value?.validate();
                console.log('校验完成');

                const params = {
                    ...form.value,
                };

                console.log('提交参数:', params);

                const res = await useClientRequest.post('/plt-api/app/processe/create', params);
                if (res.code == 200) {
                    uni.showToast({
                        title: '创建成功',
                        icon: 'success',
                        duration: 2000,
                    });
                    setTimeout(() => {
                        // 发送更新事件
                        uni.$emit('updateprocesstasklist');
                        uni.navigateBack({
                            delta: 1,
                        });
                    }, 1000);
                }
            } catch (error: any) {
                console.log('表单验证错误:', error);
                // 滚动到第一个错误字段
                if (error && error[0]?.field) {
                    const firstErrorField = error[0].field + 'pppp';
                    paging.value?.scrollIntoViewById(firstErrorField, 30, true);
                }
                return;
            }
        },
        1000,
        true,
    );
};
const selectMedicine = () => {
    if (form.value.processMedType == '1') {
        uni.$once('updateBiologicalname', function (data) {
            form.value.varietyName = data.msg.varietyName;
            form.value.varietyId = data.msg.id;
        });
        uni.navigateTo({
            url: '/tools/por-torganism/index',
        });
    } else if (form.value.processMedType == '2') {
        uni.$once('medicineSelected', (medicine: any) => {
            form.value.medicineCode = medicine.medicineCode;
            form.value.varietyName = medicine.medicineName;
        });
        uni.$u.route({
            type: 'navigateTo',
            url: '/tools/select-medicine/index',
            params: {
                singleSelect: true,
            },
        });
    }
};
onLoad((options: any) => {
    form.value.processType = options?.taskType;
    if (+options?.taskType == 2) {
        pageTitle.value = '创建趁鲜切制任务';
        form.value.processMedType = '2';
    }
});
</script>

<style scoped lang="scss">
.base-bottom-wrap {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    padding: 24rpx;
    z-index: 99;
}
</style>
