<template>
  <view class="u-page">
    <!-- 核心：将所有 up-form-item 包裹在同一个 up-form 内 -->
    <up-form
        label-position="left"
        :model="workOrderForm"
        ref="workOrderFormRef"
        labelWidth="220rpx"
        :rules="workOrderFormRules"
        :error-type="['message', 'border']"
        class="work-order-form-container"
    >
      <!-- 工单表单容器 -->
      <view class="work-order-form-content commonPageLRpadding">
        <!-- 1. 工单位置（地图选择） -->
        <up-form-item
            label="工单位置"
            prop="workLocation"
            border-bottom
            required
            @click="chooseWorkLocation(); hideKeyboard()"
        >
          <up-input
              v-model="workOrderForm.workLocation"
              border="none"
              readonly
              suffix-icon="map-fill"
              placeholder="点击选择工单位置"
          ></up-input>
        </up-form-item>

        <!-- 2. 道路名称（下拉框：位置选择后才可点击） -->
        <up-form-item
            label="道路名称"
            prop="roadName"
            border-bottom
            required
            @click="workOrderForm.workLocation ? (showRoadName = true, hideKeyboard()) : uni.showToast({title: '请先选择工单位置', icon: 'none'})"
        >
          <up-input
              v-model="workOrderForm.roadName"
              disabled
              disabled-color="#ffffff"
              placeholder="请先选择工单位置"
              border="none"
              :placeholder-style="workOrderForm.workLocation ? '' : 'color:#999;'"
          ></up-input>
          <template #right>
            <up-icon name="arrow-right" size="16" :color="workOrderForm.workLocation ? '#333' : '#999'"></up-icon>
          </template>
        </up-form-item>

        <!-- 3. 工单名称（下拉框） -->
        <up-form-item
            label="工单名称"
            prop="orderName"
            border-bottom
            required
            @click="showOrderName = true; hideKeyboard()"
        >
          <up-input
              v-model="workOrderForm.orderName"
              disabled
              disabled-color="#ffffff"
              placeholder="请选择工单名称"
              border="none"
          ></up-input>
          <template #right>
            <up-icon name="arrow-right" size="16"></up-icon>
          </template>
        </up-form-item>

        <!-- 4. 情况描述（文本域） -->
        <up-form-item
            label="情况描述"
            prop="problemDesc"
            required
        >
          <up-textarea
              placeholder="请输入情况描述（最多150字）"
              v-model="workOrderForm.problemDesc"
              count
              maxlength="150"
              rows="4"
              @blur="() => workOrderFormRef.value?.validateField('problemDesc')"
          ></up-textarea>
        </up-form-item>
      </view>

      <!-- 问题照片：独立一行显示（移入 up-form 内） -->
      <view class="img-upload-wrap">
        <up-form-item label="问题照片" prop="problemImgs" required>
          <up-upload
              :file-list="problemImgsList"
              @after-read="(event) => uploadImgs(event, 'problemImgsList')"
              @delete="(event) => deleteImg(event, 'problemImgsList')"
              multiple
              :max-count="3"
              upload-text="选择问题照片"
          ></up-upload>
        </up-form-item>
      </view>

      <!-- 完成照片：独立一行显示（移入 up-form 内） -->
      <view class="img-upload-wrap">
        <up-form-item label="完成照片" prop="completeImgs" required>
          <up-upload
              :file-list="completeImgsList"
              @after-read="(event) => uploadImgs(event, 'completeImgsList')"
              @delete="(event) => deleteImg(event, 'completeImgsList')"
              multiple
              :max-count="3"
              :sizeType="['compressed']"
              upload-text="选择完成照片"
          ></up-upload>
        </up-form-item>
      </view>

      <!-- 处理结果描述（独立显示，移入 up-form 内） -->
      <view class="handle-result-wrap">
        <up-form-item
            label="处理结果"
            prop="handleResultDesc"
            required
        >
          <up-textarea
              placeholder="请输入处理结果描述（最多200字）"
              v-model="workOrderForm.handleResultDesc"
              count
              maxlength="200"
              rows="4"
              @blur="() => workOrderFormRef.value?.validateField('handleResultDesc')"
          ></up-textarea>
        </up-form-item>
      </view>
    </up-form>

    <!-- 底部提交按钮 -->
    <view class="fixed-bottom-btn-wrap">
      <up-button
          type="primary"
          text="提交工单"
          @click="submitWorkOrder"
          :loading="isSubmitting"
          :disabled="isSubmitting"
      ></up-button>
    </view>

    <!-- 道路名称下拉弹窗 -->
    <up-action-sheet
        :show="showRoadName"
        :actions="roadNameList"
        title="请选择道路名称"
        @close="showRoadName = false"
        @select="handleRoadNameSelect"
    ></up-action-sheet>

    <!-- 工单名称下拉弹窗 -->
    <up-action-sheet
        :show="showOrderName"
        :actions="orderNameList"
        title="请选择工单名称"
        @close="showOrderName = false"
        @select="handleOrderNameSelect"
    ></up-action-sheet>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { UniFormRef, UniActionSheetSelectEvent, UploadFile, UploadDeleteEvent } from '@/uni_modules/uview-plus/types'
