<template>
  <view class="container">
    <!-- 顶部固定吸顶Tabs区域 -->
    <up-sticky bg-color="#ffffff">
      <view class="header-wrap">
        <up-tabs
            v-model="activeTab"
            :list="tabList"
            active-color="#1989fa"
            inactive-color="#666"
            font-size="30rpx"
            @click="handleTabChange"
            :scrollable="false"
        />
      </view>
    </up-sticky>

    <!-- Tab0 基本信息页面 - v-if改v-show 核心修复 -->
    <view v-show="activeTab === 0" class="base-info-wrap">
      <up-form :model="formData" ref="formRef" label-width="140rpx" border-bottom>
        <up-form-item label="名称" prop="treetype" required>
          <up-input v-model.trim="formData.treetype" placeholder="请输入名称" maxlength="30" border="none"/>
        </up-form-item>

        <view class="form-row-wrap">
          <up-row gutter="10">
            <up-col span="6">
              <up-form-item label="胸径" prop="dbh" required>
                <up-input v-model.trim="formData.dbh" placeholder="请输入" maxlength="10" border="none"
                          input-align="left"/>
                <template #right>
                  <text style="padding-left: 12rpx;color:#ccc;font-size:14px">厘米</text>
                </template>
              </up-form-item>
            </up-col>
            <up-col span="6">
              <up-form-item label="高度" prop="treeheight">
                <up-input v-model.trim="formData.treeheight" placeholder="请输入" maxlength="10" border="none"
                          input-align="left"/>
                <template #right>
                  <text style="padding-left: 12rpx;color:#ccc;font-size:14px;">米</text>
                </template>
              </up-form-item>
            </up-col>
          </up-row>
        </view>

        <up-form-item label="位置" prop="growlocation" required class="location-form-item" @click="openMap">
          <up-input v-model="formData.growlocation" placeholder="请选择" readonly border="none"/>
          <template #right>
            <up-icon name="map" size="22"></up-icon>
          </template>
        </up-form-item>

        <up-row gutter="10">
          <up-col span="6">
            <up-form-item label="经度" :borderBottom="false">
              <up-input v-model="formData.longitude" placeholder="" readonly border="none"/>
            </up-form-item>
          </up-col>
          <up-col span="6">
            <up-form-item label="纬度" :borderBottom="false">
              <up-input v-model="formData.latitude" placeholder="" readonly border="none"/>
            </up-form-item>
          </up-col>
        </up-row>

        <up-form-item label="管护单位" prop="managedutyunit" required>
          <up-input v-model.trim="formData.managedutyunit" placeholder="请输入" maxlength="30" border="none"/>
        </up-form-item>

        <up-form-item label="权属分类" prop="oldtreeownershipText" required arrow
                      @click="handleActionSheetOpen('ownership')">
          <up-input v-model.trim="formData.oldtreeownershipText" placeholder="请选择" readonly border="none"
                    bg-color="transparent"/>
        </up-form-item>

        <!-- ✅ 核心修复：补全name属性 + 所有配置齐全 -->
        <up-form-item label="图片信息" prop="treeImgList" required>
          <up-upload
              name="treeImgList"
              :file-list="treeImgList.imgList.value"
              @after-read="treeImgList.uploadImgs"
              @delete="treeImgList.deleteImg"
              multiple
              :width="70"
              :height="70"
              :max-count="treeImgList.uploadConfig.maxCount"
              :upload-text="treeImgList.uploadConfig.uploadText"
              :size-type="treeImgList.uploadConfig.sizeType"
          ></up-upload>
        </up-form-item>

        <view
            class="animated-area"
            :style="{
            height: isShow ? contentHeight + 'px' : '0',
            opacity: isShow ? 1 : 0,
            overflow: 'hidden'
          }"
        >
          <up-row gutter="10">
            <up-col span="6">
              <up-form-item label="拉丁文" prop="latinname">
                <up-input v-model.trim="formData.latinname" placeholder="请输入" maxlength="30" border="none"/>
              </up-form-item>
            </up-col>
            <up-col span="6">
              <up-form-item label="级别" arrow @click="handleActionSheetOpen('level')">
                <up-input v-model.trim="formData.treeleveltext" placeholder="请选择" readonly border="none"
                          bg-color="transparent"/>
              </up-form-item>
            </up-col>
          </up-row>

          <up-form-item label="生长环境" prop="growthenvironment">
            <up-input v-model.trim="formData.growthenvironment" placeholder="请输入" maxlength="50" border="none"/>
          </up-form-item>

          <view class="form-row-wrap">
            <up-row gutter="10">
              <up-col span="6">
                <up-form-item label="预估树龄" prop="estimationtreeage">
                  <up-input v-model.trim="formData.estimationtreeage" placeholder="请输入" maxlength="10" border="none"
                            input-align="left"/>
                  <template #right>
                    <text style="padding-left:12rpx;color:#ccc;font-size:14px">年</text>
                  </template>
                </up-form-item>
              </up-col>
              <up-col span="6">
                <up-form-item label="干周" prop="weekday">
                  <up-input v-model.trim="formData.weekday" placeholder="请输入" maxlength="10" border="none"
                            input-align="left"/>
                  <template #right>
                    <text style="padding-left:12rpx;color:#ccc;font-size:14px">厘米</text>
                  </template>
                </up-form-item>
              </up-col>
            </up-row>
          </view>

          <view class="form-row-wrap">
            <up-row gutter="10">
              <up-col span="6">
                <up-form-item label="东西冠幅" prop="canopyeastwest">
                  <up-input v-model.trim="formData.canopyeastwest" placeholder="请输入" maxlength="10" border="none"
                            input-align="left"/>
                  <template #right>
                    <text style="padding-left:12rpx;color:#ccc;font-size:14px">米</text>
                  </template>
                </up-form-item>
              </up-col>
              <up-col span="6">
                <up-form-item label="南北冠幅" prop="canopysouthnorth">
                  <up-input v-model.trim="formData.canopysouthnorth" placeholder="请输入" maxlength="10" border="none"
                            input-align="left"/>
                  <template #right>
                    <text style="padding-left:12rpx;color:#ccc;font-size:14px">米</text>
                  </template>
                </up-form-item>
              </up-col>
            </up-row>
          </view>
        </view>

        <up-button
            @click="toggleArea"
            type="primary"
            plain
            size="large"
            style="margin-top:20rpx"
        >
          {{ isShow ? '- 隐藏区域' : '+ 显示区域' }}
        </up-button>
      </up-form>
    </view>

    <!-- Tab1 变更日志页面 - 不变，保留原布局 -->
    <view v-show="activeTab === 1" class="log-wrap">
      <up-empty v-if="logRows.length === 0" marginTop="100" text="暂无变更日志"></up-empty>
      <view class="record-wrap" v-else>
        <up-card
            v-for="item in logRows"
            :key="item.id"
            :border="false"
            :show-head="false"
            class="tree-card"
            :foot-border-top="false"
            @click="toLogDetailPage(item)"
        >
          <template #body>
            <view class="card-body-inner">
              <view class="record-list-left" :style="`background-image: url(${item.treephotoone});`"></view>
              <view class="record-list-right">
                <view class="record-list-right-title">
                  <view class="u-line-1 treetypeName">{{ item.treetype }}</view>
                  <view style="text-align: right">{{ timeFormat(item.updatetime) }}</view>
                </view>
                <view class=" fs-align__center" style="margin: 5px 0">
                  <img src="../../../static/imgs/tree/tree-high.png" style="width:14px;height:14px;margin-right:6px;"
                       alt=""> 高度：{{ item.treeheight }} 米
                </view>
                <view class=" fs-align__center">
                  <img src="../../../static/imgs/tree/treearound.png" style="width:14px;height:14px;margin-right:6px;"
                       alt="">胸径：{{ item.dbh }} 厘米
                </view>
              </view>
            </view>
            <view class="treenumber-no">
              树木编号：{{ item.treenumber }}
            </view>
          </template>
        </up-card>
      </view>
    </view>

    <!-- 修改：底部按钮 新增改修改，只在基本信息Tab显示 -->
    <view class="fixed-bottom-btn-wrap" v-show="activeTab === 0">
      <up-button type="primary" @click="submit" :loading="loadingFlag" size="large" >修改树木信息</up-button>
    </view>

    <!-- 字典选择弹窗 -->
    <up-action-sheet
        :show="showActionSheet"
        :actions="currentActionSheetData.list"
        :title="currentActionSheetData.title"
        @close="handleActionSheetClose"
        @select="handleActionSheetSelect"
    ></up-action-sheet>

  </view>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { onReady, onLoad, onShow, onUnload } from '@dcloudio/uni-app';
