<template>
  <view class="inspect-add-container">
    <!-- 巡检表单内容 -->
    <scroll-view class="inspect-scroll" scroll-y>
      <u-form :model="inspectForm" ref="formRef" label-width="auto">
        <u-collapse
          v-model="activeCollapse"
          :border="true"
          accordion
          :value="['1']"
          bg-color="#ffffff"
          title-bg-color="#f8f9fa"
          :disabled="pageType === 'detail'"
        >
          <!-- 1. 树根部位 -->
          <u-collapse-item title="树根部位" name="1">
            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                1、观察树木根部，是否存在病害？
              </view>
              <u-radio-group
                v-model="inspectForm.root.disease"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in rootDiseaseOptions"
                  :key="item.value"
                  :name="item.score"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>

            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                2、观察根系下扎情况，是否存在以下情况？
              </view>
              <u-radio-group
                v-model="inspectForm.root.anchorage"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in rootGrowOptions"
                  :key="item.value"
                  :name="item.score"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>

            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                3、是否存在工程切根情况？
              </view>
              <u-radio-group
                v-model="inspectForm.root.cutting"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in rootCutOptions"
                  :key="item.value"
                  :name="item.score"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>
          </u-collapse-item>

          <!-- 2. 根颈部位 -->
          <u-collapse-item title="根颈部位" name="rootNeck">
            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                4、树颈部位是否存在木质部受损情况？
              </view>
              <u-radio-group
                v-model="inspectForm.collar.woodDamage"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in rootNeckWoodDamageOptions"
                  :key="item.value"
                  :name="item.score"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>

            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                5、树颈部位是否存在树皮受损情况？
              </view>
              <u-radio-group
                v-model="inspectForm.collar.barkDamage"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in rootNeckBarkDamageOptions"
                  :key="item.value"
                  :name="item.score"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>

            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                6、是否存在根颈松动情况？
              </view>
              <u-radio-group
                v-model="inspectForm.collar.loosening"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in rootNeckLooseOptions"
                  :key="item.value"
                  :name="item.score"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>
          </u-collapse-item>

          <!-- 3. 主干部位 -->
          <u-collapse-item title="主干部位" name="trunk">
            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                7、主干部位是否存在木质部受损情况？
              </view>
              <u-radio-group
                v-model="inspectForm.trunk.woodDamage"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in trunkWoodDamageOptions"
                  :key="item.value"
                  :name="item.score"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>

            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                8、是否存在主干倾斜情况？
              </view>
              <u-radio-group
                v-model="inspectForm.trunk.tilt"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in trunkTiltOptions"
                  :key="item.value"
                  :name="item.score"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>

            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                9、主干部位是否存在树皮受损情况？
              </view>
              <u-radio-group
                v-model="inspectForm.trunk.barkDamage"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in trunkBarkDamageOptions"
                  :key="item.value"
                  :name="item.score"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>
          </u-collapse-item>

          <!-- 4. 树冠部位 -->
          <u-collapse-item title="树冠部位" name="crown">
            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                10、是否有易落枝？
              </view>
              <u-radio-group
                v-model="inspectForm.crown.looseBranch"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in crownFallBranchOptions"
                  :key="item.value"
                  :name="item.score"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>

            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                11、枝干结合部是否存在异常？
              </view>
              <u-radio-group
                v-model="inspectForm.crown.collarAbnormal"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in crownBranchJointOptions"
                  :key="item.value"
                  :name="item.score"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>

            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                12、观察树冠透风情况及平衡性情况？
              </view>
              <u-radio-group
                v-model="inspectForm.crown.ventilationBalance"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in crownWindBalanceOptions"
                  :key="item.value"
                  :name="item.score"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>
          </u-collapse-item>

          <!-- 5. 权重因子评估 -->
          <u-collapse-item title="权重因子评估" name="weight">
            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                13、该行道树属于什么树种？
              </view>
              <u-radio-group
                v-model="inspectForm.weight.treeSpeciesType"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in weightTreeTypeOptions"
                  :key="item.value"
                  :name="item.label"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>

          <view class="question-wrap">
  <view class="question-title">
    <text class="required">*</text>
    14、该行道树的栽植年限属于哪一种？
  </view>

  <!-- 栽种年月：标题下方、单选上方，绑定表单字段 inspectForm.weight.plantingDate -->
  <view class="date-select-row" @click="showDatePicker = true" :class="pageType === 'detail' ? 'disabled-row' : ''">
    <text>{{ inspectForm.weight.plantingDate || '请选择栽种年月' }}</text>
    <u-icon name="arrow-right" color="#999" size="16"></u-icon>
  </view>

  <u-radio-group
    v-model="inspectForm.weight.plantingYears"
    placement="column"
    @change="calcRiskScore"
    :disabled="true"
  >
    <u-radio
      v-for="item in weightPlantYearOptions"
      :key="item.value"
      :name="item.label"
      :label="item.label"
    ></u-radio>
  </u-radio-group>