// 导入接口
import { getRoadListByLatLng } from '@/api/common'
// 导入统一的多文件上传方法
import { uploadImages } from '@/common/utils/upload';
import { createQuick } from '@/api/quick-order/quick-order'

// ========== 基础变量定义 ==========
// 问题照片列表
const problemImgsList = ref<UploadFile[]>([])
// 完成照片列表
const completeImgsList = ref<UploadFile[]>([])
// 表单Ref
const workOrderFormRef = ref<UniFormRef>(null)
// 提交加载状态
const isSubmitting = ref(false)
// 弹窗显隐控制
const showRoadName = ref(false)
const showOrderName = ref(false)
// 下拉列表数据
const roadNameList = ref<any[]>([])
const orderNameList = ref([
  { name: '绿地卫生', code: 'ORDER001' },
  { name: '设施维修', code: 'ORDER002' },
  { name: '垃圾清理', code: 'ORDER003' }
])

// ========== 工单表单数据 ==========
const workOrderForm = reactive({
  roadId: 0,                     // 道路ID
  roadName: '',                  // 道路名称
  workLocation: '',              // 工单位置
  orderName: '',                 // 工单名称
  problemDesc: '',               // 情况描述
  handleResultDesc: '',          // 处理结果描述
  lat: 0,                        // 纬度
  lon: 0                         // 经度
})

// ========== 表单校验规则 ==========
const workOrderFormRules = reactive({
  workLocation: [
    { type: 'string', required: true, message: '请选择工单位置', trigger: ['change', 'blur'] }
  ],
  roadName: [
    { type: 'string', required: true, message: '请选择道路名称', trigger: ['change', 'blur'] }
  ],
  orderName: [
    { type: 'string', required: true, message: '请选择工单名称', trigger: ['change', 'blur'] }
  ],
  problemDesc: [
    { type: 'string', required: true, message: '请输入情况描述', trigger: ['change', 'blur'] },
    { type: 'string', min: 3, max: 150, message: '情况描述需3-150字', trigger: ['change', 'blur'] }
  ],
  problemImgs: [
    { required: true, message: '请上传问题照片', trigger: 'change' }
  ],
  completeImgs: [
    { required: true, message: '请上传完成照片', trigger: 'change' }
  ],
  handleResultDesc: [
    { type: 'string', required: true, message: '请输入处理结果描述', trigger: ['change', 'blur'] },
    { type: 'string', min: 3, max: 200, message: '处理结果需3-200字', trigger: ['change', 'blur'] }
  ]
})

// ========== 方法定义 ==========
/**
 * 删除图片
 */
const deleteImg = (event: UploadDeleteEvent, type: string) => {
  console.log('删除图片事件：', event, '类型：', type)
  if (type === 'problemImgsList') {
    problemImgsList.value.splice(event.index, 1)
  } else if (type === 'completeImgsList') {
    completeImgsList.value.splice(event.index, 1)
  }
  uni.showToast({ title: '图片删除成功', icon: 'success' })
}

/**
 * 上传图片
 */