// 接口修改：删除addTree，新增 treeDetailReq + updateTree
import { treeRoadReq, treeLogReq, treeDetailReq, updateTree } from "@/api/tree-archive/tree-archive.js";
import { timeFormat } from '@/uni_modules/uview-plus';
import { useUploadImgs } from '@/common/utils/useUploadImgs'
import { useUserStore } from '@/pinia/user';

// ========== 常量配置区 - 完全对标参考页写法 集中管理 ==========
const CONST = {
  // 上传配置 统一抽离，和参考页一致
  UPLOAD_CONFIG: { maxCount: 3, uploadText: '选择图片', sizeType: ['compressed'] }
}

// ========== 页面关闭统一跳转 ==========
onUnload(() => {
  uni.reLaunch({url: '/pages-sub/data/tree-archive/index'})
})

// ========== 基础变量 ==========
const rows = ref([])
const roadId = ref('')
const count = ref(0)
const treeId = ref('') // 树木主键ID 必传修改接口
const loadingFlag = ref(false)
const isInit = ref(false) // ✅ 新增：防止重复加载回显数据的核心标识

// ========== Tab切换核心变量 ==========
const activeTab = ref(0); // 0=基本信息 1=变更日志
const tabList = ref([{name: '基本信息'}, {name: '变更日志'}]);