</view>

            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                15、该行道树是否处于风口位置？
              </view>
              <u-radio-group
                v-model="inspectForm.weight.isWindCorridor"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in weightWindGapOptions"
                  :key="item.value"
                  :name="item.boolVal"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>

            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                16、该行道树的树池类型属于哪一种？
              </view>
              <u-radio-group
                v-model="inspectForm.weight.treePoolType"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in weightPoolTypeOptions"
                  :key="item.value"
                  :name="item.label"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>

            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                17、该行道树的树池宽度与胸径比属于哪种？
              </view>
              <u-radio-group
                v-model="inspectForm.weight.treePoolWidthDbhRatio"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in weightPoolRatioOptions"
                  :key="item.value"
                  :name="item.label"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>
          </u-collapse-item>

          <!-- 6. 现状及处理措施 -->
          <u-collapse-item title="树木现状照片" name="measure">
            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                18、上传拍照图片
              </view>
              <!-- 修复：增加图片格式化、只读禁止删除、大图预览 -->
              <up-upload
                :file-list="formatImgList(imgList.imgList.value)"
                @after-read="imgList.uploadImgs"
                @delete="imgList.deleteImg"
                multiple
                :width="50"
                :height="50"
                :max-count="imgList.uploadConfig.maxCount"
                :upload-text="imgList.uploadConfig.uploadText"
                :size-type="imgList.uploadConfig.sizeType"
                :disabled="pageType === 'detail'"
                :deletable="pageType !== 'detail'"
                preview-full-image
              ></up-upload>
            </view>
          </u-collapse-item>
        </u-collapse>

        <view class="risk-result-wrap">
          <view style="padding-bottom: 10px;">风险评估结果</view>
          <view class="risk-item">
            <text class="risk-label">常规安全风险得分：</text>
            <text class="risk-value">{{ riskResult.normalScore }}</text>
          </view>
          <view class="risk-item">
            <text class="risk-label">常规风险等级：</text>
            <text class="risk-value" :class="getRiskLevelClass(riskResult.normalLevel)">{{ riskResult.normalLevel }}</text>
          </view>

          <view class="question-wrap" style="margin-top: 20rpx">
            <view class="question-title">
              <text class="required">*</text>
              20、是否开展应急评估？
            </view>
            <u-radio-group
              v-model="inspectForm.result.isEmergency"
              placement="column"
              @change="onEmergencyChange"
              :disabled="pageType === 'detail'"
            >
              <u-radio
                v-for="item in isEmergencyOptions"
                :key="item.value"
                :name="item.boolVal"
                :label="item.label"
              ></u-radio>
            </u-radio-group>
          </view>

          <view
            v-if="inspectForm.result.isEmergency"
            :key="emergencyKey"
            class="emergency-wrap"
          >
            <view class="question-wrap">
              <view class="question-title">
                <text class="required">*</text>
                21、请选择风力等级？
              </view>
              <u-radio-group
                v-model="inspectForm.result.windPower"
                placement="column"
                @change="calcRiskScore"
                :disabled="pageType === 'detail'"
              >
                <u-radio
                  v-for="item in emergencyWindLevelOptions"
                  :key="item.value"
                  :name="item.label"
                  :label="item.label"
                ></u-radio>
              </u-radio-group>
            </view>

            <view class="risk-item">
              <text class="risk-label">应急安全风险得分：</text>
              <text class="risk-value">{{ riskResult.emergencyScore }}</text>
            </view>
            <view class="risk-item">
              <text class="risk-label">应急风险等级：</text>
              <text class="risk-value" :class="getRiskLevelClass(riskResult.emergencyLevel)">{{ riskResult.emergencyLevel }}</text>
            </view>
          </view>
        </view>
      </u-form>
    </scroll-view>

    <!-- 底部固定提交按钮：仅新增页面显示 -->
    <view class="fixed-bottom-btn-wrap" v-if="pageType === 'add'">
      <u-button type="primary" size="large" @click="submitInspect" :loading="loadingFlag">提交巡检记录</u-button>
    </view>

    <!-- 栽种年月选择弹窗，放到最外层form结束标签外面 -->