const uploadImgs = async (event: { file: UploadFile | UploadFile[] }, type: string) => {
  console.log('上传图片事件：', event, '类型：', type)
  const fileList = Array.isArray(event.file) ? event.file : [event.file]
  const targetImgList = type === 'problemImgsList' ? problemImgsList : completeImgsList

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

  try {
    const uploadResultUrls = await uploadImages({
      filePaths: filePaths,
      ignoreError: true
    })
    console.log('上传成功的URL列表：', uploadResultUrls)

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

    if (uploadResultUrls.length < fileList.length) {
      const failCount = fileList.length - uploadResultUrls.length
      for (let i = uploadResultUrls.length; i < fileList.length; i++) {
        if (targetImgList.value[startIndex + i]) {
          targetImgList.value.splice(startIndex + i, 1, {
            ...fileList[i],
            status: 'failed' as const,
            message: '上传失败'
          })
        }
      }
      uni.showToast({ title: `成功上传${uploadResultUrls.length}张，失败${failCount}张`, icon: 'none' })
    } else {
      uni.showToast({ title: `成功上传${fileList.length}张图片`, icon: 'success' })
    }
  } catch (err) {
    console.error('图片上传失败：', err)
    for (let i = 0; i < fileList.length; i++) {
      if (targetImgList.value[startIndex + i]) {
        targetImgList.value.splice(startIndex + i, 1, {
          ...fileList[i],
          status: 'failed' as const,
          message: '上传失败'
        })
      }
    }
    uni.showToast({ title: '图片上传失败，请重试', icon: 'none' })
  }
}

/**
 * 选择工单位置
 */
const chooseWorkLocation = () => {
  if (isSubmitting.value) return

  uni.authorize({
    scope: 'scope.userLocation',
    success: () => {
      uni.chooseLocation({
        success: async (res) => {
          workOrderForm.roadName = ''
          workOrderForm.roadId = 0
          roadNameList.value = []

          workOrderForm.workLocation = res.name
          workOrderForm.lat = res.latitude
          workOrderForm.lon = res.longitude

          workOrderFormRef.value?.validateField('workLocation')
          workOrderFormRef.value?.validateField('roadName')

          try {
            uni.showLoading({ title: '获取道路名称中...' })
            const roadRes = await getRoadListByLatLng({
              companyCode: 'sls',
              latitude: res.latitude,
              longitude: res.longitude
            })
            uni.hideLoading()

            if (Array.isArray(roadRes)) {
              roadNameList.value = roadRes.map((item: any) => ({
                name: item.roadName || '',
                code: item.roadCode || '',
                id: item.roadId || 0
              }))
            } else {
              roadNameList.value = [{ name: '未查询到道路名称', code: '', id: 0 }]
              uni.showToast({ title: '未查询到该位置的道路信息', icon: 'none' })
            }
          } catch (err) {
            uni.hideLoading()
            console.error('获取道路名称失败：', err)
            uni.showToast({ title: '获取道路名称失败，请重试', icon: 'none' })
            roadNameList.value = [{ name: '获取失败，请重新选择位置', code: '', id: 0 }]
          }
        },
        fail: (err) => {
          console.error('选择位置失败：', err)
          uni.showToast({ title: '选择位置失败：' + err.errMsg, icon: 'none' })
        }
      })
    },
    fail: (err) => {
      console.error('位置授权失败：', err)
      uni.showModal({
        title: '权限提示',
        content: '需要获取您的位置权限才能选择工单位置，请前往设置开启',
        confirmText: '去设置',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            uni.openSetting({
              success: (settingRes) => {
                if (settingRes.authSetting['scope.userLocation']) {
                  uni.showToast({ title: '权限已开启，请重新选择位置', icon: 'none' })
                }
              }
            })
          }
        }
      })
    }
  })
}

/**
 * 选择道路名称
 */
const handleRoadNameSelect = (e: UniActionSheetSelectEvent) => {
  console.log('选择道路名称：', e)
  workOrderForm.roadName = e.name
  workOrderForm.roadId = e.code
  showRoadName.value = false
  workOrderFormRef.value?.validateField('roadName')
}

/**
 * 选择工单名称
 */
const handleOrderNameSelect = (e: UniActionSheetSelectEvent) => {
  workOrderForm.orderName = e.name
  showOrderName.value = false
  workOrderFormRef.value?.validateField('orderName')
}

/**
 * 隐藏键盘
 */
const hideKeyboard = () => {
  uni.hideKeyboard()
}

/**
 * 提取图片URL数组
 */
const getImgUrlList = (imgList: UploadFile[]) => {
  console.log('提取图片URL：', imgList)
  return imgList.filter(item => item.status === 'success').map(item => item.url)
}

/**
 * 校验上传图片
 */
const validateUploadImgs = () => {
  const hasValidProblemImgs = problemImgsList.value.some(item => item.status === 'success')
  if (!hasValidProblemImgs) {
    uni.showToast({ title: '请上传至少1张问题照片', icon: 'none' })
    workOrderFormRef.value?.validateField('problemImgs')
    return false
  }

  const hasValidCompleteImgs = completeImgsList.value.some(item => item.status === 'success')
  if (!hasValidCompleteImgs) {
    uni.showToast({ title: '请上传至少1张完成照片', icon: 'none' })
    workOrderFormRef.value?.validateField('completeImgs')
    return false
  }

  return true
}

