<template>
    <z-paging ref="paging" bgColor="#F7F7F7" safe-area-inset-bottom paging-class="paging-btm-shadow" scroll-with-animation>
        <template #top>
            <ut-navbar :title="did && !+form?.baseInfo?.tempFlag ? '编辑基地' : '添加基地'" :fixed="false" border></ut-navbar>
            <view class="bg-fff pd2-0-24">
                <view class="pd-5"></view>
                <ut-tabs v-model="activeTab" :tabs="tabs" mode="btw" @change="changeActiveTab"></ut-tabs>
            </view>
        </template>
        <up-form class="p-rtv" labelPosition="top" :model="form" :rules="rules" labelWidth="auto" ref="upFormRef">
            <!-- 基本信息 -->
            <view ref="baseRef" class="pd2-18-24 d-flex j-sb a-c" id="base12345">
                <view>
                    <view class="startline-title">基本信息</view>
                </view>
                <view class="pd-10 bg-primary c-#fff radius-16 text-center" @click="selectGapInfo">
                    <view class="f-s-24">一键复用云南GAP基地信息</view>
                    <view class="f-s-18">仅做信息复用填写，不做GAP基地标记</view>
                </view>
            </view>
            <view class="pd-24 bg-#fff mb-10">
                <up-alert type="primary" fontSize="24rpx" description="注意：基地不强制与品种挂钩！基地地址以行政村为界，可成片集中或相对集中，跨村则视为另一基地（连片跨村除外）。"></up-alert>
                <view class="pd-10"></view>
                <view class="h-1" id="baseTypepppp"></view>
                <up-form-item borderBottom label="基地类型" required prop="baseType">
                    <view v-if="form.baseInfo.baseType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_base_type, form.baseInfo.baseType) }}</view>
                    <view v-else class="f-s-30 c-ccc f-w-4 flex1">请选择基地类型</view>
                </up-form-item>
                <!-- 基地名称 -->
                <view class="h-1" id="baseNamepppp"></view>
                <up-form-item borderBottom label="基地名称" required prop="baseInfo.baseName">
                    <up-input v-model="form.baseInfo.baseName" placeholder="请输入基地名称" border="none" clearable></up-input>
                </up-form-item>
                <!-- 基地编号 -->
                <view class="h-1" id="baseCodepppp"></view>
                <up-form-item borderBottom label="基地编号" prop="baseInfo.baseCode">
                    <up-input v-model="form.baseInfo.baseCode" placeholder="请输入基地编号" border="none" clearable></up-input>
                </up-form-item>
                <!-- 校验定位：建设时间 -->
                <view class="h-1" id="buildDatepppp"></view>
                <ut-datetime-picker v-model="form.baseInfo.buildDate" mode="date" dateFields="month">
                    <up-form-item borderBottom label="建设时间" prop="baseInfo.buildDate">
                        <up-input v-model="form.baseInfo.buildDate" readonly placeholder="请选择基地建设年份" 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="orgTypepppp"></view>
                <ut-action-sheet v-model="form.baseInfo.orgType" :tabs="pt_org_type" mode="custom" title="选择基地组织方式">
                    <up-form-item borderBottom label="基地组织方式" required prop="baseInfo.orgType">
                        <view v-if="form.baseInfo.orgType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_org_type, form.baseInfo.orgType) }}</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="contactIdpppp"></view>
                <up-form-item @click="selectCpyMember" borderBottom label="基地负责人" prop="baseInfo.contactId">
                    <view v-if="form.baseInfo.contactId" class="f-s-30 c-333 f-w-5 flex1">{{ form.baseInfo.contactName }}</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>
                <!-- 填写基地联系电话 -->
                <view class="h-1" id="contactTelpppp"></view>
                <up-form-item borderBottom label="基地联系电话" prop="baseInfo.contactTel">
                    <up-input v-model="form.baseInfo.contactTel" placeholder="请输入基地联系电话" border="none" clearable></up-input>
                </up-form-item>
                <template v-if="!+form.baseInfo.gapFlag && !form.baseInfo.gapId">
                    <view class="h-1" id="adcodepppp"></view>
                    <up-form-item @click="showArea = true" borderBottom label="基地具体地址" required prop="baseInfo.gapInfo.adcode">
                        <!-- <up-input v-model="form.address" placeholder="请选择基地所在省/市/县/镇(乡)" border="none" clearable></up-input> -->
                        <view v-if="form?.baseInfo?.gapInfo?.adcode" class="f-s-30 c-333 f-w-5 flex1">{{ form?.baseInfo?.gapInfo?.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="baseInfo.gapInfo.address">
                        <up-input v-model="form.baseInfo.gapInfo.address" placeholder="请填写村级以下的具体地址信息" border="none" clearable></up-input>
                    </up-form-item>
                    <up-form-item v-if="['1', '2'].includes(form.baseInfo.baseType)" borderBottom prop="baseInfo.gapInfo.basePic">
                        <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" v-if="form.baseInfo.gapInfo?.basePic" :src="form.baseInfo.gapInfo.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.baseInfo.gapInfo?.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>
                    <up-form-item v-if="['3'].includes(form.baseInfo.baseType)" borderBottom>
                        <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" v-if="form.baseInfo.gapInfo?.basePic" :src="form.baseInfo.gapInfo.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.baseInfo.gapInfo?.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="areaPppp"></view>
                    <up-form-item required borderBottom label="基地面积" prop="baseInfo.gapInfo.area">
                        <up-input v-model="form.baseInfo.gapInfo.area" placeholder="地块绘制后自动带出可修改" border="none" clearable></up-input>
                        <template #right>
                            <span>{{ form.baseInfo.gapInfo.areaUnit }}</span>
                        </template>
                    </up-form-item>
                    <!-- 基地经纬度 -->
                    <view class="h-1" id="lngpppp"></view>
                    <view class="h-1" id="latpppp"></view>
                    <up-form-item label="基地经纬度" class="form-item-wrap-column">
                        <view class="d-flex" style="margin-top: -10px">
                            <up-form-item prop="baseInfo.gapInfo.lng">
                                <up-input v-model="form.baseInfo.gapInfo.lng" border="bottom" placeholder="70-150内的经度数值" clearable></up-input>
                            </up-form-item>
                            <view class="pd-5"></view>
                            <up-form-item prop="baseInfo.gapInfo.lat">
                                <up-input v-model="form.baseInfo.gapInfo.lat" placeholder="4-53内的纬度数值" border="bottom" clearable></up-input>
                            </up-form-item>
                        </view>
                    </up-form-item>
                </template>
            </view>
            <!-- 地块/圈舍/培养架信息 -->
            <view ref="plotRef" class="h-1" id="plot12345"></view>
            <template v-if="form.baseInfo.baseType == '1'">
                <view class="pd-24">
                    <view class="startline-title">地块信息</view>
                </view>
                <view class="pd-24 bg-#fff">
                    <up-swipe-action>
                        <template v-for="(item, index) in form.landInfoList" :key="index">
                            <up-swipe-action-item class="mb-20" :options="options" @click="clickPlotSwipe($event, item, index, '编辑地块信息')">
                                <view class="plot-item pd-24">
                                    <view class="d-flex mb-16">
                                        <view class="f-s-32 f-w-5 c-#333 flex1 mr-10">{{ item?.landName || '-' }}</view>
                                        <view v-if="item?.contactName" class="f-s-24 c-#333">负责人：{{ item?.contactName }}</view>
                                    </view>
                                    <view class="f-s-28 c-#666">
                                        <span class="">面积：</span>
                                        <span class="c-#333 f-w-5">{{ item?.area || '-' }}{{ item?.areaUnit || '-' }}</span>
                                    </view>
                                </view>
                            </up-swipe-action-item>
                        </template>
                    </up-swipe-action>
                    <up-button @click="addPlot({ landType: form.baseInfo.baseType, areaUnit: form.baseInfo.gapInfo.areaUnit }, '添加地块')" type="primary" text="确定" plain>
                        <up-icon class="mr-10" name="plus" color="#37A954"></up-icon>
                        <span>添加地块信息</span>
                    </up-button>
                </view>
            </template>
            <template v-if="form.baseInfo.baseType == '2'">
                <view class="pd-24">
                    <view class="startline-title">圈舍信息</view>
                </view>
                <view class="pd-24 bg-#fff">
                    <up-swipe-action>
                        <template v-for="(item, index) in form.landInfoList" :key="index">
                            <up-swipe-action-item class="mb-20" :options="options" @click="clickPlotSwipe($event, item, index, '编辑圈舍信息')">
                                <view class="plot-item pd-24">
                                    <view class="d-flex mb-16">
                                        <view class="f-s-32 f-w-5 c-#333 flex1 mr-10">{{ item?.landName || '-' }}</view>
                                        <view v-if="item?.contactName" class="f-s-24 c-#333">负责人：{{ item?.contactName }}</view>
                                    </view>
                                    <view class="f-s-28 c-#666">
                                        <span class="">面积：</span>
                                        <span class="c-#333 f-w-5">{{ item?.area || '-' }}{{ item?.areaUnit || '-' }}</span>
                                    </view>
                                </view>
                            </up-swipe-action-item>
                        </template>
                    </up-swipe-action>

                    <up-button @click="addPlot({ landType: form.baseInfo.baseType, areaUnit: form.baseInfo.gapInfo.areaUnit }, '添加圈舍')" type="primary" text="确定" plain>
                        <up-icon class="mr-10" name="plus" color="#37A954"></up-icon>
                        <span>添加圈舍信息</span>
                    </up-button>
                </view>
            </template>
            <template v-if="form.baseInfo.baseType == '3'">
                <view class="pd-24">
                    <view class="startline-title">培养架信息</view>
                </view>
                <view class="pd-24 bg-#fff">
                    <up-swipe-action>
                        <template v-for="(item, index) in form.landInfoList" :key="index">
                            <up-swipe-action-item class="mb-20" :options="options" @click="clickPlotSwipe($event, item, index, '编辑培养架信息')">
                                <view class="plot-item pd-24">
                                    <view class="d-flex mb-16">
                                        <view class="f-s-32 f-w-5 c-#333 flex1 mr-10">{{ item?.landName || '-' }}</view>
                                        <view v-if="item?.contactName" class="f-s-24 c-#333">负责人：{{ item?.contactName }}</view>
                                    </view>
                                    <view class="d-flex flex-wrap gap-10">
                                        <view class="f-s-28 c-#666 w-310">
                                            <span class="">层数：</span>
                                            <span class="c-#333 f-w-5">{{ item?.layers || '-' }}</span>
                                        </view>
                                        <view class="f-s-28 c-#666 w-310">
                                            <span class="">每层容量：</span>
                                            <span class="c-#333 f-w-5">{{ item?.capacityAmount || '-' }}{{ item?.capacityUnit || '-' }}</span>
                                        </view>
                                        <view class="f-s-28 c-#666 w-310">
                                            <span class="">总容量：</span>
                                            <span class="c-#333 f-w-5">{{ item?.capacityAmount * item?.layers || '-' }}{{ item?.capacityUnit || '-' }}</span>
                                        </view>
                                        <view class="f-s-28 c-#666 w-310">
                                            <span v-if="item?.lightType" class="mr-10">{{ selectDictLabel(pt_light_type, item?.lightType) }}</span>
                                            <span v-if="item?.tempeStatus">{{ +item?.tempeStatus ? '有独立温控' : '无独立温控' }}</span>
                                        </view>
                                    </view>
                                </view>
                            </up-swipe-action-item>
                        </template>
                    </up-swipe-action>
                    <up-button @click="addPlot({ landType: form.baseInfo.baseType, areaUnit: form.baseInfo.gapInfo.areaUnit, capacityUnit: '瓶' }, '添加培养架')" type="primary" text="确定" plain>
                        <up-icon class="mr-10" name="plus" color="#37A954"></up-icon>
                        <span>添加培养架信息</span>
                    </up-button>
                </view>
            </template>

            <view class="pd-24" id="environment12345">
                <view class="startline-title">选址依据及环境信息</view>
            </view>
            <template v-if="form.baseInfo.baseType == '1'">
                <view class="pd-24 bg-#fff mb-10">
                    <view class="f-s-32 c-#333 f-w-600">选址依据</view>
                    <up-form-item label="是否道地产区">
                        <up-radio-group v-model="form.environmentInfo.daoStatus">
                            <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 label="基地选址依据/标准" prop="environmentInfo.accordFile" borderBottom>
                        <ut-upload v-model="form.environmentInfo.accordFile" :max-count="9" valueType="array" accept="file"></ut-upload>
                    </up-form-item>
                    <up-form-item label="文献或科学数据等选址适应性证明材料" prop="environmentInfo.adaptFile" borderBottom>
                        <ut-upload v-model="form.environmentInfo.adaptFile" :max-count="9" valueType="array" accept="file"></ut-upload>
                    </up-form-item>
                </view>
                <view class="pd-24 bg-#fff mb-10">
                    <view class="f-s-32 c-#333 f-w-600">环境信息</view>
                    <!-- 土壤类型选择 -->
                    <ut-action-sheet v-model="form.environmentInfo.soilType" :tabs="pt_soil_type" mode="custom" title="选择土壤类型">
                        <up-form-item borderBottom label="土壤类型" prop="soilType">
                            <view v-if="form.environmentInfo.soilType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_soil_type, form.environmentInfo.soilType) }}</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>
                    <!-- 字典 -->
                    <ut-action-sheet v-model="form.environmentInfo.soilTexture" :tabs="pt_soil_texture" mode="custom" title="选择土壤质地">
                        <up-form-item borderBottom label="土壤质地" prop="soilTexture">
                            <view v-if="form.environmentInfo.soilTexture" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_soil_texture, form.environmentInfo.soilTexture) }}</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 label="有机质含量" prop="environmentInfo.organic" borderBottom>
                        <up-input v-model="form.environmentInfo.organic" placeholder="请输入有机质含量" border="none" clearable></up-input>
                    </up-form-item>
                    <up-form-item label="土壤PH值" prop="environmentInfo.soilPh" borderBottom>
                        <up-input v-model="form.environmentInfo.soilPh" placeholder="请输入土壤PH值" border="none" clearable></up-input>
                    </up-form-item>
                    <ut-action-sheet v-model="form.environmentInfo.waterType" :tabs="pt_water_type" mode="custom" title="选择水源类型">
                        <up-form-item borderBottom label="水源类型" prop="waterType">
                            <view v-if="form.environmentInfo.waterType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_water_type, form.environmentInfo.waterType) }}</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 label="无霜期" prop="environmentInfo.notFrost" borderBottom>
                        <up-input v-model="form.environmentInfo.notFrost" placeholder="请输入无霜期" border="none" clearable></up-input>
                        <template #right>
                            <span>天</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="年降水量" prop="environmentInfo.precipitation" borderBottom>
                        <up-input v-model="form.environmentInfo.precipitation" placeholder="请输入年降水量" border="none" clearable></up-input>
                        <template #right>
                            <span>mm</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="年平均气温" prop="environmentInfo.avgTem" borderBottom>
                        <up-input v-model="form.environmentInfo.avgTem" placeholder="请输入年平均气温" border="none" clearable></up-input>
                        <template #right>
                            <span>℃</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="年绝对最高气温" prop="environmentInfo.maxTem" borderBottom>
                        <up-input v-model="form.environmentInfo.maxTem" placeholder="请输入年绝对最高气温" border="none" clearable></up-input>
                        <template #right>
                            <span>℃</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="年绝对最低气温" prop="environmentInfo.minTem" borderBottom>
                        <up-input v-model="form.environmentInfo.minTem" placeholder="请输入年绝对最低气温" border="none" clearable></up-input>
                        <template #right>
                            <span>℃</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="年日照时数" prop="environmentInfo.sunshineHours" borderBottom>
                        <up-input v-model="form.environmentInfo.sunshineHours" placeholder="请输入年日照时数" border="none" clearable></up-input>
                        <template #right>
                            <span>小时</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="海拔" prop="environmentInfo.altitude" borderBottom>
                        <up-input v-model="form.environmentInfo.altitude" placeholder="请输入海拔" border="none" clearable></up-input>
                        <template #right>
                            <span>米</span>
                        </template>
                    </up-form-item>
                    <!-- 水、土壤、大气等环评报告 -->
                    <up-form-item label="水、土壤、大气等环评报告" prop="environmentInfo.report" borderBottom>
                        <ut-upload v-model="form.environmentInfo.report" :max-count="9" valueType="array" accept="file"></ut-upload>
                    </up-form-item>
                    <!-- 基地图片 -->
                    <up-form-item label="基地图片" prop="environmentInfo.basePic" borderBottom>
                        <ut-upload v-model="form.environmentInfo.basePic" :max-count="9"></ut-upload>
                    </up-form-item>
                    <!-- 基地视频 -->
                    <up-form-item label="基地视频" prop="environmentInfo.baseVoice" borderBottom>
                        <ut-upload v-model="form.environmentInfo.baseVoice" :max-count="1" valueType="array" accept="video"></ut-upload>
                    </up-form-item>
                </view>
            </template>
            <template v-if="form.baseInfo.baseType == '2'">
                <view class="pd-24 bg-#fff mb-10">
                    <view class="f-s-32 c-#333 f-w-600">选址依据</view>
                    <up-form-item label="是否道地产区">
                        <up-radio-group v-model="form.environmentInfo.daoStatus">
                            <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 label="基地选址依据/标准" prop="environmentInfo.accordFile" borderBottom>
                        <ut-upload v-model="form.environmentInfo.accordFile" :max-count="9" valueType="array" accept="file"></ut-upload>
                    </up-form-item>
                    <up-form-item label="文献或科学数据等选址适应性证明材料" prop="environmentInfo.adaptFile" borderBottom>
                        <ut-upload v-model="form.environmentInfo.adaptFile" :max-count="9" valueType="array" accept="file"></ut-upload>
                    </up-form-item>
                </view>
                <view class="pd-24 bg-#fff mb-10">
                    <view class="f-s-32 c-#333 f-w-600">环境信息</view>
                    <ut-action-sheet v-model="form.environmentInfo.waterType" :tabs="pt_water_type" title="选择水源类型">
                        <up-form-item borderBottom label="水源类型" prop="waterType">
                            <view v-if="form.environmentInfo.waterType" class="f-s-30 c-333 f-w-5 flex1">{{ selectDictLabel(pt_water_type, form.environmentInfo.waterType) }}</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 label="无霜期" prop="environmentInfo.notFrost" borderBottom>
                        <up-input v-model="form.environmentInfo.notFrost" placeholder="请输入无霜期" border="none" clearable></up-input>
                        <template #right>
                            <span>天</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="年降水量" prop="environmentInfo.precipitation" borderBottom>
                        <up-input v-model="form.environmentInfo.precipitation" placeholder="请输入年降水量" border="none" clearable></up-input>
                        <template #right>
                            <span>mm</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="年平均气温" prop="environmentInfo.avgTem" borderBottom>
                        <up-input v-model="form.environmentInfo.avgTem" placeholder="请输入年平均气温" border="none" clearable></up-input>
                        <template #right>
                            <span>℃</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="年绝对最高气温" prop="environmentInfo.maxTem" borderBottom>
                        <up-input v-model="form.environmentInfo.maxTem" placeholder="请输入年绝对最高气温" border="none" clearable></up-input>
                        <template #right>
                            <span>℃</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="年绝对最低气温" prop="environmentInfo.minTem" borderBottom>
                        <up-input v-model="form.environmentInfo.minTem" placeholder="请输入年绝对最低气温" border="none" clearable></up-input>
                        <template #right>
                            <span>℃</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="年日照时数" prop="environmentInfo.sunshineHours" borderBottom>
                        <up-input v-model="form.environmentInfo.sunshineHours" placeholder="请输入年日照时数" border="none" clearable></up-input>
                        <template #right>
                            <span>小时</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="海拔" prop="environmentInfo.altitude" borderBottom>
                        <up-input v-model="form.environmentInfo.altitude" placeholder="请输入海拔" border="none" clearable></up-input>
                        <template #right>
                            <span>米</span>
                        </template>
                    </up-form-item>
                    <!-- 水、土壤、大气等环评报告 -->
                    <up-form-item label="水、大气等环评报告" prop="environmentInfo.report" borderBottom>
                        <ut-upload v-model="form.environmentInfo.report" :max-count="9" valueType="array" accept="file"></ut-upload>
                    </up-form-item>
                    <!-- 基地图片 -->
                    <up-form-item label="基地图片" prop="environmentInfo.basePic" borderBottom>
                        <ut-upload v-model="form.environmentInfo.basePic" :max-count="9"></ut-upload>
                    </up-form-item>
                    <!-- 基地视频 -->
                    <up-form-item label="基地视频" prop="environmentInfo.baseVoice" borderBottom>
                        <ut-upload v-model="form.environmentInfo.baseVoice" :max-count="1" valueType="array" accept="video"></ut-upload>
                    </up-form-item>
                </view>
            </template>
            <template v-if="form.baseInfo.baseType == '3'">
                <view class="pd-24 bg-#fff mb-10">
                    <up-form-item label="温度" prop="environmentInfo.temperature" borderBottom>
                        <up-input v-model="form.environmentInfo.temperature" placeholder="请输入温度" border="none" clearable></up-input>
                        <template #right>
                            <span>℃</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="湿度" prop="environmentInfo.humidity" borderBottom>
                        <up-input v-model="form.environmentInfo.humidity" placeholder="请输入湿度" border="none" clearable></up-input>
                        <template #right>
                            <span>%</span>
                        </template>
                    </up-form-item>
                    <up-form-item label="洁净度" prop="environmentInfo.cleanliness" borderBottom>
                        <up-input v-model="form.environmentInfo.cleanliness" placeholder="请输入洁净度" border="none" clearable></up-input>
                    </up-form-item>
                    <up-form-item label="光照" prop="environmentInfo.illumination" borderBottom>
                        <up-input v-model="form.environmentInfo.illumination" placeholder="请输入光照" border="none" clearable></up-input>
                    </up-form-item>
                    <up-form-item label="光照周期" prop="environmentInfo.lightCycle" borderBottom>
                        <up-input v-model="form.environmentInfo.lightCycle" placeholder="请输入光照周期" border="none" clearable></up-input>
                    </up-form-item>
                </view>
            </template>
        </up-form>
        <template #bottom>
            <view class="pd-20 d-flex">
                <up-button v-if="!did" @click="saveBaseInfo" class="mr-30" color="#F19F18" type="primary">暂存</up-button>
                <up-button @click="submitForm" type="primary">提交</up-button>
            </view>
        </template>
    </z-paging>
    <ut-picker-area v-model:show="showArea" v-model="form.baseInfo.gapInfo.adcode" :maxLevel="5" @confirm="confirmArea"></ut-picker-area>
    <FormPlot v-if="showPlot" v-model:show="showPlot" v-model="rowForm" :title="plotTitle" :dict="{ pt_light_type, pt_capacity_unit, yes_no }" @submit="submitFormPlotAdd"></FormPlot>
    <FormPlot v-if="showPlotEdit" v-model:show="showPlotEdit" v-model="rowFormEdit" :title="plotTitle" :dict="{ pt_light_type, pt_capacity_unit, yes_no }" @submit="submitFormPlotEdit"></FormPlot>