<up-datetime-picker
    v-model="tempPlantDate"
    :show="showDatePicker"
    :closeOnClickOverlay="true"
    mode="year-month"
    minDate="1000"
    @confirm="onSelectPlantDate"
    @cancel="showDatePicker=false"
></up-datetime-picker>

    <!-- 风险确认弹窗 -->
    <u-modal
      :show="showRiskModal"
      title="提交确认"
      showCancelButton="true"
      @cancel="modalCancel"
      @confirm="modalConfirm"
      confirm-text="确定提交"
      cancel-text="取消"
    >
      <view class="modal-risk-content">
        <view class="modal-row">常规安全风险得分：{{ modalContent.normalScore }}</view>
        <view class="modal-row">常规风险等级：{{ modalContent.normalLevel }}</view>
        <view class="modal-row" v-if="modalContent.showEmergency">
          应急安全风险得分：{{ modalContent.emergencyScore }}
        </view>
        <view class="modal-row" v-if="modalContent.showEmergency">
          应急风险等级：{{ modalContent.emergencyLevel }}
        </view>
      </view>
    </u-modal>
  </view>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { useUploadImgs } from '@/common/utils/useUploadImgs'
import { timeFormat } from '@/uni_modules/uview-plus'
// 引入创建、详情接口
import { inspectionLogCreate, getInspectDetail } from "@/api/tree-archive/tree-archive.js";

// 常量配置
const CONST = {
  UPLOAD_CONFIG: { maxCount: 5, uploadText: '选择图片', sizeType: ['compressed'] }
}

// 页面模式：add 新增 / detail 详情只读
const pageType = ref('add')
// 巡检详情ID
const detailId = ref('')
// 页面入参
const treeId = ref('')

// 基础变量
const loadingFlag = ref(false)
const formRef = ref(null)
const activeCollapse = ref(['1'])
const emergencyKey = ref(0)

// 风险确认弹窗
const showRiskModal = ref(false)
const modalContent = reactive({
  normalScore: '',
  normalLevel: '',
  emergencyScore: '',
  emergencyLevel: '',
  showEmergency: false
})

// 图片上传
const imgList = useUploadImgs({
  ...CONST.UPLOAD_CONFIG,
  formRef: formRef,
  fieldName: 'inspectImgs'
})
imgList.imgList.value = []
imgList.rawImgList.value = []

// ===================== 图片格式化函数（修复回显核心） =====================
const formatImgList = (imgArr) => {
  if (!imgArr || !Array.isArray(imgArr) || imgArr.length === 0) return []
  return imgArr.map(item => {
    return typeof item === 'string' ? { url: item } : item
  })
}

// ===================== 表单结构：完全对齐后端 VO =====================
const inspectForm = reactive({
  treeId: '',
  inspectionTime: '',
  // 树根部位
  root: {
    disease: null,
    anchorage: null,
    cutting: null
  },
  // 根颈部位
  collar: {
    woodDamage: null,
    barkDamage: null,
    loosening: null
  },
  // 主干部位
  trunk: {
    woodDamage: null,
    tilt: null,
    barkDamage: null
  },
  // 树冠部位
  crown: {
    looseBranch: null,
    collarAbnormal: null,
    ventilationBalance: null
  },
  // 权重因子
  weight: {
    treeSpeciesType: '',
    plantingYears: '',
    
    isWindCorridor: null,
    treePoolType: '',
    treePoolWidthDbhRatio: ''
  },
  // 评估结果
  result: {
    isEmergency: false,
    windPower: '',
    defectScore: 0,
    normalResult: {
      score: 0,
      level: ''
    },
    emergencyResult: {
      score: 0,
      level: ''
    }
  },
  // 现状照片
  status: {
    photos: []
  }
})

