<template>
  <view class="u-page">
    <!-- 原有模板内容不变，仅调整表单校验相关配置 -->
    <view class="inspect-form-content commonPageLRpadding">
      <up-form
          label-position="left"
          :model="inspectForm"
          ref="inspectFormRef"
          labelWidth="200rpx"
      >
        <!-- 1. 巡查描述 -->
        <up-form-item
            label="巡查描述"
            prop="content"
            class="form-item"
            required
        >
          <up-textarea
              v-model.trim="inspectForm.content"
              placeholder="请输入巡查描述"
              maxlength="200"
              count
          ></up-textarea>
        </up-form-item>

        <!-- 2. 上传图片 -->
        <up-form-item
            label="上传图片"
            prop="images"
            required
            border-bottom
            class="form-item"
        >
          <up-upload
              :file-list="imagesList"
              @after-read="(event) => uploadImgs(event)"
              @delete="(event) => deleteImg(event)"
              @on-exceed="handleExceed"
              multiple
              :max-count="3"
              upload-text="选择图片"
              del-color="#ff4d4f"
              class="upload-wrap"
              width="70"
              height="70"
          ></up-upload>
        </up-form-item>

        <!-- 3. 转为工单 -->
        <up-form-item
            label="转为工单"
            prop="isWorkOrder"
            required
            class="form-item"
        >
          <up-radio-group
              v-model="inspectForm.isWorkOrder"
              active-color="#1989fa"
              direction="row"
              class="radio-group"
              @change="handleWorkOrderChange"
          >
            <up-radio
                :custom-style="{marginRight: '40rpx'}"
                v-for="(item, index) in radioList"
                :key="index"
                :label="item.label"
                :name="item.value"
            >
              {{ item.label }}
            </up-radio>
          </up-radio-group>
        </up-form-item>

        <!-- 紧急程度（仍为必填） -->
<!--        v-if="inspectForm.isWorkOrder === '2'"-->
        <up-form-item
            v-if="inspectForm.isWorkOrder === '2'"
            label="紧急程度"
            prop="pressingTypeName"
            border-bottom
            required
            class="form-item"
            @click="handleActionSheetOpen('pressingType')"
        >
          <up-input
              v-model="inspectForm.pressingTypeName"
              disabled
              disabled-color="#ffffff"
              placeholder="请选择紧急程度"
              border="none"

          ></up-input>
          <template #right>
            <up-icon name="arrow-right" size="16"></up-icon>
          </template>
        </up-form-item>

        <!-- 希望完成时间（移除 required 属性，改为非必填） -->
<!--        v-if="inspectForm.isWorkOrder === '2'"-->
        <up-form-item
            v-if="inspectForm.isWorkOrder === '2'"
            label="希望完成时间"
            prop="expectedFinishDate"
            class="form-item"
            @click="show = true;  uni.hideKeyboard()"
        >
        <up-input
            v-model="inspectForm.expectedFinishDate"
            border="none"
            readonly
            placeholder="点击选择时间"
        >


        </up-input>
        <template #right>
          <!-- 核心修复：用view包裹图标，添加双重@click.stop -->
          <view v-if="inspectForm.expectedFinishDate" @click.stop>
            <up-icon
                name="close"
                size="16"
                @click.stop="clearExpectedFinishDate"
            ></up-icon>
          </view>
          <up-icon name="arrow-right" size="16" v-else></up-icon>
        </template>
        </up-form-item>

      </up-form>
    </view>

    <!-- 底部提交按钮 -->
    <view class="fixed-bottom-btn-wrap">
      <up-button
          type="primary"
          text="提交"
          @click="submitInspect"
          :style="{ width: '100%', height: '88rpx', fontSize: '32rpx', borderRadius: 0 }"
      ></up-button>
    </view>

    <!-- 紧急程度下拉弹窗 -->
    <up-action-sheet
        :show="showActionSheet"
        :actions="pressingTypeList"
        title="请选择紧急程度"
        @close="handleActionSheetClose"
        @select="handlePressingTypeSelect"
    ></up-action-sheet>

    <!-- 完成时间选择器 -->
    <up-datetime-picker
        :show="show"
        v-model="datetimeValue"
        mode="datetime"
        :min-date="new Date()"
        @cancel="show = false"
        @confirm="expectedFinishDateConfirm"
    ></up-datetime-picker>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { UniFormRef } from '@/uni_modules/uview-plus/types'