</template>
<script setup lang="ts">
import { useClientRequest } from '@/utils/request';
import { isOpenSetting } from '@/utils/common';
import { generateUniqueId } from '@/utils/public';
import FormPlot from './models/form-plot.vue';
import { getUrlParams, recursiveDecodeURIComponent } from '@/utils/ruoyi';
// import { $uGetRect } from 'uview-plus'
const tabs = reactive([
    { label: '基本信息', value: 'base' },
    { label: '地块信息', value: 'plot' },
    { label: '选址依据及环境信息', value: 'environment' },
]);
const activeTab = ref('base');
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { yes_no, pt_org_type, pt_base_type, pt_water_type, pt_soil_type, pt_soil_texture, pt_light_type, pt_capacity_unit } = toRefs<any>(proxy?.useDict('yes_no', 'pt_org_type', 'pt_base_type', 'pt_water_type', 'pt_soil_type', 'pt_soil_texture', 'pt_light_type', 'pt_capacity_unit'));
const paging = ref<any>(null);
const upFormRef = ref<any>(null);
const showArea = ref(false);
const showPlot = ref(false);
const showPlotEdit = ref(false);
const plotTitle = ref('添加地块信息');
const rowEidtIdx = ref<number | string>(-1);
const rowForm = ref<any>(null);
const rowFormEdit = ref<any>(null);
const form = ref<any>({
    baseInfo: {
        baseType: '',
        baseName: '',
        baseCode: '',
        gapFlag: '',
        buildDate: '',
        orgType: '',
        contactId: undefined,
        contactName: undefined,
        gapId: undefined,
        gapInfo: {
            adcode: '',
            adcodeName: '',
            address: '',
            areaUnit: '亩',
            area: undefined,
        },
        randomCode: generateUniqueId(),
        // 当前位置经纬度
        longitudeLatitude: {
            lng: '',
            lat: '',
        },
        coordinates: [],
    }, // 基地信息
    landInfoList: [], // 地块/圈舍/培养架信息
    environmentInfo: {}, // 基地环境信息
});
const options = ref([
    {
        text: '编辑',
        name: 'edit',
        style: {
            backgroundColor: '#37a954',
            color: '#fff',
        },
    },
    {
        text: '删除',
        name: 'delete',
        style: {
            backgroundColor: '#FF3B30',
            color: '#fff',
        },
    },
]);
const rules = reactive({
    'baseInfo.baseName': [{ required: true, message: '请输入基地名称' }],
    // 'baseInfo.baseCode': [{ required: true, message: '请输入基地编号' }],
    // 'baseInfo.buildDate': [{ required: true, message: '请选择建设时间' }],
    'baseInfo.orgType': [{ required: true, message: '请选择基地组织方式' }],
    // 'baseInfo.contactId': [{ required: true, message: '请选择基地负责人' }],
    'baseInfo.contactTel': [{ required: true, message: '请输入基地联系电话' }],
    'baseInfo.gapInfo.adcode': [{ required: true, message: '请选择基地具体地址' }],
    // 'baseInfo.gapInfo.basePic': [{ required: true, message: '请绘制基地范围' }],
    'baseInfo.gapInfo.area': [{ required: true, message: '请输入基地面积' }],
    // 'baseInfo.gapInfo.lng': [{ required: true, message: '请输入基地经纬度' }],
    // 'baseInfo.gapInfo.lat': [{ required: true, message: '请输入基地经纬度' }],
});
// saveInfo和submitForm防抖
// 暂存基地信息
const saveBaseInfo = async () => {
    uni.$u.debounce(
        async () => {
            // 提交表单
            uni.showLoading({
                title: '保存中...',
            });
            try {
                const res = await useClientRequest.post('/plt-api/app/base/temp', form.value);
                uni.hideLoading();
                if (!res || res.code !== 200) return;
                uni.showToast({
                    title: '保存成功',
                    icon: 'success',
                });
                uni.$emit('refreshBase');
                uni.$emit('refreshBaseList');
                // 返回上一页
                setTimeout(() => {
                    uni.navigateBack({
                        delta: 1,
                    });
                }, 1500);
            } catch (error) {
                uni.hideLoading();
            }
        },
        500,
        true,
    );
};
const submitForm = async () => {
    uni.$u.debounce(
        async () => {
            try {
                await upFormRef.value?.validate();
            } catch (error: any) {
                // 滚动到第一个错误字段
                console.log(error);

                const firstErrorField = error && error[0].field + 'pppp';
                paging.value?.scrollIntoViewById(firstErrorField, 30, true);
                return;
            }
            // 提交表单
            uni.showLoading({
                title: '提交中...',
            });
            try {
                const res = did.value && !+form.value?.baseInfo?.tempFlag ? await useClientRequest.post('/plt-api//app/base/update', form.value) : await useClientRequest.post('/plt-api/app/base/add', form.value);
                if (!res || res.code !== 200) return;
                uni.hideLoading();
                uni.showToast({
                    title: '提交成功',
                    icon: 'success',
                });
                uni.$emit('refreshBase');
                uni.$emit('refreshBaseList');
                // 返回上一页
                setTimeout(() => {
                    uni.navigateBack({
                        delta: 1,
                    });
                }, 1500);
            } catch (error) {
                uni.hideLoading();
            }
        },
        500,
        true,
    );
};