// 风险结果展示
const riskResult = reactive({
  baseScore: 0,
  weightTotal: 1,
  normalScore: 0,
  normalLevel: 'I 级 基本无风险',
  emergencyScore: 0,
  emergencyLevel: '基本无安全风险'
})

// ===================== 选项数据 =====================
const rootDiseaseOptions = [
  { label: '无真菌危害或腐朽情况', value: '0', score: 0 },
  { label: '存在真菌危害或腐朽情况', value: '1', score: 8 }
]
const rootGrowOptions = [
  { label: '根部下扎良好，无盘根或隆起', value: '0', score: 0 },
  { label: '存在根部隆起或盘根', value: '1', score: 7 }
]
const rootCutOptions = [
  { label: '无工程切根', value: '0', score: 0 },
  { label: '存在工程切根', value: '1', score: 5 }
]
const rootNeckWoodDamageOptions = [
  { label: '无受损情况', value: '0', score: 0 },
  { label: '受损程度＜10%', value: '1', score: 5 },
  { label: '受损程度介于10%（含）-30%（不含）', value: '2', score: 15 },
  { label: '受损程度介于30%（含）-50%（不含）', value: '3', score: 25 },
  { label: '受损程度≥50%', value: '4', score: 70 }
]
const rootNeckBarkDamageOptions = [
  { label: '受损程度＜10%', value: '0', score: 0 },
  { label: '受损程度介于10%-30%', value: '1', score: 2 },
  { label: '受损程度介于30%-50%', value: '2', score: 4 },
  { label: '受损程度≥50%', value: '3', score: 6 }
]
const rootNeckLooseOptions = [
  { label: '不存在树颈松动情况', value: '0', score: 0 },
  { label: '存在树颈松动情况', value: '1', score: 100 }
]
const trunkWoodDamageOptions = [
  { label: '无受损情况', value: '0', score: 0 },
  { label: '受损程度＜10%', value: '1', score: 5 },
  { label: '受损程度介于10%（含）-30%（不含）', value: '2', score: 12 },
  { label: '受损程度介于30%（含）-50%（不含）', value: '3', score: 20 },
  { label: '受损程度≥50%', value: '4', score: 70 }
]
const trunkTiltOptions = [
  { label: '倾斜度＜10°', value: '0', score: 0 },
  { label: '倾斜度介于10°（含）-20°（不含）', value: '1', score: 3 },
  { label: '倾斜度介于20°（含）-30°（不含）', value: '2', score: 8 },
  { label: '倾斜度≥30°', value: '3', score: 70 }
]
const trunkBarkDamageOptions = [
  { label: '受损程度＜10%', value: '0', score: 0 },
  { label: '受损程度介于10%（含）-30%（不含）', value: '1', score: 1 },
  { label: '受损程度介于30%（含）-50%（不含）', value: '2', score: 3 },
  { label: '受损程度≥50%', value: '3', score: 5 }
]
const crownFallBranchOptions = [
  { label: '未发现易落枝', value: '0', score: 0 },
  { label: '易落枝占整个树冠枝条数量的比例＜1/10', value: '1', score: 2 },
  { label: '易落枝占整个树冠枝条数量的比例≥1/10', value: '2', score: 3 }
]
const crownBranchJointOptions = [
  { label: '无异常', value: '0', score: 0 },
  { label: '有龟裂或卷皮情况', value: '1', score: 3 },
  { label: '有腐烂现象但尚未形成明显空洞', value: '2', score: 5 },
  { label: '有明显空洞或蛀干痕迹', value: '3', score: 70 }
]
const crownWindBalanceOptions = [
  { label: '透风情况较好，不偏冠', value: '0', score: 0 },
  { label: '存在【透风情况较好但有明显偏冠】或【透风性差但冠幅适中，不偏冠】', value: '1', score: 1 },
  { label: '透风性差且明显偏冠，但冠幅适中', value: '2', score: 2 },
  { label: '透风性差且冠幅较大，但不偏冠', value: '3', score: 5 },
  { label: '透风性差、冠幅较大且明显偏冠', value: '4', score: 8 }
]