// ========== 数据变量 ==========
const logRows = ref([]) // 变更日志列表数据
const userStore = useUserStore();
const formRef = ref(null)
const isShow = ref(false)
const contentHeight = ref(200)
const treeOwnershipData = ref([])
const treeLevelData = ref([])
const showActionSheet = ref(false);
const currentActionSheetData = reactive({type: '', list: [], title: ''});

// ========== 核心修复：图片上传配置 - 1:1对标工单页面 无任何冗余 ==========
const treeImgList = useUploadImgs({
  ...CONST.UPLOAD_CONFIG,
  formRef: formRef,
  fieldName: 'treeImgList'
})
// ✅ 初始化图片数组为纯净空数组，杜绝残留数据
treeImgList.imgList.value = []
treeImgList.rawImgList.value = []

// ========== 表单数据 ==========
const formData = reactive({
  id: '', // 新增主键ID，提交修改必传
  treetype: '',
  treeheight: '',
  dbh: '',
  treelevel: '',
  treeleveltext: '',
  managedutyunit: '',
  oldtreeownership: '',
  oldtreeownershipText: '',
  latinname: '',
  estimationtreeage: '',
  canopysouthnorth: '',
  canopyeastwest: '',
  weekday: '',
  growlocation: '',
  growthenvironment: '',
  treeImgList: [],
  address: '',
  latitude: '',
  longitude: '',
  road: '',
  maintainunit: '',
  treephotoone: '',
  treephototwo: '',
  treephotothree: '',
  treephotofour: '',
  treephotofive: ''
})

