<template>
    <z-paging class="" ref="paging" bgColor="#fff" paging-class="paging-btm-shadow" safe-area-inset-bottom
        scroll-with-animation>
        <template #top>
            <ut-navbar :title="did ? '编辑GAP基地信息' : '添加GAP基地信息'" :fixed="false" border></ut-navbar>
        </template>
        <view class="pd-24">
            <up-form class="p-rtv" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
                <!-- 校验定位：基地类型 -->
                <!-- 基地信息部分 -->
                <view>
                    <view class="h-1" id="gapBaseTypepppp"></view>
                    <ut-action-sheet v-model="form.gapBaseType" :tabs="pt_base_type" title="选择基地类型">
                        <up-form-item borderBottom label="基地类型" required prop="baseType">
                            <view v-if="form.gapBaseType" class="f-s-30 c-333 f-w-5 flex1">{{
                                selectDictLabel(pt_base_type,
                                form.gapBaseType) }}</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>
                    <!-- 基地名称 -->
                    <view class="h-1" id="gapBaseNamepppp"></view>
                    <up-form-item borderBottom label="基地名称" required prop="gapBaseName">
                        <up-input v-model="form.gapBaseName" placeholder="请输入基地名称" border="none" clearable></up-input>
                    </up-form-item>
                    <!-- 选择获评品种 -->
                    <view class="h-1" id="medicineCodepppp"></view>
                    <up-form-item @click="selectMedicine" borderBottom label="获评品种" required prop="medicineCode">
                        <view v-if="form.medicineCode" class="f-s-30 c-333 f-w-5 flex1">{{ form.medicineName }}</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 prop="basePic" required>
                        <view class="flex1 ov-hd">
                            <view class="d-flex a-c mb-10" style="margin-bottom: 5px">
                                <view class="f-s-30 c-#666">基地范围</view>
                            </view>
                            <view class="bg-#ccc d-flex ov-hd p-rtv" @click="mapDrawArea">
                                <image class="w-full h-380" v-if="form?.basePic" :src="form?.basePic" mode="widthFix" />
                                <image class="w-full h-380" v-else src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/base/select_base_gap.png"
                                    mode="widthFix" />
                                <view v-if="!form?.basePic" class="btn-aree-center d-flex flex-cln a-c j-c">
                                    <image class="w-52 h-52 mb-10" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/base/draw_area_icon.png"
                                        mode="widthFix" />
                                    <view class="c-primary f-s-28 f-w-400">点击绘制基地范围</view>
                                </view>
                            </view>
                        </view>
                    </up-form-item>
                    <view class="h-1" id="adcodepppp"></view>
                    <up-form-item @click="showArea = true" borderBottom label="基地具体地址" required prop="adcode">
                        <!-- <up-input v-model="form.address" placeholder="请选择基地所在省/市/县/镇(乡)" border="none" clearable></up-input> -->
                        <view v-if="form?.adcode" class="f-s-30 c-333 f-w-5 flex1">{{ form?.adcodeName }}</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 prop="address">
                        <up-input v-model="form.address" placeholder="请填写村级以下的具体地址信息" border="none"
                            clearable></up-input>
                    </up-form-item>

                    <view class="h-1" id="areaPppp"></view>
                    <up-form-item required borderBottom label="基地面积" prop="area">
                        <up-input v-model="form.area" placeholder="地块绘制后自动带出可修改" border="none" clearable></up-input>
                        <template #right>
                            <span>{{ form.areaUnit }}</span>
                        </template>
                    </up-form-item>
                    <!-- 基地经纬度 -->
                      <view class="h-1" id="lngpppp"></view>
                    <view class="h-1" id="latpppp"></view>
                    <up-form-item required label="基地经纬度" class="form-item-wrap-column">
                        <view class="d-flex" style="margin-top: -10px">
                            <up-form-item prop="gapInfo.lng">
                                <up-input v-model="form.lng" border="bottom" placeholder="70-150内的经度数值" clearable></up-input>
                            </up-form-item>
                            <view class="pd-5"></view>
                            <up-form-item prop="gapInfo.lat">
                                <up-input v-model="form.lat" placeholder="4-53内的纬度数值" border="bottom" clearable></up-input>
                            </up-form-item>
                        </view>
                    </up-form-item>
                    <!-- 校验定位：建设时间 -->
                    <view class="h-1" id="ratedDatepppp"></view>
                    <ut-datetime-picker v-model="form.ratedDate" mode="date" :minDate="new Date(1990, 0, 1)" dateFields="day">
                        <up-form-item borderBottom label="获评GAP基地时间" required prop="ratedDate">
                            <up-input v-model="form.ratedDate" placeholder="请选择获评GAP基地时间" border="none"
                                clearable></up-input>
                            <template #right>
                                <up-icon size="22rpx" color="#2A6D52" name="arrow-down-fill"></up-icon>
                            </template>
                        </up-form-item>
                    </ut-datetime-picker>
                    <!-- 官方公示证明材料 -->
                    <view class="h-1" id="certFilepppp"></view>
                    <up-form-item borderBottom required prop="certFile">
                        <view class="flex1">
                            <view style="margin-bottom: 10rpx">
                                <span class="c-666 f-s-30">官方公示证明材料</span>
                                <span class="f-s-26 c-999">（可上传9张）</span>
                            </view>
                            <ut-upload v-model="form.certFile" :max-count="9"></ut-upload>
                        </view>
                    </up-form-item>
                    <!-- 官方公示网址 -->
                    <view class="h-1" id="urlpppp"></view>
                    <up-form-item borderBottom label="官方公示网址" prop="url" required>
                        <up-input v-model="form.url" placeholder="请输入官方公示网址" border="none" clearable></up-input>
                    </up-form-item>
                </view>
            </up-form>
        </view>
        <template #bottom>
            <view class="pd-20 d-flex">
                <up-button @click="submitForm" type="primary">提交</up-button>
            </view>
        </template>
    </z-paging>
    <ut-picker-area v-model:show="showArea" v-model="form.adcode" @confirm="confirmArea"></ut-picker-area>