const weightTreeTypeOptions = [
  { label: '深根性树种', value: '0', weight: 1 },
  { label: '浅根性树种', value: '1', weight: 1.1 }
]
const weightPlantYearOptions = [
  { label: '栽植 10 年以内', value: '0', weight: 1 },
  { label: '栽植 10-30 年', value: '1', weight: 1.1 },
  { label: '栽植 30 年以上', value: '2', weight: 1.2 }
]
const weightWindGapOptions = [
  { label: '否', value: '0', weight: 1, boolVal: false },
  { label: '是', value: '1', weight: 2, boolVal: true }
]
const weightPoolTypeOptions = [
  { label: '联通树池', value: '0', weight: 1 },
  { label: '独立树池', value: '1', weight: 1.2 },
  { label: '无树池或树池硬化', value: '2', weight: 1.5 }
]
const weightPoolRatioOptions = [
  { label: '7 倍及以上', value: '0', weight: 1 },
  { label: '5 倍（含）-7 倍（不含）', value: '1', weight: 1.1 },
  { label: '3 倍（含）-5 倍（不含）', value: '2', weight: 1.2 },
  { label: '3 倍以下', value: '3', weight: 1.3 }
]
const isEmergencyOptions = [
  { label: '否', value: '0', boolVal: false },
  { label: '是', value: '1', boolVal: true }
]
const emergencyWindLevelOptions = [
  { label: '7 级及以下', value: '0', weight: 1 },
  { label: '8-9 级', value: '1', weight: 1.5 },
  { label: '10 级', value: '2', weight: 2 },
  { label: '10 级以上', value: '3', weight: 3 }
]

// 风险等级配置
const normalRiskLevelConfig = [
  { min: 0, max: 10, level: 'I 级 基本无风险' },
  { min: 10, max: 30, level: 'II 级 轻度风险' },
  { min: 30, max: 70, level: 'III 级 中度风险' },
  { min: 70, max: 100, level: 'IV 级 重度风险' },
  { min: 100, max: 999999, level: 'V 级 极度风险' }
]
const emergencyRiskLevelConfig = [
  { min: 0, max: 10, level: '基本无安全风险' },
  { min: 10, max: 30, level: '轻度安全风险' },
  { min: 30, max: 70, level: '中度安全风险' },
  { min: 70, max: 100, level: '重度安全风险' },
  { min: 100, max: 9999999, level: '极度安全风险' }
]

// 栽种年月弹窗临时值、弹窗开关
const tempPlantDate = ref(Date.now())
const showDatePicker = ref(false)

// 选中年月自动赋值表单+自动匹配栽植年限单选
const onSelectPlantDate = (val) => {
  // 赋值到表单正式字段
  console.log(val)
    console.log(timeFormat(val.value, 'yyyy-mm'))
  inspectForm.weight.plantingDate = timeFormat(val.value, 'yyyy-mm')
  const selectYear = Number(inspectForm.weight.plantingDate.split('-')[0])
  const nowYear = new Date().getFullYear()
  const yearDiff = nowYear - selectYear

  if (yearDiff <= 10) {
    inspectForm.weight.plantingYears = '栽植 10 年以内'
  } else if (yearDiff > 10 && yearDiff <= 30) {
    inspectForm.weight.plantingYears = '栽植 10-30 年'
  } else {
    inspectForm.weight.plantingYears = '栽植 30 年以上'
  }
  calcRiskScore()
  showDatePicker.value = false
}