// ========== 表单校验规则【完整保留，无修改】 ==========
const isPureZero = (val) => {
  if (!val) return false;
  const pureZeroReg = /^0+$/;
  return pureZeroReg.test(val.trim());
};
const trimFormData = (obj) => {
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === 'string') {
      obj[key] = obj[key].trim();
    }
  }
};
const emojiReg = /[\uD83C\uD83D\uD83E][\uDC00-\uDFFF]+|[\u2702\u2705\u2708-\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763-\u2767\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\ufe0f\u200d]+/g;
const filterEmoji = (val) => typeof val === 'string' ? val.replace(emojiReg, '') : val;
const hasEmoji = (val) => val && emojiReg.test(val);
const rules = reactive({
  treetype: [
    {
      validator: (rule, val, callback) => hasEmoji(val) ? callback(new Error('禁止输入表情符号')) : callback(),
      trigger: ['blur', 'change', 'input'],
      priority: 10
    },
    {required: true, message: '请输入名称', trigger: ['blur', 'change', 'input']},
    {max: 30, message: '名称最多输入30个字符', trigger: ['blur', 'change', 'input']}
  ],
  treeheight: [
    {max: 10, message: '树高不能超过10个字符', trigger: ['blur', 'change', 'input']},
    {pattern: /^\d+(\.\d{1,2})?$/, message: '格式不正确，支持数字或两位小数', trigger: ['blur', 'change', 'input']},
    {
      validator: (rule, val, callback) => isPureZero(val) ? callback(new Error('不能输入纯0无效值')) : callback(),
      trigger: ['blur', 'change', 'input']
    }
  ],
  dbh: [
    {
      validator: (rule, val, callback) => hasEmoji(val) ? callback(new Error('禁止输入表情符号')) : callback(),
      trigger: ['blur', 'change', 'input'],
      priority: 10
    },
    {required: true, message: '请输入胸径', trigger: ['blur', 'change', 'input']},
    {max: 10, message: '胸径不能超过10个字符', trigger: ['blur', 'change', 'input']},
    {pattern: /^\d+(\.\d{1,2})?$/, message: '格式不正确，支持数字或两位小数', trigger: ['blur', 'change', 'input']},
    {
      validator: (rule, val, callback) => isPureZero(val) ? callback(new Error('不能输入纯0无效值')) : callback(),
      trigger: ['blur', 'change', 'input']
    }
  ],
  estimationtreeage: [
    {max: 10, message: '预估树龄不能超过10个字符', trigger: ['blur', 'change', 'input']},
    {pattern: /^\d+(\.\d{1,2})?$/, message: '格式不正确，支持数字或两位小数', trigger: ['blur', 'change', 'input']},
    {
      validator: (rule, val, callback) => isPureZero(val) ? callback(new Error('不能输入纯0无效值')) : callback(),
      trigger: ['blur', 'change', 'input']
    }
  ],
  weekday: [
    {max: 10, message: '干周不能超过10个字符', trigger: ['blur', 'change', 'input']},
    {pattern: /^\d+(\.\d{1,2})?$/, message: '格式不正确，支持数字或两位小数', trigger: ['blur', 'change', 'input']},
    {
      validator: (rule, val, callback) => isPureZero(val) ? callback(new Error('不能输入纯0无效值')) : callback(),
      trigger: ['blur', 'change', 'input']
    }
  ],
  canopyeastwest: [
    {max: 10, message: '东西冠幅不能超过10个字符', trigger: ['blur', 'change', 'input']},
    {pattern: /^\d+(\.\d{1,2})?$/, message: '格式不正确，支持数字或两位小数', trigger: ['blur', 'change', 'input']},
    {
      validator: (rule, val, callback) => isPureZero(val) ? callback(new Error('不能输入纯0无效值')) : callback(),
      trigger: ['blur', 'change', 'input']
    }
  ],
  canopysouthnorth: [
    {max: 10, message: '南北冠幅不能超过10个字符', trigger: ['blur', 'change', 'input']},
    {pattern: /^\d+(\.\d{1,2})?$/, message: '格式不正确，支持数字或两位小数', trigger: ['blur', 'change', 'input']},
    {
      validator: (rule, val, callback) => isPureZero(val) ? callback(new Error('不能输入纯0无效值')) : callback(),
      trigger: ['blur', 'change', 'input']
    }
  ],
  growlocation: [{required: true, message: '请选择地图位置', trigger: ['blur', 'change', 'manual']}],
  managedutyunit: [
    {
      validator: (rule, val, callback) => hasEmoji(val) ? callback(new Error('禁止输入表情符号')) : callback(),
      trigger: ['blur', 'change', 'input'],
      priority: 10
    },
    {required: true, message: '请输入管护单位', trigger: ['blur', 'change', 'input']},
    {max: 30, message: '管护单位最多输入30个字符', trigger: ['blur', 'change', 'input']}
  ],
  oldtreeownershipText: [{required: true, message: '请选择权属分类', trigger: ['blur', 'change']}],
  latinname: [
    {
      validator: (rule, val, callback) => hasEmoji(val) ? callback(new Error('禁止输入表情符号')) : callback(),
      trigger: ['blur', 'change', 'input'],
      priority: 10
    },
    {max: 30, message: '拉丁文最多输入30个字符', trigger: ['blur', 'change', 'input']}
  ],
  growthenvironment: [
    {
      validator: (rule, val, callback) => hasEmoji(val) ? callback(new Error('禁止输入表情符号')) : callback(),
      trigger: ['blur', 'change', 'input'],
      priority: 10
    },
    {max: 50, message: '生长环境最多输入50个字符', trigger: ['blur', 'change', 'input']}
  ],
  treeImgList: [treeImgList.imgValidateRule]
})