</template>
<script setup lang="ts">
import { useUserStore } from '@/store';
import { useClientRequest } from '@/utils/request';
import { isOpenSetting } from '@/utils/common';
import { generateUniqueId } from '@/utils/public';
const tabs = reactive([
    { label: '基本信息', value: 'base' },
    { label: '地块信息', value: 'plot' },
    { label: '选址依据及环境信息', value: 'environment' },
]);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { yes_no, pt_org_type, pt_base_type } = toRefs<any>(proxy?.useDict('yes_no', 'pt_org_type', 'pt_base_type'));
const paging = ref<any>(null);
const upFormRef = ref<any>(null);
const showArea = ref(false);
const form = ref<any>({
    sourceType: '2', // 基地来源 1-GAP系统 2-手动录入
    gapBaseType: '',
    adcode: '',
    adcodeName: '',
    address: '',
    areaUnit: '亩',
    basePic: '',
    area: undefined,
    randomCode: generateUniqueId(),
    // 当前位置经纬度
    longitudeLatitude: {
        lng: '',
        lat: '',
    },
    coordinates: [],
    zoom: undefined,
    url: '',
});
const rules = reactive({
    gapBaseType: [{ required: true, message: '请选择基地类型' }],
    gapBaseName: [{ required: true, message: '请输入基地名称' }],
    medicineId: [{ required: true, message: '请选择获评品种' }],
    basePic: [{ required: true, message: '请绘制基地范围' }],
    adcode: [{ required: true, message: '请选择基地具体地址' }],
    area: [{ required: true, message: '请输入基地面积' }],
    ratedDate: [{ required: true, message: '请选择获评GAP基地时间' }],
    certFile: [{ required: true, message: '请上传官方公示证明材料' }],
    url: [{ required: true, message: '请输入官方公示网址' }],

});