/**
 * 提交工单
 */
const submitWorkOrder = async () => {
  if (isSubmitting.value) {
    uni.showToast({ title: '提交中，请稍候', icon: 'none' })
    return
  }

  try {
    isSubmitting.value = true

    if (!validateUploadImgs()) {
      isSubmitting.value = false
      return
    }

    const valid = await new Promise<boolean>((resolve) => {
      workOrderFormRef.value?.validate((isValid, invalidFields) => {
        console.log('校验失败的字段：', invalidFields)
        resolve(isValid)
      })
    })

    if (!valid) {
      const firstInvalidField = Object.keys(workOrderFormRef.value?.invalidFields || {})[0]
      if (firstInvalidField) {
        const el = document.querySelector(`[prop="${firstInvalidField}"]`)
        el?.scrollIntoView({ behavior: 'smooth', block: 'center' })
      }
      uni.showToast({ title: '表单填写不完整，请检查', icon: 'none' })
      isSubmitting.value = false
      return
    }

    const submitData = {
      roadId: workOrderForm.roadId,
      roadName: workOrderForm.roadName,
      imgs: getImgUrlList(problemImgsList.value),
      longRangeImgList: getImgUrlList(completeImgsList.value),
      remark: workOrderForm.problemDesc,
      handleResultDesc: workOrderForm.handleResultDesc,
      latLonType: 2,
      lat: workOrderForm.lat,
      lon: workOrderForm.lon,
      lonLatAddress: workOrderForm.workLocation,
      pressingType: 2,
      orderName: workOrderForm.orderName,
      sourceId: 1,
      sourceName: '园林',
      thirdWorkNo: ''
    }

    console.log('提交工单数据：', submitData)
    await createQuick(submitData)
    uni.showToast({ title: '工单提交成功', icon: 'success' })

  } catch (error) {
    console.error('提交工单失败：', error)
    uni.showToast({ title: '提交失败，请重试', icon: 'none' })
  } finally {
    isSubmitting.value = false
  }
}

// ========== 页面挂载初始化 ==========
onMounted(() => {
  if (workOrderFormRef.value && !workOrderFormRef.value.rules) {
    workOrderFormRef.value.setRules(workOrderFormRules)
    console.log('工单表单规则初始化完成')
  }
})
</script>

<style lang="scss" scoped>
// 全局页面样式
.u-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 100rpx;
}

// 表单容器（新增：包裹整个表单）
.work-order-form-container {
  width: 100%;
}

// 工单表单内容容器
.work-order-form-content {
  background: #fff;
  padding: 20rpx;
  box-sizing: border-box;
  margin-bottom: 20rpx;
}

// 图片上传区域
.img-upload-wrap {
  background: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;

  :deep(.u-upload) {
    --u-upload-item-width: 200rpx;
    --u-upload-item-height: 200rpx;
  }

  :deep(.u-form-item) {
    margin-bottom: 0;
  }
}

// 处理结果描述区域
.handle-result-wrap {
  background: #fff;
  padding: 0 20rpx 20rpx;
  margin-bottom: 20rpx;
  border-top: 1px solid #f0f0f0;

  :deep(.u-form-item) {
    --u-form-item-label-font-size: 28rpx;
    --u-form-item-content-font-size: 28rpx;
  }

  :deep(.u-textarea) {
    --u-textarea-font-size: 28rpx;
    padding: 10rpx 0;
  }
}

// 提交按钮区域
.fixed-bottom-btn-wrap {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  :deep(.u-button) {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 32rpx;
    border-radius: 8rpx;
  }
}

// Label样式
:deep(.u-form-item__label) {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  line-height: 1.4;
}

// 表单基础样式
:deep(.u-form-item) {
  --u-form-item-label-font-size: 28rpx;
  --u-form-item-content-font-size: 28rpx;
  margin-bottom: 10rpx;
}

:deep(.u-input) {
  --u-input-font-size: 28rpx;
}

:deep(.u-textarea) {
  --u-textarea-font-size: 28rpx;
  padding: 10rpx 0;
}

:deep(.u-action-sheet) {
  z-index: 9999 !important;
}

// 错误提示样式
:deep(.u-form-item__error-message) {
  font-size: 24rpx !important;
  color: #f56c6c !important;
  margin-top: 5rpx !important;
}

:deep(.u-form-item--error .u-input__wrap) {
  border-color: #f56c6c !important;
}
</style>