const mapDrawArea = async () => {
    uni.$on('mapAreaData', (data: any) => {
        // 这里可以将 data 赋值给 form 中的相应字段
        form.value.baseInfo.gapInfo.basePic = data.gapInfo.basePic;
        form.value.baseInfo.gapInfo.area = String(data.gapInfo.area);
        form.value.baseInfo.gapInfo.areaUnit = data.gapInfo.areaUnit;
        form.value.baseInfo.coordinates = data.coordinates;
        form.value.baseInfo.gapInfo.lng = data.mapInfo.lng;
        form.value.baseInfo.gapInfo.lat = data.mapInfo.lat;
        form.value.baseInfo.lnglat = `${data.mapInfo.lng},${data.mapInfo.lat}`;
        form.value.baseInfo.zoom = data.mapInfo.zoom;
        uni.$off('mapAreaData');
    });
    if (form.value.baseInfo.gapInfo?.basePic) {
        // 暂存地图当前数据后跳转
        await useClientRequest.post('/plt-api/app/gapCertificationInfo/painting', {
            randomCode: form.value.id || form.value.baseInfo.randomCode,
            value: JSON.stringify({
                gapInfo: form.value.baseInfo.gapInfo,
                coordinates: form.value.baseInfo.coordinates,
            }),
        });
    }
    uni.$u.route({
        type: 'navigateTo',
        url: '/tools/map-draw-area/index',
        params: {
            drawId: form.value.id || form.value.baseInfo.randomCode,
            unit: form.value.baseInfo.gapInfo.areaUnit || '亩',
            lng: form.value.baseInfo.gapInfo.lng || form.value?.longitudeLatitude?.lng || '',
            lat: form.value.baseInfo.gapInfo.lat || form.value?.longitudeLatitude?.lat || '',
            zoom: form.value.baseInfo.zoom,
        },
    });
};
const clickPlotSwipe = (e: any, item: any, idx: number | string, title = '编辑地块') => {
    console.log(e, item);
    const index = e.index;
    if (index == 0) {
        // 编辑
        plotTitle.value = title;
        rowFormEdit.value = item;
        rowEidtIdx.value = idx;
        showPlotEdit.value = true;
    }
    if (index == 1) {
        // 删除
        form.value.landInfoList.splice(idx, 1);
    }
};
const submitFormPlotEdit = (data: any) => {
    if (rowEidtIdx.value === -1) return;
    form.value.landInfoList[rowEidtIdx.value] = {
        ...data,
    };
};
const selectCpyMember = () => {
    uni.$on('selectCpyMember', (item: any) => {
        form.value.baseInfo.contactId = item.userInfo?.id;
        form.value.baseInfo.contactName = item.userInfo?.name;
        form.value.baseInfo.contactTel = item.userInfo?.phone;
        uni.$off('selectCpyMember');
    });
    uni.$u.route({
        type: 'navigateTo',
        url: '/tools/select-cpy-member/index',
    });
};
const selectGapInfo = () => {
    uni.$on('selectGapInfo', (item: any) => {
        console.log(item);
        form.value.baseInfo.gapInfo = {
           adcode: item.adcode,
           adcodeName: item.adcodeName,
           address: item.address,
           areaUnit: item.areaUnit,
           area: item.area,
           basePic: item.basePic,
           lng: item.lng,
           lat: item.lat,
           lnglat: `${item.lng},${item.lat}`,
        };
        form.value.baseInfo.coordinates = item.coordinates || [];
        uni.$off('selectGapInfo');
    });
    uni.$u.route({
        type: 'navigateTo',
        url: '/tools/select-gap-info/index',
        params: {
            baseType: form.value.baseInfo.baseType,
        },
    });
};
const removeGapInfo = () => {
    form.value.baseInfo.gapId = undefined;
    form.value.baseInfo.gapInfo = {
        adcode: '',
        adcodeName: '',
        address: '',
        areaUnit: mapUnitByBaseType[form.value.baseInfo.baseType],
        area: undefined,
    };
};
const confirmArea = (area: any) => {
    form.value.baseInfo.gapInfo.adcodeName = area.fullName;
};
// value label value
const changeActiveTab = (value: any) => {
    let scrollId = `${value.value}12345`;
    paging.value?.scrollIntoViewById(scrollId, 30, true);
};