const submitForm = async () => {
    uni.$u.debounce(
        async () => {
            try {
                await upFormRef.value?.validate();
            } catch (error: any) {
                // 滚动到第一个错误字段
                const firstErrorField = error && error[0].prop + 'pppp';
                paging.value?.scrollIntoViewById(firstErrorField, 30, true);
                return;
            }
            // 提交表单
            uni.showLoading({
                title: '提交中...',
            });
            try {
                const res = did.value ? await useClientRequest.post(`/plt-api/app/gapCertificationInfo/update`, form.value) : await useClientRequest.post('/plt-api/app/gapCertificationInfo/add', form.value);
                if (!res || res.code !== 200) return;
                uni.hideLoading();
                uni.showToast({
                    title: '提交成功',
                    icon: 'success',
                });
                uni.$emit('gapBaseInfoUpdated');
                // 返回上一页
                setTimeout(() => {
                    uni.navigateBack({
                        delta: 1,
                    });
                }, 1500);
            } catch (error) {
                uni.hideLoading();
            }
        },
        500,
        true
    );
};

const mapDrawArea = async () => {
    uni.$on('mapAreaData', (data: any) => {
        // 这里可以将 data 赋值给 form 中的相应字段
        form.value.basePic = data.gapInfo.basePic;
        form.value.area = String(data.gapInfo.area);
        form.value.areaUnit = data.gapInfo.areaUnit;
        form.value.coordinates = data.coordinates;
        form.value.lng = data.mapInfo.lng;
        form.value.lat = data.mapInfo.lat;
        form.value.lnglat = String(data.mapInfo.lng) + ',' + String(data.mapInfo.lat);
        form.value.zoom = data.mapInfo.zoom;
        uni.$off('mapAreaData');
    });
    if (form.value?.basePic) {
        // 暂存地图当前数据后跳转
        await useClientRequest.post('/plt-api/app/gapCertificationInfo/painting', {
            randomCode: form.value.id || form.value.randomCode,
            value: JSON.stringify({
                gapInfo: form.value,
                coordinates: form.value.coordinates,
            }),
        });
    }
    uni.$u.route({
        type: 'navigateTo',
        url: '/tools/map-draw-area/index',
        params: {
            drawId: form.value.id || form.value.randomCode,
            unit: form.value.areaUnit || '亩',
            lng: form.value.lng || form.value.longitudeLatitude.lng || '',
            lat: form.value.lat || form.value.longitudeLatitude.lat || '',
            zoom: form.value.zoom,
        },
    });
};

// 改成去选择获评品种页面
const selectMedicine = () => {
    uni.$on('medicineSelected', (medicine: any) => {
        form.value.medicineCode = medicine.medicineCode;
        form.value.medicineName = medicine.medicineName;
        uni.$off('medicineSelected');
    });
    uni.$u.route({
        type: 'navigateTo',
        url: '/tools/select-medicine/index',
        params: {
            singleSelect: true,
        },
    });
};
const confirmArea = (area: any) => {
    form.value.adcodeName = area.fullName;
};
const getDetailById = async (id: string) => {
    if (!id) return;
    const res = await useClientRequest.get(`/plt-api/app/gapCertificationInfo/getInfoById/${id}`);
    if (res && res.code === 200) {
        form.value = {
            ...res.data,
            lnglat: res.data.lng + ',' + res.data.lat,
        };
    }
};
const did = ref('');
onLoad((optins: any) => {
    if (optins.id) {
        // 编辑加载详
        did.value = optins.id;
        getDetailById(optins.id);
    } else {
        getLocationByAddress();
    }
});
// 获取当前经纬度返回地址
const getLocationByAddress = async () => {
    const info = await uni.getSystemInfo();
    let locationEnabled = info.locationEnabled; //判断手机定位服务是否开启
    let locationAuthorized = info.locationAuthorized; //判断定位服务是否允许微信授权
    if (locationEnabled == false || locationAuthorized == false) {
        //手机定位服务（GPS）未授权
        uni.showModal({
            title: '提示',
            content: '请打开定位服务功能',
            showCancel: false, // 不显示取消按钮
        });
        return;
    }

    const scope = await isOpenSetting('scope.userLocation');
    if (!scope) return;
    const location = await uni.getLocation({ type: 'gcj02', isHighAccuracy: true });
    form.value.longitudeLatitude = {
        lng: location.longitude,
        lat: location.latitude,
    };
};

</script>
<style lang="scss" scoped></style>