// ===================== 计分逻辑 =====================
const calcRiskScore = () => {
  const f = inspectForm
  // 1. 缺陷基础分
  let baseScore = 0
  baseScore += f.root.disease || 0
  baseScore += f.root.anchorage || 0
  baseScore += f.root.cutting || 0
  baseScore += f.collar.woodDamage || 0
  baseScore += f.collar.barkDamage || 0
  baseScore += f.collar.loosening || 0
  baseScore += f.trunk.woodDamage || 0
  baseScore += f.trunk.tilt || 0
  baseScore += f.trunk.barkDamage || 0
  baseScore += f.crown.looseBranch || 0
  baseScore += f.crown.collarAbnormal || 0
  baseScore += f.crown.ventilationBalance || 0

  // 2. 权重系数
  let weightTotal = 1
  const getWeightByLabel = (opts, label) => {
    const item = opts.find(o => o.label === label)
    return item ? item.weight : 1
  }
  const getBoolWeight = (opts, boolVal) => {
    const item = opts.find(o => o.boolVal === boolVal)
    return item ? item.weight : 1
  }

  weightTotal *= getWeightByLabel(weightTreeTypeOptions, f.weight.treeSpeciesType)
  weightTotal *= getWeightByLabel(weightPlantYearOptions, f.weight.plantingYears)
  weightTotal *= getBoolWeight(weightWindGapOptions, f.weight.isWindCorridor)
  weightTotal *= getWeightByLabel(weightPoolTypeOptions, f.weight.treePoolType)
  weightTotal *= getWeightByLabel(weightPoolRatioOptions, f.weight.treePoolWidthDbhRatio)

  // 常规得分
  const normalScore = Number((baseScore * weightTotal).toFixed(2))
  riskResult.baseScore = baseScore
  riskResult.weightTotal = weightTotal
  riskResult.normalScore = normalScore
  riskResult.normalLevel = getNormalRiskLevel(normalScore)

  // 应急得分
  if (f.result.isEmergency) {
    const windWeight = getWeightByLabel(emergencyWindLevelOptions, f.result.windPower)
    const emergencyScore = Number((normalScore * windWeight).toFixed(2))
    riskResult.emergencyScore = emergencyScore
    riskResult.emergencyLevel = getEmergencyRiskLevel(emergencyScore)
  } else {
    riskResult.emergencyScore = 0
    riskResult.emergencyLevel = '无安全风险'
  }
}

// 应急切换
const onEmergencyChange = async () => {
  inspectForm.result.windPower = ''
  emergencyKey.value++
  await nextTick()
  calcRiskScore()
}

// ===================== 工具方法 =====================
const getNormalRiskLevel = (score) => {
  for (let item of normalRiskLevelConfig) {
    if (score >= item.min && score < item.max) return item.level
  }
  return 'V 级 极度风险'
}
const getEmergencyRiskLevel = (score) => {
  for (let item of emergencyRiskLevelConfig) {
    if (score >= item.min && score < item.max) return item.level
  }
  return '极度安全风险'
}
const getRiskLevelClass = (level) => {
  if (level.includes('无风险')) return 'risk-level-low'
  if (level.includes('轻度')) return 'risk-level-normal'
  if (level.includes('中度')) return 'risk-level-warning'
  if (level.includes('重度') || level.includes('极度')) return 'risk-level-danger'
  return ''
}