// ========== 生命周期 ==========
onLoad((options) => {
  console.log('编辑页入参', options)
  roadId.value = options.roadId || ''
  count.value = options.count || 0
  treeId.value = options.id || '' // 获取树木主键ID
  formData.id = treeId.value      // 赋值给表单，提交必传
  formData.road = roadId.value    // 赋值道路ID
  isInit.value = false // 初始化标识为false
});

onShow(async () => {
  treeLevelData.value = uni.$dict.transformLabelValueToNameValue(uni.$dict.getDictSimpleList('tree_level'))
  treeOwnershipData.value = uni.$dict.transformLabelValueToNameValue(uni.$dict.getDictSimpleList('tree_ownership'))
  // ✅ 核心修复：只执行一次回显加载，彻底杜绝重复加载
  if (activeTab.value === 0 && treeId.value && !isInit.value) {
    await getTreeDetail()
    isInit.value = true // 加载完成后标记为true，永不重复执行
  }
})

onReady(() => {
  nextTick(() => formRef.value?.setRules(rules));
});

// ========== Tab切换事件 ==========
const handleTabChange = async (item) => {
  activeTab.value = item.index
  if (activeTab.value === 0) {
    getTreeLogList()
  } else if (activeTab.value === 1) {
    getTreeLogList()
  }
}

// ========== 接口请求 ==========
const treeRoadQuery = async () => {
  const res = await treeRoadReq({road: roadId.value})
  rows.value = res.list
}

// ========== ✅ 终极修复：图片回显逻辑 - 彻底解决重复渲染4张图的问题 ==========
const getTreeDetail = async () => {
  const res = await treeDetailReq({id: treeId.value})
  Object.assign(formData, res)
  // 字典文本回显
  formData.oldtreeownershipText = uni.$dict.getDictLabel('tree_ownership', res.oldtreeownership)
  formData.treeleveltext = uni.$dict.getDictLabel('tree_level', formData.treelevel)

  // ✅ 第一步：强制清空为纯净空数组，杜绝任何残留
  treeImgList.imgList.value = []
  treeImgList.rawImgList.value = []
  formData.treephotoone = ''
  formData.treephototwo = ''
  formData.treephotoone = ''
  formData.treephotothree = ''
  formData.treephotofour = ''
  formData.treephotofive = ''

  // ✅ 第二步：接口返回几张就渲染几张，绝对不会重复
  if (Array.isArray(res.treeImgList) && res.treeImgList.length > 0) {
    const imgList = res.treeImgList.map((url, idx) => ({
      url,
      name: `renew_img_${idx}`,
      status: 'success'
    }));
    // 直接赋值，不再追加，彻底解决重复问题
    treeImgList.imgList.value = imgList
    treeImgList.rawImgList.value = imgList
  }
}

// 获取树木的变更日志列表
const getTreeLogList = async () => {
  const res = await treeLogReq({treeid: treeId.value})
  logRows.value = res.list
}

// ========== 表单相关方法 ==========
const toggleArea = () => isShow.value = !isShow.value

const handleActionSheetOpen = (type) => {
  const configMap = {
    ownership: {title: '请选择权属分类', list: treeOwnershipData.value},
    level: {title: '请选择树木级别', list: treeLevelData.value}
  };
  Object.assign(currentActionSheetData, configMap[type], {type});
  showActionSheet.value = true;
};