onLoad((options: any) => {
    form.value.baseInfo.baseType = options.baseType || '1';
    form.value.baseInfo.gapInfo.areaUnit = mapUnitByBaseType[options.baseType || '1'];
    did.value = options?.id || getUrlParams(recursiveDecodeURIComponent(options?.q))?.id || '';
    if (did.value) {
        getDetailById(did.value);
    }
    getLocationByAddress();
});
onMounted(() => {});
// 获取当前经纬度返回地址
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,
    };
};
const addPlot = (rowItem: any, title = '添加地块') => {
    rowForm.value = {
        ...rowItem,
    };
    plotTitle.value = title;
    showPlot.value = true;
};
const submitFormPlotAdd = (data: any) => {
    form.value.landInfoList.push({
        ...data,
        baseId: did.value || undefined,
    });
};
const mapUnitByBaseType: any = {
    '1': '亩',
    '2': '平方米',
    '3': '平方米',
};
const did = ref('');
// 根据id获取基地详情
const getDetailById = async (id: string) => {
    const res = await useClientRequest.get(`/plt-api/app/base/getInfoAllById/${id}`);
    if (res && res.code === 200) {
        form.value = res.data || {};
    }
};
</script>
<style lang="scss" scoped>
.z-paging-wrap {
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
    left: 0;
}

.btn-aree-center {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
.plot-item {
    border: 1rpx solid rgba($u-primary, 0.4);
    border-radius: 10rpx;
}
.gap-info-card {
    border: 1rpx solid rgba($u-primary, 0.4);
    .card-close {
        position: absolute;
        top: 0rpx;
        right: 0rpx;
    }
}
</style>