const inspectFormRef = ref<UniFormRef>(null)
</script>

<script lang="ts">
import { uploadImages } from '@/common/utils/upload';
import { inspectionCreate } from  "@/api/patrol-manage/patrol-plan";
import { timeFormat } from '@/uni_modules/uview-plus'

export default {
  data() {
    return {
      imagesList: [],
      radioList: [
        { label: '否', value: '1' },
        { label: '是', value: '2' }
      ],
      pressingTypeList: [],
      inspectForm: {
        content: '',
        isWorkOrder: '1',
        pressingTypeName: '',
        pressingType: '',
        expectedFinishDate: '' // 非必填，可空
      },
      paramsOptins: {},
      showActionSheet: false,
      show: false,
      datetimeValue: Date.now(),
      inspectFormRules: {
        images: [
          {
            required: true,
            message: '请上传图片',
            trigger: 'change',
            validator: (rule, value, callback) => {
              const hasSuccessImg = this.imagesList.some(item => item.status === 'success')
              const imgCount = this.imagesList.filter(item => item.status === 'success').length

              if (!hasSuccessImg || imgCount < 1) {
                callback(new Error('最少需要上传1张图片'))
              } else if (imgCount > 3) {
                callback(new Error('最多只能上传3张图片'))
              } else {
                callback()
              }
            }
          }
        ],
        content: [
          { type: 'string', required: true, message: '请输入工单描述', trigger: ['change'] }
        ],
        isWorkOrder: [
          { type: 'string', required: true, message: '请选择是否转为工单', trigger: ['change'] }
        ],
        pressingTypeName: [
          {
            required: true,
            message: '请选择紧急程度',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.inspectForm.isWorkOrder === '2' && !value) {
                callback(new Error('请选择紧急程度'))
              } else {
                callback()
              }
            }
          }
        ],
        // 关键修改：希望完成时间 移除必填校验，或改为非必填
        expectedFinishDate: [
          {
            // 移除 required: true，改为非必填
            message: '请选择有效的希望完成时间', // 仅当有值时，校验格式（可选）
            trigger: 'change',
            validator: (rule, value, callback) => {
              // 只有当字段有值时，才校验时间格式是否有效
              if (value && !/^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}$/.test(value)) {
                callback(new Error('请选择有效的希望完成时间'))
              } else {
                callback() // 无值时直接通过校验
              }
            }
          }
        ]
      }
    }
  },
  onLoad(option){
    this.paramsOptins = option
    this.getPressingTypeDict()
  },
  onReady() {
    this.$refs.inspectFormRef.setRules(this.inspectFormRules)
  },
  methods: {
    getPressingTypeDict() {
      const dictList = uni.$dict.getDictSimpleList('workorder_pressing_type')
      this.pressingTypeList = uni.$dict.transformLabelValueToNameValue(dictList)
      console.log(this.pressingTypeList)
    },

    handleWorkOrderChange() {
      if (this.inspectForm.isWorkOrder === '1') {
        this.inspectForm.pressingTypeName = ''
        this.inspectForm.pressingType = ''
        this.inspectForm.expectedFinishDate = '' // 清空非必填字段
        this.$refs.inspectFormRef.validateField(['pressingTypeName', 'expectedFinishDate'])
      }
    },


    handleActionSheetOpen(type) {
      uni.hideKeyboard()
      console.log('showActionSheet')
      if (type === 'pressingType') {
        console.log('showActionSheet')
        this.showActionSheet = true
      }
      uni.hideKeyboard()
    },

    handleActionSheetClose() {
      this.showActionSheet = false
    },

    handlePressingTypeSelect(e) {
      console.log(e)
      this.inspectForm.pressingTypeName = e.name
      this.inspectForm.pressingType = e.value
      this.showActionSheet = false
      this.$refs.inspectFormRef.validateField('pressingTypeName')
    },

    expectedFinishDateConfirm(e) {
      this.inspectForm.expectedFinishDate = timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
      this.show = false
      this.$refs.inspectFormRef.validateField('expectedFinishDate')
    },
    // 新增：清除希望完成时间的方法
    clearExpectedFinishDate() {
      this.inspectForm.expectedFinishDate = ''
      // 清除后触发一次字段校验，确保校验状态更新
      this.$refs.inspectFormRef.validateField('expectedFinishDate')
    },

    deleteImg(event) {
      this.imagesList.splice(event.index, 1)
      this.$refs.inspectFormRef.validateField('images')
      uni.showToast({ title: '图片删除成功', icon: 'success' })
    },

    async uploadImgs(event) {
      const fileList = Array.isArray(event.file) ? event.file : [event.file]
      const targetImgList = this.imagesList

      const filePaths = fileList.map(item => item.url)
      const tempItems = fileList.map(item => ({
        ...item,
        status: 'uploading',
        message: '上传中'
      }))
      const startIndex = targetImgList.length
      targetImgList.push(...tempItems)

      try {
        const uploadResultUrls = await uploadImages({
          filePaths: filePaths,
          ignoreError: true
        })

        uploadResultUrls.forEach((url, index) => {
          if (targetImgList[startIndex + index]) {
            targetImgList.splice(startIndex + index, 1, {
              ...fileList[index],
              status: 'success',
              message: '',
              url: url
            })
          }
        })

        if (uploadResultUrls.length < fileList.length) {
          const failCount = fileList.length - uploadResultUrls.length
          uni.showToast({ title: `成功上传${uploadResultUrls.length}张，失败${failCount}张`, icon: 'none' })
        } else {
          uni.showToast({ title: `成功上传${fileList.length}张图片`, icon: 'success' })
        }

        this.$refs.inspectFormRef.validateField('images')
      } catch (err) {
        console.error('图片上传失败：', err)
        for (let i = 0; i < fileList.length; i++) {
          if (targetImgList[startIndex + i]) {
            targetImgList.splice(startIndex + i, 1, {
              ...fileList[i],
              status: 'failed',
              message: '上传失败'
            })
          }
        }
        uni.showToast({ title: '图片上传失败，请重试', icon: 'none' })
        this.$refs.inspectFormRef.validateField('images')
      }
    },

    handleExceed() {
      uni.showToast({ title: '最多只能上传3张图片', icon: 'none' })
    },

    getImgUrlList(imgList) {
      return imgList.filter(item => item.status === 'success').map(item => item.url)
    },

    async submitInspect() {
      console.log('当前选择是否转为工单：', this.inspectForm.isWorkOrder)
      try {
        await this.$refs.inspectFormRef.validate()
        console.log(this.imagesList)

        // 构造基础提交数据
        const baseSubmitData = {
          "batchNo": this.paramsOptins.batchNo,
          "planNo": this.paramsOptins.planNo,
          "imgHost": "1",
          "imgList": this.getImgUrlList(this.imagesList),
          "inspectionState": this.inspectForm.isWorkOrder,
          "transState": this.inspectForm.isWorkOrder === '1' ? '1' : '2',
          "transWorkNo": "default'",
          "remark": this.inspectForm.content.trim()
        }

        // 构造最终提交数据
        let submitData = { ...baseSubmitData }
        if (this.inspectForm.isWorkOrder === '2') {
          // 紧急程度仍为必填，必传
          submitData.pressingType = this.inspectForm.pressingType
          // 关键修改：仅当希望完成时间有值时，才添加该参数
          if (this.inspectForm.expectedFinishDate) {
            submitData.expectedFinishDate = new Date(this.inspectForm.expectedFinishDate).getTime()
          }
        }

        uni.showLoading({ title: '提交中...' })
        await inspectionCreate(submitData)

        uni.hideLoading()
        uni.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1000
        })

        setTimeout(() => {
          uni.reLaunch({
            url: '/pages-sub/daily/patrol-manage/index'
          })
        }, 1000)

      } catch (error) {
        uni.hideLoading()
        if (!Array.isArray(error)) {
          console.error('巡查表单提交失败：', error)
          uni.showToast({
            title: '提交失败，请重试',
            icon: 'none',
            duration: 2000
          })
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.u-page {
  min-height: 100vh;
}

.inspect-form-content {
  background: #fff;
  padding: 20rpx;
}

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


</style>