const handleActionSheetClose = () => {
  showActionSheet.value = false;
  Object.assign(currentActionSheetData, {type: '', list: [], title: ''});
};

const handleActionSheetSelect = (e) => {
  const {type} = currentActionSheetData;
  if (type === 'ownership') {
    formData.oldtreeownership = e.value
    formData.oldtreeownershipText = e.name
    formRef.value?.validateField('oldtreeownershipText');
  } else if (type === 'level') {
    formData.treelevel = e.value
    formData.treeleveltext = e.name
  }
  handleActionSheetClose();
};

// 地图选址
const openMap = () => {
  uni.chooseLocation({
    success: async (res) => {
      formData.growlocation = res.address
      formData.latitude = res.latitude
      formData.longitude = res.longitude
      await nextTick()
      formRef.value?.validateField('growlocation');
    },
    fail: (err) => {
      console.error('地图选择失败', err);
      err.errMsg.includes('auth deny') && uni.showToast({title: '请授权位置权限', icon: 'none'});
    }
  });
}

// ========== 核心修改：表单提交 ==========
const submit = async () => {
  if (loadingFlag.value) return
  // 过滤表情+去空格
  for (const key in formData) {
    if (typeof formData[key] === 'string') {
      formData[key] = filterEmoji(formData[key]).trim();
    }
  }
  // 表单校验
  const valid = await formRef.value.validate()
  if (!valid) return
  // 对标参考页：图片取值 统一调用封装方法
  const uploadImgUrls = treeImgList.getSuccessImgUrls()
  formData.maintainunit = userStore.userInfo.user.companyId
  formData.treeImgList = uploadImgUrls
  loadingFlag.value = true
  try {
    await updateTree(formData)
    uni.showToast({title: "修改成功", icon: "success"});
    uni.redirectTo({url: '/pages-sub/data/tree-archive/index'});
  } catch (err) {
    uni.showToast({title: "修改失败，请重试", icon: "none"});
    console.error(err)
  } finally {
    loadingFlag.value = false
  }
}

// ========== 页面跳转 ==========
const toLogDetailPage = (i) => {
  uni.navigateTo({
    url: `/pages-sub/data/tree-archive/logDetail`,
    success: (res) => {
      res.eventChannel.emit('logData', i);
    }
  })
}
</script>

<style scoped lang="scss">
.container {
  min-height: 100vh;
  padding-bottom: 100rpx;
}

.header-wrap {
  background-color: #fff;
  padding: 10rpx 0;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.03);
}

.base-info-wrap {
  padding: 20rpx 15rpx;
}

.log-wrap {
  min-height: calc(100vh - 120rpx);
}

.record-wrap {
  padding-bottom: 20px;
}

.treetypeName {
  flex: 1;
  font-size: 16px;
  font-weight: bold;
}

.record-list-left {
  height: 70px;
  width: 70px;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
}

.record-list-right {
  margin-left: 20px;
  flex: 1;
  overflow: hidden;
}

.record-list-right-title {
  display: flex;
  justify-content: space-between;
}

.treenumber-no {
  padding: 3px 10px;
  background: #bdefd0;
  font-size: 12px;
  margin-top: 8px;
}

.card-body-inner {
  display: flex;
}

.fs-align__center {
  display: flex;
  align-items: center;
}

// 表单样式
.animated-area {
  transition: all 0.3s ease-out;
  margin-top: 10rpx;
}

.location-form-item {
  padding-right: 10rpx;
}

.form-row-wrap {
  width: 100%;
  display: flex;
  flex-direction: column;

  :deep(.u-form-item) {
    position: relative;
    margin-bottom: 0 !important;
  }

  :deep(.u-form-item__body__right__message ) {
    position: absolute;
    left: 0;
    bottom: -20rpx;
    line-height: 20rpx;
    font-size: 22rpx;
    color: #f56c6c;
    width: 100%;
    box-sizing: border-box;
  }
}

.form-row-wrap + .u-form-item {
  margin-top: 25rpx !important;
}
</style>