<template>
  <home-container>
    <view class="record-container">
      <!-- 表单区域 -->
      <uni-forms ref="form" :rules="rules" :modelValue="formData" label-position="top" err-show-type="modal">
        <!-- <scroll-view class="form-scroll" scroll-y> -->
        <uni-card :is-shadow="true" :shadow="shadow">
          <template v-slot:title>

            <view class="header-section collapse-title">
              <uni-row>
                <uni-col :span="8">
                  <view>
                    <image v-if="currentUser.avatar" :src="currentUser.avatar" class="cu-avatar xl round">
                  </view>
                </uni-col>
                <uni-col :span="16" class="flex padding justify-between">
                  <uni-row>
                    <uni-col>
                      <text>{{ formData.checkerName }} </text></br>
                      <text class="collapse-summary" v-if="formData.positionText">{{ formData.positionText }} ： </text>
                      <text class="collapse-summary">{{ formData.securityLocationText }} </text>
                    </uni-col>

                  </uni-row>

                </uni-col>
              </uni-row>
            </view>
          </template>
        </uni-card>
        <uni-card :border="false" :is-shadow="false" margin="0" class="no-bg">
          <view class="title-group">
            <view class="title-main">机场安检科长巡检记录单</view>
            <view class="title-sub">
              记录巡检过程中的问题和优秀事例，及时跟踪整改情况
            </view>
          </view>
        </uni-card>


        <!-- 基本信息 -->
        <uni-card :is-shadow="true" :shadow="shadow">
          <uni-collapse :accordion="false">
            <uni-collapse-item title="基本信息" name="group1" :open="false" :show-animation="true">

              <uni-forms-item label="任务标题" name="documentName">
                <uni-easyinput v-model="formData.documentName" placeholder="请输入任务标题" />
              </uni-forms-item>

              <uni-forms-item label="检查人" name="checkerName" required>
                <text class="form-value">{{ formData.checkerName }}</text>
              </uni-forms-item>

              <uni-forms-item label="检查时间" name="checkTime" required>

                <uni-datetime-picker type="datetime" :start="startDate" :end="endDate" v-model="formData.checkTime" />
              </uni-forms-item>




              <!-- 任务标题 -->
              <!-- <view class="form-item">
                  <text class="label">任务标题</text>
                  <textarea v-model="formData.documentName" placeholder="请输入任务标题" class="textarea" auto-height />
                </view> -->

              <!-- <uni-forms-item label="任务标题" name="documentName">
                <uni-easyinput v-model="formData.documentName" placeholder="请输入任务标题" />
              </uni-forms-item> -->


            </uni-collapse-item>
          </uni-collapse>
        </uni-card>


        <!-- 负面问题记录 -->
        <uni-card :is-shadow="true" :shadow="shadow">
          <uni-collapse :accordion="false" :value="['group2']">
            <!-- <uni-collapse-item title="负面问题记录" name="group2" :show-animation="true"> -->
            <uni-collapse-item name="group2" :show-animation="true">
              <template #title>
                <view style="display:flex;align-items:center">
                  <image src="/static/images/bad.png" style="width:32rpx;height:32rpx;margin-right:12rpx"
                    mode="aspectFit" />
                  <text>负面问题记录</text>
                </view>
              </template>
              <!-- 动态记录列表 -->
              <view v-for="(item, idx) in records" :key="idx" class="record-card">




                <!-- 大类 -->
                <view class="form-item">
                  <text class="label">问题类型</text>
                  <picker :value="item.categoryCodeOne" :range="bigOptions"
                    @change="onBigChange(idx, $event.detail.value)">
                    <view class="picker-box">{{ bigOptions[item.categoryCodeOne] || '请选择' }}</view>
                  </picker>
                </view>

                <!-- 小类（联动） -->
                <view class="form-item">
                  <picker :value="item.categoryCodeTwo" :range="smallOptions(item.categoryCodeOne)" @change="e => {
                    const val = e.detail.value;
                    item.categoryCodeTwo = val;
                    item.categoryNameTwo = smallOptions(item.categoryCodeOne)[val] || '无';
                  }">
                    <view class="picker-box">{{ smallOptions(item.categoryCodeOne)[item.categoryCodeTwo] || '请选择' }}
                    </view>
                  </picker>
                </view>

                <!-- 问题描述 -->
                <view class="form-item">
                  <text class="label">问题描述</text>
                  <textarea v-model="item.problemDescription" placeholder="请详细描述发现的问题" class="textarea" auto-height />
                </view>

                <!-- 涉及人员：点击 + 号添加 -->
                <view class="form-item">
                  <view class="label-row">
                    <text class="label">涉及人员</text>
                    <text class="add-person-btn" @click="openPersonPicker(idx)">+</text>
                  </view>
                  <view class="person-tags">
                    <view v-for="p in item.checkUserList" :key="p.userId" class="tag">
                      {{ p.nickName }} <text class="close" @click="removePerson(idx, p)">×</text>
                    </view>
                  </view>
                </view>

                <view v-if="records.length > 1" class="del-btn" @click="removeRecord(idx)">
                  删除本记录
                </view>
              </view>

              <button class="add-btn" @click="addRecord">+ 添加问题</button>

              <uni-popup ref="personPopup" type="bottom" :mask-click="true">
                <view class="popup-body">
                  <picker-view :value="[personIndex]" @change="onPersonPickerChange" style="height: 400rpx">
                    style="height: 400rpx">
                    <picker-view-column>
                      <view v-for="p in allPersons" :key="p.userId" class="picker-item">{{ p.nickName }}</view>
                    </picker-view-column>
                  </picker-view>
                  <button class="popup-btn" @click="confirmPerson">确定</button>
                </view>
              </uni-popup>


            </uni-collapse-item>
          </uni-collapse>
        </uni-card>


        <!-- 优秀事例记录 -->
        <uni-card :is-shadow="true" :shadow="shadow">
          <uni-collapse :accordion="false" :value="['group3']">
            <!-- <uni-collapse-item title="优秀事例记录" name="group3" :show-animation="true"> -->
              <uni-collapse-item name="group3" :show-animation="true">
              <template #title>
                <view style="display:flex;align-items:center">
                  <image src="/static/images/good.png" style="width:32rpx;height:32rpx;margin-right:12rpx"
                    mode="aspectFit" />
                  <text>优秀事例记录</text>
                </view>
              </template>
              <!-- 动态记录列表 -->
              <view v-for="(item, idx) in rewardRecords" :key="idx" class="record-card">




                <!-- 大类 -->
                <view class="form-item">
                  <text class="label">问题类型</text>
                  <picker :value="item.categoryCodeOne" :range="bigOptions"
                    @change="onBigChangeReward(idx, $event.detail.value)">
                    <view class="picker-box">{{ bigOptions[item.categoryCodeOne] || '请选择' }}</view>
                  </picker>
                </view>

                <!-- 小类（联动） -->
                <view class="form-item">
                  <picker :value="item.categoryCodeTwo" :range="smallOptions(item.categoryCodeOne)" @change="e => {
                    const val = e.detail.value;
                    item.categoryCodeTwo = val;
                    item.categoryNameTwo = smallOptions(item.categoryCodeOne)[val] || '无';
                  }">


                    <view class="picker-box">{{ smallOptions(item.categoryCodeOne)[item.categoryCodeTwo] || '请选择' }}
                    </view>
                  </picker>
                </view>

                <!-- 问题描述 -->
                <view class="form-item">
                  <text class="label">事例描述</text>
                  <textarea v-model="item.problemDescription" placeholder="请详细描述发现的问题" class="textarea" auto-height />
                </view>

                <!-- 涉及人员：点击 + 号添加 -->
                <view class="form-item">
                  <view class="label-row">
                    <text class="label">涉及人员</text>
                    <text class="add-person-btn" @click="openPersonPickerReward(idx)">+</text>
                  </view>
                  <view class="person-tags">
                    <view v-for="p in item.checkUserList" :key="p.userId" class="tag">
                      {{ p.nickName }} <text class="close" @click="removePersonReward(idx, p)">×</text>
                    </view>
                  </view>
                </view>
                <!-- 奖励建议 -->
                <view class="form-item">
                  <text class="label">奖励建议</text>
                  <textarea v-model="item.rewardSuggestion" placeholder="请提出该优势里的奖励建议" class="textarea" auto-height />
                </view>

                <!-- 删除整套记录 -->
                <view v-if="rewardRecords.length > 1" class="del-btn" @click="removeRecordReward(idx)">
                  删除本记录
                </view>
              </view>

              <!-- 添加整套记录 -->
              <button class="add-btn" @click="addRecordReward">+ 添加事例</button>

              <uni-popup ref="personPopupReward" type="bottom" :mask-click="true">
                <view class="popup-body">
                  <picker-view :value="[personIndexReward]" @change="onPersonPickerChangeReward" style="height: 400rpx">
                    style="height: 400rpx">
                    <picker-view-column>
                      <view v-for="p in allPersons" :key="p.userId" class="picker-item">{{ p.nickName }}</view>
                    </picker-view-column>
                  </picker-view>
                  <button class="popup-btn" @click="confirmPersonReward">确定</button>
                </view>
              </uni-popup>


            </uni-collapse-item>
          </uni-collapse>
        </uni-card>

        <!-- 整体评价 -->
        <uni-card :is-shadow="true" :shadow="shadow">
          <uni-collapse :accordion="false" :value="['group3']">
            <uni-collapse-item title="整体评价" name="group3" :show-animation="true">
              <template v-slot:title>
                <view class="collapse-title">
                  <text>整体评价</text>
                  <text class="collapse-summary" v-if="formData.partCategoryText">{{ formData.partCategoryText }} ·
                    {{ formData.customLocation || formData.locationText }}</text>
                </view>
              </template>




              <!-- 星级评分 -->
              <view class="star-rating">
                <view v-for="i in 5" :key="i" @click="setRating(i)" class="star">
                  <uni-icons :type="i <= currentRating ? 'star-filled' : 'star'" size="30"
                    :color="i <= currentRating ? '#FFCA3E' : '#C0C0C0'" />
                </view>
                <text class="score-text">{{ currentRating.toFixed(1) }} / 5.0</text>
              </view>

              <uni-forms-item label="总体评价" name="comprehensiveEvaluation">
                <uni-easyinput type="textarea" v-model="formData.comprehensiveEvaluation"
                  placeholder="请对本次巡检的整体情况进行评价" />
              </uni-forms-item>


            </uni-collapse-item>
          </uni-collapse>
        </uni-card>



        <!-- 附件上传 -->
        <uni-card :is-shadow="true">
          <uni-collapse :accordion="false" :value="['group4']">
            <uni-collapse-item title="附件上传 (可选)" name="group4" :show-animation="true" :lazy="false">
              <uni-file-picker ref="fpRef" v-model="formData.baseAttachmentList" :limit="8" file-mediatype="all"
                file-extname="jpg,jpeg,png,pdf,doc,docx" mode="list" @select="handleUploadSuccess"
                @delete="handleDelete">

                <template #default>
                  <view class="upload-slot">
                    <uni-icons type="cloud-upload" size="36" color="#999" />
                    <text class="tip">点击或拖拽文件到此处上传</text>
                    <text class="sub-tip">支持 JPG、PNG、PDF、Word，最多 8 个</text>
                  </view>
                </template>
              </uni-file-picker>
            </uni-collapse-item>
          </uni-collapse>
        </uni-card>
        <!-- 提交按钮 -->
        <button type="primary" class="submit-btn" @click="submitForm">提交上报</button>
        <!-- </scroll-view> -->
      </uni-forms>
      <!-- 自定义 TabBar（固定底部） -->
      <!-- <custom-tabbar style="
        position: fixed;
        bottom: 0;
        width: 100%;
        height: 50px;
        z-index: 1000;
        background: #fff;
      " /> -->
    </view>
  </home-container>