onLoad(async (options) => {
  treeId.value = options.treeId || ''
  pageType.value = options.type || 'add'
  detailId.value = options.id || ''

  // 读取本地缓存
  const cacheStr = uni.getStorageSync('temp_inspect_fill_data')
  if (cacheStr) {
    try {
      const oldData = JSON.parse(cacheStr)
      // 表单赋值
      Object.assign(inspectForm, oldData)

      // 图片回填
      if (oldData.status?.photos && Array.isArray(oldData.status.photos)) {
        const imgArr = oldData.status.photos.map(url => ({ url, status: 'success' }))
        imgList.imgList.value = imgArr
        imgList.rawImgList.value = imgArr
      }

      // 栽种年月自动推算栽植年限
      if (inspectForm.weight.plantingDate) {
        const selectYear = Number(inspectForm.weight.plantingDate.split('-')[0])
        const nowYear = new Date().getFullYear()
        const yearDiff = nowYear - selectYear
        if (yearDiff <= 10) {
          inspectForm.weight.plantingYears = '栽植 10 年以内'
        } else if (yearDiff > 10 && yearDiff <= 30) {
          inspectForm.weight.plantingYears = '栽植 10-30 年'
        } else {
          inspectForm.weight.plantingYears = '栽植 30 年以上'
        }
      }
      // 自动计算分数
      nextTick(() => calcRiskScore())

      // 【关键】读取完毕立刻删除缓存，防止再次打开页面重复回填旧数据
      uni.removeStorageSync('temp_inspect_fill_data')
    } catch (err) {
      console.error('缓存解析失败', err)
      uni.removeStorageSync('temp_inspect_fill_data')
    }
  }

  // ========== 原有详情接口逻辑保持原样不动 ==========
  if (pageType.value === 'detail' && detailId.value) {
    try {
      const res = await getInspectDetail({ id: detailId.value })
      console.log('成功', res)
      Object.assign(inspectForm, res)
      imgList.imgList.value = inspectForm.status?.photos || []

      if (inspectForm.weight.plantingDate) {
        const selectYear = Number(inspectForm.weight.plantingDate.split('-')[0])
        const nowYear = new Date().getFullYear()
        const yearDiff = nowYear - selectYear
        if (yearDiff <= 10) {
          inspectForm.weight.plantingYears = '栽植 10 年以内'
        } else if (yearDiff > 10 && yearDiff <= 30) {
          inspectForm.weight.plantingYears = '栽植 10-30 年'
        } else {
          inspectForm.weight.plantingYears = '栽植 30 年以上'
        }
      }
      calcRiskScore()
    } catch (err) {
      uni.showToast({ title: '获取详情失败', icon: 'none' })
      console.error('获取巡检详情异常：', err)
    }
  }
})
// ===================== 表单校验 & 弹窗确认（新入口） =====================
const submitInspect = async () => {
  if (loadingFlag.value) return
  const f = inspectForm

  // 原有全部必填校验
  const requiredCheck = [
    { category: '树根部位', val: f.root.disease, tip: '请选择：观察树木根部，是否存在病害？' },
    { category: '树根部位', val: f.root.anchorage, tip: '请选择：观察根系下扎情况，是否存在以下情况？' },
    { category: '树根部位', val: f.root.cutting, tip: '请选择：是否存在工程切根情况？' },

    { category: '根颈部位', val: f.collar.woodDamage, tip: '请选择：树颈部位是否存在木质部受损情况？' },
    { category: '根颈部位', val: f.collar.barkDamage, tip: '请选择：树颈部位是否存在树皮受损情况？' },
    { category: '根颈部位', val: f.collar.loosening, tip: '请选择：是否存在根颈松动情况？' },

    { category: '主干部位', val: f.trunk.woodDamage, tip: '请选择：主干部位是否存在木质部受损情况？' },
    { category: '主干部位', val: f.trunk.tilt, tip: '请选择：是否存在主干倾斜情况？' },
    { category: '主干部位', val: f.trunk.barkDamage, tip: '请选择：主干部位是否存在树皮受损情况？' },

    { category: '树冠部位', val: f.crown.looseBranch, tip: '请选择：是否有易落枝？' },
    { category: '树冠部位', val: f.crown.collarAbnormal, tip: '请选择：枝干结合部是否存在异常？' },
    { category: '树冠部位', val: f.crown.ventilationBalance, tip: '请选择：观察树冠透风情况及平衡性情况？' },

    { category: '权重因子评估', val: f.weight.treeSpeciesType, tip: '请选择：该行道树属于什么树种？' },
    { category: '权重因子评估', val: f.weight.plantingYears, tip: '请选择：该行道树的栽植年限属于哪一种？' },
    { category: '权重因子评估', val: f.weight.isWindCorridor === null ? undefined : f.weight.isWindCorridor, tip: '请选择：该行道树是否处于风口位置？' },
    { category: '权重因子评估', val: f.weight.treePoolType, tip: '请选择：该行道树的树池类型属于哪一种？' },
    { category: '权重因子评估', val: f.weight.treePoolWidthDbhRatio, tip: '请选择：该行道树的树池宽度与胸径比属于哪种？' }
  ]
  for (let item of requiredCheck) {
    if (item.val === null || item.val === '') {
      const toastTitle = `${item.category}--${item.tip}`
      uni.showToast({ title: toastTitle, icon: 'none', duration: 2000 })
      return
    }
  }

  // 应急专项校验
  if (f.result.isEmergency && !f.result.windPower) {
    uni.showToast({ title: '应急评估--请选择风力等级', icon: 'none', duration: 2000 })
    return
  }

  // 图片校验
  const imgUrls = imgList.getSuccessImgUrls()
  if (!imgUrls || imgUrls.length === 0) {
    uni.showToast({ title: '树木现状照片--请上传拍照图片', icon: 'none', duration: 2000 })
    return
  }

  // 填充弹窗内容、弹出模态框
  modalContent.normalScore = riskResult.normalScore
  modalContent.normalLevel = riskResult.normalLevel
  modalContent.showEmergency = !!f.result.isEmergency
  modalContent.emergencyScore = riskResult.emergencyScore
  modalContent.emergencyLevel = riskResult.emergencyLevel

  showRiskModal.value = true
}

