<template>
    <z-paging ref="paging" v-model="list" bgColor="#f7f7f7" @query="query" safe-area-inset-bottom>
        <template #top>
            <ut-navbar title="添加管理记录" :fixed="false">
                <template #left><view class=""></view></template>
            </ut-navbar>
        </template>
        <view class="pt-24">
            <up-form class="p-rtv" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
                <view class="startline-title pl-24 ml-24 mb-16">管理记录信息</view>
                <view class="bg-#fff pd-24 mb-20">
                    <!-- 操作日期 -->
                    <view class="h-1" id="operationDatepppp"></view>
                    <up-form-item :borderBottom="false" label="操作日期" required prop="operationDate">
                        <ut-datetime-picker v-model="form.operationDate.startDate" mode="datetime" dateFields="day">
                            <view class="d-flex mr-20">
                                <up-input v-model="form.operationDate.startDate" 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>
                        <ut-datetime-picker v-model="form.operationDate.endDate" mode="datetime" dateFields="day">
                            <view class="d-flex">
                                <up-input v-model="form.operationDate.endDate" 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>

                    <!-- 操作类型 -->
                    <ut-action-sheet v-model="form.operationType" :tabs="operationTypeOptions" title="选择操作类型">
                        <up-form-item borderBottom label="操作类型" required prop="operationType" id="operationTypepppp">
                            <view v-if="form.operationType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(operationTypeOptions, form.operationType) }}</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 :borderBottom="false" label="种养殖所在基地" required prop="baseId" id="baseIdpppp">
                        <view v-if="!deawerData" class="w-100% d-flex a-c j-c pd-24 b-radius bg-#FBFDFB border-#AFDDBB" @click="openDrawer">
                            <view class=""></view>
                            <view class="f-s-34 c-primary">请选择种养殖所在的基地</view>
                        </view>
                        <view class="w-100%" v-else>
                            <Baseinfo :modeValue="deawerData" @close="handleBaseinfoClose" :baseType="form.taskType" />
                        </view>
                    </up-form-item>
                    <!-- 操作方式 -->
                    <up-form-item borderBottom label="操作方式" required prop="operationMethod" id="operationMethodpppp">
                        <up-input v-model="form.operationMethod" placeholder="请输入操作方式" border="none"></up-input>
                    </up-form-item>

                    <!-- 记录人 -->
                    <up-form-item borderBottom label="记录人" required prop="recorder" id="recorderpppp">
                        <up-input v-model="form.recorder" placeholder="请输入记录人" border="none"></up-input>
                    </up-form-item>

                    <!-- 是否使用物料 -->
                    <up-form-item borderBottom label="是否使用物料" required prop="useMaterial" id="useMaterialpppp">
                        <up-radio-group v-model="form.useMaterial">
                            <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>
                    </up-form-item>

                    <!-- 备注 -->
                    <up-form-item borderBottom label="备注" prop="remark" id="remarkpppp">
                        <up-input v-model="form.remark" placeholder="请输入备注" border="none"></up-input>
                    </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="warning" @click="saveDraft()">暂存</up-button>
                <up-button type="primary" @click="save()">提交</up-button>
            </view>
        </template>
    </z-paging>
</template>
<script setup lang="ts">
import { ref, reactive, computed, getCurrentInstance, type ComponentInternalInstance } from 'vue';
import { useClientRequest } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { yes_no } = toRefs<any>(proxy?.useDict('yes_no'));
const deawerData = ref();
// 表单数据
const form = ref({
    operationDate: {
        startDate: null as string | null,
        endDate: null as string | null,
    },
    operationType: null as string | null,
    operationMethod: '',
    recorder: '',
    useMaterial: '0' as '0' | '1',
    remark: '',
});

// 操作类型选项（示例，可以根据实际需求调整）
const operationTypeOptions = ref([
    { label: '浇水', value: '1' },
    { label: '施肥', value: '2' },
    { label: '除草', value: '3' },
    { label: '病虫害防治', value: '4' },
    { label: '修剪', value: '5' },
    { label: '其他', value: '6' },
]);

// 自定义校验函数：操作日期校验
const validateOperationDate = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请选择操作日期'));
        return;
    }
    const { startDate, endDate } = value;
    if (!startDate) {
        callback(new Error('请选择操作开始时间'));
        return;
    }
    if (!endDate) {
        callback(new Error('请选择操作结束时间'));
        return;
    }
    const start = new Date(startDate);
    const end = new Date(endDate);
    if (end <= start) {
        callback(new Error('操作结束时间必须晚于开始时间'));
        return;
    }
    callback();
};

// 表单验证规则
const rules = reactive({
    operationDate: [{ validator: validateOperationDate, trigger: 'blur' }],
    operationType: [{ required: true, message: '请选择操作类型' }],
    operationMethod: [{ required: true, message: '请输入操作方式' }],
    recorder: [{ required: true, message: '请输入记录人' }],
    useMaterial: [{ required: true, message: '请选择是否使用物料' }],
    remark: [{ required: false, message: '请输入备注' }],
});

// 字典标签选择函数（从 port-create 复制）
const selectDictLabel = (dict: any[], value: any) => {
    if (!dict || dict.length === 0) return '';
    const item = dict.find((item) => item.value === value);
    return item ? item.label : '';
};

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

const query = async (pageNo: number, pageSize: number) => {
    const res = await useClientRequest.get('/plt-api/app/plantationTask/list', {
        pageNo,
        pageSize,
    });
    // return res.data;
};
const handleBaseinfoClose = () => {
    deawerData.value = null;
};
// 提交表单
const save = () => {
    uni.$u.debounce(
        async () => {
            try {
                console.log('开始提交管理记录');
                await upFormRef.value?.validate();
                console.log('校验完成');

                const params = {
                    ...form.value,
                    startDate: form.value.operationDate.startDate,
                    endDate: form.value.operationDate.endDate,
                };

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

                // 这里需要根据实际 API 进行调整
                const res = await useClientRequest.post('/plt-api/app/managementRecord/save', params);
                if (res.code == 200) {
                    uni.showToast({
                        title: '提交成功',
                        icon: 'success',
                        duration: 2000,
                    });
                    setTimeout(() => {
                        uni.navigateBack();
                    }, 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 saveDraft = () => {
    uni.$u.debounce(
        async () => {
            try {
                const params = {
                    ...form.value,
                    startDate: form.value.operationDate.startDate,
                    endDate: form.value.operationDate.endDate,
                };

                console.log('暂存参数:', params);

                // 这里需要根据实际 API 进行调整
                const res = await useClientRequest.post('/plt-api/app/managementRecord/draft', params);
                if (res.code == 200) {
                    uni.showToast({
                        title: '暂存成功',
                        icon: 'success',
                        duration: 2000,
                    });
                    setTimeout(() => {
                        uni.navigateBack();
                    }, 1000);
                }
            } catch (error: any) {
                console.log('暂存错误:', error);
            }
        },
        1000,
        true,
    );
};
</script>