</template>

<script>
import HomeContainer from "@/components/HomeContainer.vue";

import CustomTabbar from '@/components/custom-tabbar.vue';
import { treeSelectByType } from "@/api/system/common"
import { submitInspection } from "@/api/check/checkReward";
import { getCheckProject } from "@/api/check/checkProject";
import { getUserList } from "@/api/system/user";
import config from '@/config'
import { getToken } from '@/utils/auth'
import { getUserProfile } from "@/api/system/user"





export default {
  components: { CustomTabbar, HomeContainer },

  computed: {
    currentUser() {
      return this.$store.state.user;
    },
    bigOptions() {
      return this.categoryTree.map(item => item.label);
    }
  },
  data() {
    return {
      // 阴影效果配置
      shadow: '0 2px 6px rgba(0, 0, 0, 0.1)',
      currentRating: 5.0,

      // 表单数据
      formData: {
        // 安检员信息
        checkerId: this.$store.state.user.id,
        checkerName: this.$store.state.user.name,
        checkTime: this.formatDateTime(new Date()),
        positionText: '安检员',
        securityLocationText: 'T3航站楼',
        documentName: '',
        comprehensiveEvaluation: '',
        type: '',
        // 文件
        baseAttachmentList: []
      },
      //负面问题记录
      // 大类 → 小类 映射
      // bigOptions: [],
      // smallMap: {
      //   0: ['违规操作', '未按流程检查', '漏检', '携带违禁品'],
      //   1: ['机器故障', '系统错误'],
      //   2: ['误操作', '未及时记录'],
      //   3: ['其他'],
      // },
      categoryTree: [],
      allPersons: [],
      records: [
        {
          categoryCodeOne: '',
          categoryNameOne: '无',
          categoryCodeTwo: '无',
          categoryNameTwo: '无',
          problemDescription: '',
          checkUserList: [],
          sourceId: 111111,
          projectCode: '无',
          type: '无',
          projectName: '无',
          typeDesc: '无',
          evaluationType: '无',
          evaluationTypeDesc: '无',
          //处罚
          evaluationType: 0
        },
      ],
      showPersonPicker: false,
      curRecordIndex: 0,
      personIndex: 0,
      //优秀事例记录
      rewardRecords: [
        {
          categoryCodeOne: '',
          categoryNameOne: '无',
          categoryCodeTwo: '无',
          categoryNameTwo: '无',
          problemDescription: '',
          checkUserList: [],
          sourceId: 111111,
          projectCode: '无',
          type: '无',
          projectName: '无',
          typeDesc: '无',
          evaluationType: '无',
          evaluationTypeDesc: '无',
          //奖励
          evaluationType: 1
        },
      ],
      showPersonPicker: false,
      curRecordIndexReward: 0,
      personIndexReward: 0,
      //文件
      shadow: '0 2px 8px rgba(0,0,0,.12)',



      // 验证规则
      rules: {
        checkTime: {
          rules: [{ required: true, errorMessage: '请选择查获时间' }]
        },
        type: {                           // 部位类别/类型
          rules: [{ required: true, errorMessage: '请选择部位类别/类型' }]
        },
        comprehensiveEvaluation: {        // 总体评价
          rules: [
            { required: true, errorMessage: '请填写总体评价' },
            { maxLength: 500, errorMessage: '评价不能超过 500 字' }
          ]
        },

        /* 星级评分（整体评价） */
        currentRating: {
          rules: [
            { required: true, errorMessage: '请给出安检工作评分' },
            { format: 'number', minimum: 1, maximum: 5, errorMessage: '评分需在 1~5 之间' }
          ]
        },


      },



      typeData: [],


      partTypeData: [],




      // 其他数据
      startDate: '2020-01-01',
      endDate: '2030-12-31',

    }
  },
  onLoad() {
    this.getUser()


    this.initPageData();

  },
  methods: {
    // 封装上传
    uploadFile(event) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: `${config.baseUrl}/common/upload`,
          filePath: event.tempFilePaths[0], // 取第一个文件
          name: 'file',
          header: { Authorization: 'Bearer ' + getToken() },
          formData: {
            // 可添加其他参数
          },
          success: (res) => resolve(JSON.parse(res.data)),
          fail: reject
        });
      });

    },
    setRating(rating) {
      this.currentRating = rating
    },
    smallOptions(bigIndex) {
      if (
        !Array.isArray(this.categoryTree) ||
        typeof bigIndex !== 'number' ||
        bigIndex < 0 ||
        bigIndex >= this.categoryTree.length
      ) {
        return [];
      }
      const bigItem = this.categoryTree[bigIndex];
      return bigItem?.children?.map(child => child.label) || [];
    },
    async initPageData() {
      try {
        uni.showLoading({ title: '加载中...', mask: true });
        const [checkProject, userList] = await Promise.all([
          treeSelectByType("CHECK_CATEGORY", 2),
          getUserList()
        ]);
        this.categoryTree = checkProject.data || [];
        this.allPersons = (userList.rows || []).map(u => ({
          ...u,
          deptId: u.dept?.deptId,
          deptName: u.dept?.deptName
        }));

        uni.hideLoading();
      } catch (err) {
        uni.hideLoading();
        uni.showToast({ title: '加载失败', icon: 'none' });
        console.error('初始化数据失败:', err);
      }
    },
    /* 上传成功回调：将返回值格式化后塞进 v-model */
    async handleUploadSuccess(res) {

      const file = await this.uploadFile(res)
      console.log("file", file)
      console.log("上传成功====");
      this.formData.baseAttachmentList.push({
        url: file.url,
        name: file.newFileName,
        extname: file.newFileName.split('.').pop()
      });
    },

    /* 删除文件 */
    handleDelete({ tempFile }) {
      console.log("删除成功====")

      this.formData.baseAttachmentList = this.formData.baseAttachmentList.filter(f => f.url !== tempFile.url);
    },
    async getUser() {
      const data = await getUserProfile();
      this.formData.securityLocationText = data.data.dept.deptName
      this.formData.positionText = data.postGroup
    },



    //优秀实例
    onPersonPickerChange(e) {
      // e.detail.value 是数组，第一项就是索引
      this.personIndex = e.detail.value[0];
    },
    onPersonPickerChangeReward(e) {
      // e.detail.value 是数组，第一项就是索引
      this.personIndexReward = e.detail.value[0];
    },
    // smallOptions(bigIndex) {
    //   return this.smallMap[bigIndex] || [];
    // },

    onBigChange(idx, val) {
      const bigItem = this.categoryTree[val];
      this.records[idx].categoryCodeOne = val;
      this.records[idx].categoryNameOne = bigItem?.label || '无';
      this.records[idx].categoryCodeTwo = null;
      this.records[idx].categoryNameTwo = '无';
    },
    onBigChangeReward(idx, val) {
      const bigItem = this.categoryTree[val];
      this.rewardRecords[idx].categoryCodeOne = val;
      this.rewardRecords[idx].categoryNameOne = bigItem?.label || '无';
      this.rewardRecords[idx].categoryCodeTwo = null;
      this.rewardRecords[idx].categoryNameTwo = '无';
    },
    addRecord() {
      this.records.push({


        categoryCodeOne: '',
        categoryNameOne: '无',
        categoryCodeTwo: '无',
        categoryNameTwo: '无',
        problemDescription: '',
        checkUserList: [],
        sourceId: 111111,
        projectCode: '无',
        type: '无',
        projectName: '无',
        typeDesc: '无',
        evaluationType: '无',
        evaluationTypeDesc: '无',
        //处罚
        evaluationType: 0
      });
    },
    addRecordReward() {
      this.rewardRecords.push({
        categoryCodeOne: '',
        categoryNameOne: '无',
        categoryCodeTwo: '无',
        categoryNameTwo: '无',
        problemDescription: '',
        checkUserList: [],
        sourceId: 111111,
        projectCode: '无',
        type: '无',
        projectName: '无',
        typeDesc: '无',
        evaluationType: '无',
        evaluationTypeDesc: '无',
        //奖励
        evaluationType: 1

      });
    },
    removeRecord(idx) {
      this.records.splice(idx, 1);
    },
    removeRecordReward(idx) {
      this.rewardRecords.splice(idx, 1);
    },
    openPersonPicker(idx) {
      this.curRecordIndex = idx;
      this.$nextTick(() => {
        this.$refs.personPopup.open();
      });
    },
    openPersonPickerReward(idx) {
      this.curRecordIndexReward = idx;
      this.$nextTick(() => {
        this.$refs.personPopupReward.open();
      });
    },
    confirmPerson() {
      const p = this.allPersons[this.personIndex];
      console.log("p1", p);
      console.log("p11", this.records)
      console.log(this.records[this.curRecordIndex])

      if (!this.records[this.curRecordIndex].checkUserList.includes(p)) {
        this.records[this.curRecordIndex].checkUserList.push(p);
      }
      this.$refs.personPopup.close();
    },
    confirmPersonReward() {
      const p = this.allPersons[this.personIndexReward];
      console.log("p2", p);
      console.log("p22", this.rewardRecords)
      console.log(this.rewardRecords[this.curRecordIndexReward])

      if (!this.rewardRecords[this.curRecordIndexReward].checkUserList.includes(p)) {
        this.rewardRecords[this.curRecordIndexReward].checkUserList.push(p);
      }
      this.$refs.personPopupReward.close();
    },
    removePerson(idx, p) {
      this.records[idx].checkUserList = this.records[idx].checkUserList.filter(i => i !== p);
    },
    removePersonReward(idx, p) {
      this.rewardRecords[idx].checkUserList = this.rewardRecords[idx].checkUserList.filter(i => i !== p);
    },


    // 安检位置变化
    onLocationChange(e) {
      // this.formData.securityLocation = e.detail.value[1]?.value || '';
      this.formData.securityLocationText = e.detail.value[1]?.text || e.detail.value[0]?.text || '';
    },

    // 安检岗位变化
    onPositionChange(e) {
      // this.formData.position = e.detail.value[1]?.value || '';
      this.formData.positionText = e.detail.value[1]?.text || e.detail.value[0]?.text || '';
    },





    // 违禁品类别变化
    onCategoryChange(e) {
      this.formData.forbiddenCategory = e.detail.value[0].value;
      this.formData.forbiddenCategoryText = e.detail.value[0].text;
      this.formData.forbiddenType = '';
      this.formData.forbiddenTypeText = '';

      // 根据类别加载类型数据
      if (this.formData.forbiddenCategory === 'dangerous') {
        this.typeData = [
          { text: '易燃物品', value: 'flammable' },
          { text: '爆炸物', value: 'explosive' },
          { text: '有毒物质', value: 'toxic' }
        ];
        this.formData.forbiddenName = '危险品';
      } else if (this.formData.forbiddenCategory === 'forbidden') {
        this.typeData = [
          { text: '刀具', value: 'knife' },
          { text: '钝器', value: 'blunt' },
          { text: '其他武器', value: 'weapon' }
        ];
        this.formData.forbiddenName = '违禁品';
      } else {
        this.typeData = [
          { text: '液体', value: 'liquid' },
          { text: '凝胶', value: 'gel' },
          { text: '喷雾剂', value: 'spray' }
        ];
        this.formData.forbiddenName = '限制物品';
      }
    },

    // 违禁品类型变化
    onTypeChange(e) {
      this.formData.forbiddenType = e.detail.value[0].value;
      this.formData.forbiddenTypeText = e.detail.value[0].text;
      this.formData.forbiddenName = this.formData.forbiddenName + ' - ' + e.detail.value[0].text;
    },



    // 部位类别变化
    onPartCategoryChange(e) {
      this.formData.partCategory = e.detail.value[0].value;
      this.formData.partCategoryText = e.detail.value[0].text;
      this.formData.partType = '';
      this.formData.partTypeText = '';
      this.formData.customLocation = '';

      // 根据部位类别加载类型数据
      if (this.formData.partCategory === 'body') {
        this.partTypeData = [
          { text: '口袋', value: 'pocket' },
          { text: '腰带', value: 'belt' },
          { text: '鞋底', value: 'shoe' }
        ];
      } else if (this.formData.partCategory === 'luggage') {
        this.partTypeData = [
          { text: '夹层', value: 'interlayer' },
          { text: '侧袋', value: 'sidepocket' },
          { text: '主仓', value: 'main' }
        ];
      } else {
        this.partTypeData = [
          { text: '外层', value: 'outer' },
          { text: '内层', value: 'inner' },
          { text: '特殊部位', value: 'special' }
        ];
      }
    },

    // 部位类型变化
    onPartTypeChange(e) {
      this.formData.partType = e.detail.value[0].value;
      this.formData.partTypeText = e.detail.value[0].text;
    },





    // 是否有意隐匿选择
    bindConcealChange(e) {
      this.formData.isConcealed = e.detail.value;
    },
    formatDateTime(date) {
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0');
      const d = String(date.getDate()).padStart(2, '0');
      const h = String(date.getHours()).padStart(2, '0');
      const mm = String(date.getMinutes()).padStart(2, '0');
      const s = String(date.getSeconds()).padStart(2, '0');
      return `${y}-${m}-${d} ${h}:${mm}:${s}`;
    },

    submitForm() {
      this.$refs.form.validate().then(res => {
        uni.showLoading({ title: '提交中...', mask: true });
        this.submit();
      }).catch(err => {
        console.log('表单验证失败:', err);
      });
    },


    // 提交表单
    async submit() {
      try {

        // uni.showLoading({ title: '提交中...', mask: true });

        // 1. 过滤空记录
        const validRecords = this.records.filter(r =>
          (r.categoryCodeOne !== '' || r.problemDescription.trim() || r.checkUserList.length)
        );
        const validRewards = this.rewardRecords.filter(r =>
          (r.categoryCodeOne !== '' || r.problemDescription.trim() || r.checkUserList.length)
        );

        // 2. 至少有一条
        if (validRecords.length === 0 && validRewards.length === 0) {
          uni.showToast({ title: '请至少填写一条负面问题或优秀事例', icon: 'none' });
          return;
        }

        // 3. 只合并有数据的数组
        const checkProjectItemList = [...validRecords, ...validRewards];
        const payload = {
          ...this.formData,
          baseAttachmentList: this.formData.baseAttachmentList.map(file => ({
            attachmentId: Date.now().toString(36) + Math.random().toString(36).substr(2, 6),
            attachmentUrl: file.url,
            attachmentName: file.name,
            extname: file.extname || file.name.split('.').pop(),
            size: file.size
          })),
          checkProjectItemList,
          scoreTotal: this.currentRating,
          type_desc: '1',
          score: this.currentRating

        };

        await submitInspection(payload);
        uni.showToast({ title: '提交成功', icon: 'success' });
        setTimeout(() => uni.navigateBack(), 1500);
      } catch (e) {
        console.log(e)
        uni.showModal({ content: e.data?.msg || '提交失败', showCancel: false });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.record-container {
  // background-color: #f5f5f5;
  min-height: 100vh;
  padding-top: 180rpx;
}


.form-scroll {
  height: calc(100vh - 50px);
  padding: 1px;
  box-sizing: border-box;
}

/* 卡片样式 */
::v-deep .uni-card {
  margin-bottom: 15px;
  border-radius: 8px;
  overflow: hidden;

  .uni-card__content {
    padding: 0;
  }
}

/* 折叠面板标题 */
.collapse-title {
  display: flex;
  flex-direction: column;
  padding: 12px 15px;

  .collapse-summary {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
  }
}

/* 表单项样式 */
::v-deep .uni-forms-item {
  margin-bottom: 0;
  padding: 0 15px;

  .uni-forms-item__label {
    padding: 12px 0 8px;
    font-size: 14px;
    color: #666;
    width: auto !important;
  }

  .uni-forms-item__content {
    padding: 0 0 12px;
    border-bottom: 1px solid #f0f0f0;
  }

  &:last-child .uni-forms-item__content {
    border-bottom: none;
  }
}

.picker-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;

  .picker-value {
    font-size: 15px;
    color: #333;

    &:empty::after {
      content: attr(placeholder);
      color: #999;
    }
  }

  &.disabled {
    opacity: 0.5;
  }
}

.form-value {
  font-size: 15px;
  color: #333;
  height: 44px;
  line-height: 44px;
}

.number-input {
  display: flex;
  align-items: center;
  height: 44px;

  .input-number {
    flex: 1;
  }

  .unit-picker {
    width: 80px;
    margin-left: 10px;
  }
}

.location-input {
  display: flex;
  height: 44px;

  .picker-box {
    width: 120px;
  }

  .custom-location {
    flex: 1;
    margin-left: 10px;
  }
}

.radio-group {
  display: flex;
  padding: 8px 0;

  .radio-item {
    display: flex;
    align-items: center;
    margin-right: 30px;

    text {
      font-size: 15px;
      color: #333;
      margin-left: 5px;
    }
  }
}

.submit-btn {
  margin-top: 20px;
  width: calc(100% - 30px);
  margin-left: 15px;
  margin-bottom: 80px;
}

/* 底部弹窗样式调整 */
::v-deep .uni-popup__wrapper {
  border-radius: 16px 16px 0 0;

  .uni-popup__wrapper-box {
    max-height: 70vh;
    overflow-y: auto;
  }

  .uni-data-pickerview {
    padding-bottom: 20px;
  }
}

.title-main {
  font-size: 20rpx;
  font-weight: 700;
  color: #000;
  line-height: 1.4;

}

.title-sub {
  font-size: 18rpx;
  color: #666;
}

.no-bg {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

.record-card {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.label {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.label-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.add-person-btn {
  font-size: 44rpx;
  color: #007aff;
  padding: 0 20rpx;
}

.picker-box {
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 30rpx;
}

.textarea {
  width: 100%;
  min-height: 160rpx;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 30rpx;
}

.person-tags {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10rpx;
}

.tag {
  background: #e8f4ff;
  color: #007aff;
  border-radius: 8rpx;
  padding: 6rpx 12rpx;
  margin: 6rpx 8rpx 0 0;
  font-size: 28rpx;
}

.close {
  margin-left: 6rpx;
  color: #e74c3c;
}

.del-btn {
  color: #e74c3c;
  text-align: right;
  margin-top: 20rpx;
  font-size: 28rpx;
}

.add-btn {
  width: 100%;
  background: #007aff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 8rpx;
}

.popup-body {
  padding: 30rpx;
  background: #fff;
}

.popup-btn {
  width: 100%;
  margin-top: 20rpx;
  margin-bottom: 40rpx;
}

.picker-item {
  line-height: 80rpx;
  text-align: center;
  font-size: 32rpx;
}

.upload-slot {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
}

.tip {
  font-size: 28rpx;
  color: #666;
  margin: 16rpx 0 8rpx;
}

.sub-tip {
  font-size: 24rpx;
  color: #999;
}


.rating-container {
  padding: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  display: block;
}

.star-rating {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.star {
  margin-right: 10rpx;
}

.score-text {
  margin-left: 20rpx;
  color: #666;
  font-size: 28rpx;
}

/* 放在本页 style scoped 末尾即可 */
::v-deep {

  /* 日期时间弹窗整体向上抬 40rpx */
  .uni-datetime-picker-popup {
    margin-bottom: 40rpx !important;
  }

  /* 如果使用的是官方组件库，也可再补一条 */
  .uni-popup__wrapper.uni-datetime-picker {
    transform: translateY(-40rpx) !important;
  }
}
</style>