// 真正执行接口提交（弹窗确定后调用）
const doSubmit = async () => {
  const f = inspectForm
  const imgUrls = imgList.getSuccessImgUrls()

  // 组装最终提交数据
  const nowTime = timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
  f.treeId = Number(treeId.value)
  f.inspectionTime = nowTime
  f.status.photos = imgUrls

  // 回填计算结果
  f.result.defectScore = riskResult.baseScore
  f.result.normalResult.score = riskResult.normalScore
  f.result.normalResult.level = riskResult.normalLevel
    .replace('I 级', 'I级')
    .replace('II 级', 'II级')
    .replace('III 级', 'III级')
    .replace('IV 级', 'IV级')
    .replace('V 级', 'V级')
  f.result.emergencyResult.score = riskResult.emergencyScore
  f.result.emergencyResult.level = riskResult.emergencyLevel

  const submitData = { ...inspectForm }

  loadingFlag.value = true
  try {
    const res = await inspectionLogCreate(submitData)
    uni.showToast({ title: '提交成功', icon: 'success' })
    setTimeout(() => uni.navigateBack(), 1500)
  } catch (err) {
    uni.showToast({ title: '网络异常，提交失败', icon: 'none' })
    console.error(err)
  } finally {
    loadingFlag.value = false
    showRiskModal.value = false
  }
}

// 弹窗取消
const modalCancel = () => {
  showRiskModal.value = false
}
// 弹窗确定
const modalConfirm = () => {
  doSubmit()
}

// 页面卸载清空
onUnload(() => {
  imgList.imgList.value = []
  imgList.rawImgList.value = []
})
</script>

<style scoped lang="scss">
.inspect-add-container {
  min-height: 100vh;
  background-color: #fff;
}
.inspect-scroll {
  height: calc(100vh - 120rpx);
}
.question-wrap {
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  &:last-child {
    border-bottom: none;
  }
}
.question-title {
  font-size: 14px;
  line-height: 1.5;
  margin: 15rpx 0;
  color: #333;
  .required {
    color: #ff0000;
    margin-right: 5rpx;
  }
}
.risk-result-wrap {
  padding: 15rpx 15px;
}
.risk-item {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
  font-size: 14px;
  .risk-label {
    color: #666;
    margin-right: 10rpx;
  }
  .risk-value {
    color: #333;
    font-weight: 500;
  }
}
.emergency-wrap {}

.risk-level-low {
  color: #00b42a;
}
.risk-level-normal {
  color: #1989fa;
}
.risk-level-warning {
  color: #ff9500;
}
.risk-level-danger {
  color: #ff0000;
}

// 只读状态置灰
:deep(.u-radio-group.is-disabled),
:deep(.u-upload__item--disabled) {
  opacity: 0.7;
}

// 弹窗内容样式
.modal-risk-content {
  padding: 10px 0;
  .modal-row {
    font-size: 14px;
    line-height: 2;
    color: #333;
  }
}

/* 扩大单选可点击区域 + 固定文字最小宽度，解决短文本点击范围小问题 */
:deep(.u-radio) {
  width: 100%;
  padding: 10rpx 8rpx;
  box-sizing: border-box;
}

/* 核心：给单选文字设置最小宽度，拉长可点击区域 */
:deep(.u-radio__text) {
  min-width: 220rpx; /* 根据需求自行调大/调小 */
  display: inline-block;
}

/* 单列单选组，增加上下间距，避免误触 */
:deep(.u-radio-group--column) .u-radio {
  margin: 4rpx 0;
}

.date-select-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18rpx 12rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  font-size: 14px;
  color: #333;
  margin-bottom: 12rpx;
  &.disabled-row {
    background: #f5f5f5;
    color: #999;
  }
}

</style>