<template>
  <view class="u-page">
    <!-- 工单表单容器 -->
    <view class="work-order-form-content commonPageLRpadding">
      <!-- uview-plus表单（Vue3 适配） -->
      <up-form
          label-position="left"
          :model="workOrderForm"
          ref="workOrderFormRef"
          labelWidth="220rpx"
          :rules="workOrderFormRules"
      >
        <!-- 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"
          ></up-textarea>
        </up-form-item>
      </up-form>

      <!-- 道路名称下拉弹窗 -->
      <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>

    <!-- 图片分类标签 -->
    <up-tabs :list="imgTabList" @click="switchImgTab"></up-tabs>

    <!-- 图片上传组件（根据选中标签显示对应列表） -->
    <view class="img-upload-wrap" v-if="activeImgTab === '1'">
      <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>
    <view class="img-upload-wrap" v-else>
      <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>

    <!-- 处理结果描述（独立显示） -->
    <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"
        ></up-textarea>
      </up-form-item>
    </view>

    <!-- 底部提交按钮 -->
    <view class="fixed-bottom-btn-wrap">
      <up-button
          type="primary"
          text="提交工单"
          @click="submitWorkOrder"
          :loading="isSubmitting"
          :disabled="isSubmitting"
      ></up-button>
    </view>
  </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 imgTabList = ref([
  { name: '问题照片', id: '1' },
  { name: '完成照片', id: '2' }
])
// 激活的图片标签（默认选中问题照片）
const activeImgTab = ref('1')
// 问题照片列表
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                         // 经度
})

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

// ========== 方法定义（语义化命名 + 修复逻辑） ==========
/**
 * 删除图片
 * @param event 删除事件
 * @param type 图片类型（problemImgsList/completeImgsList）
 */
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' })
}

/**
 * 上传图片（单/多图统一逻辑）
 * @param event 上传事件
 * @param type 图片类型（problemImgsList/completeImgsList）
 */
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

  // 1. 提取文件路径
  const filePaths = fileList.map(item => item.url)
  // 2. 添加上传中临时项
  const tempItems: UploadFile[] = fileList.map(item => ({
    ...item,
    status: 'uploading' as const,
    message: '上传中'
  }))
  const startIndex = targetImgList.value.length
  targetImgList.value.push(...tempItems)

  try {
    // 3. 调用统一上传方法
    const uploadResultUrls = await uploadImages({
      filePaths: filePaths,
      ignoreError: true
    })
    console.log('上传成功的URL列表：', uploadResultUrls)

    // 4. 更新成功状态
    uploadResultUrls.forEach((url, index) => {
      if (targetImgList.value[startIndex + index]) {
        targetImgList.value.splice(startIndex + index, 1, {
          ...fileList[index],
          status: 'success' as const,
          message: '',
          url: url
        })
      }
    })

    // 5. 处理失败项
    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' })
  }
}

/**
 * 切换图片标签
 * @param item 标签项
 */
const switchImgTab = (item: { name: string; id: string }) => {
  console.log('切换图片标签：', item)
  activeImgTab.value = item.id
}

/**
 * 选择工单位置（地图）- 核心修改：清空道路名称
 */
const chooseWorkLocation = () => {
  if (isSubmitting.value) return

  uni.authorize({
    scope: 'scope.userLocation',
    success: () => {
      uni.chooseLocation({
        success: async (res) => {
          // ========== 核心新增：清空道路名称相关数据 ==========
          workOrderForm.roadName = ''  // 清空道路名称
          workOrderForm.roadId = 0     // 清空道路ID
          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' })
                }
              }
            })
          }
        }
      })
    }
  })
}

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

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

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

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

/**
 * 校验上传图片（兜底校验）
 * @returns 是否校验通过
 */
const validateUploadImgs = () => {
  // 修复：补充返回值，避免函数无返回
  if (activeImgTab.value === '1') {
    const hasValidImgs = problemImgsList.value.some(item => item.status === 'success')
    if (!hasValidImgs) {
      uni.showToast({ title: '请上传至少1张问题照片', icon: 'none' })
      return false
    }
  } else {
    const hasValidcompleteImgs = completeImgsList.value.some(item => item.status === 'success')
    if (!hasValidcompleteImgs) {
      uni.showToast({ title: '请上传至少1张完成照片', icon: 'none' })
      return false
    }
  }
  return true
}

/**
 * 提交工单（修复核心：await位置 + 表单Ref名称错误）
 */
const submitWorkOrder = async () => {
  if (isSubmitting.value) {
    uni.showToast({ title: '提交中，请稍候', icon: 'none' })
    return
  }

  try {
    isSubmitting.value = true

    // 修复1：兜底校验图片
    if (!validateUploadImgs()) {
      isSubmitting.value = false
      return
    }

    // 修复2：使用正确的表单Ref名称（workOrderFormRef 而非 uFormRef）
    // 修复3：将validate转为Promise形式，配合async/await
    const valid = await new Promise((resolve) => {
      workOrderFormRef.value?.validate((isValid) => {
        resolve(isValid)
      })
    })

    if (!valid) {
      uni.showToast({ title: '表单校验失败，请检查必填项', icon: 'none' })
      isSubmitting.value = false
      return
    }

    // 构造提交数据
    const submitData = {
      roadId: workOrderForm.roadId,
      roadName: workOrderForm.roadName,
      imgs: getImgUrlList(problemImgsList.value),          // 问题照片URL数组
      longRangeImgList: getImgUrlList(completeImgsList.value), // 完成照片URL数组
      remark: activeImgTab.value === '2' ? workOrderForm.handleResultDesc : workOrderForm.problemDesc,
      latLonType: 2,
      lat: workOrderForm.lat,
      lon: workOrderForm.lon,
      lonLatAddress: workOrderForm.workLocation,
      pressingType: 2,
      orderName: workOrderForm.orderName,
      sourceId: 1,
      sourceName: '园林',
      thirdWorkNo: ''
    }

    console.log('提交工单数据：', submitData)
    // 修复4：await 现在在async函数中，可正常使用
    await createQuick(submitData)
    uni.showToast({ title: '工单提交成功', icon: 'success' })

    // 可选：提交成功后重置表单
    // problemImgsList.value = []
    // completeImgsList.value = []
    // Object.assign(workOrderForm, {
    //   roadId: 0, roadName: '', workLocation: '', orderName: '',
    //   problemDesc: '', handleResultDesc: '', lat: 0, lon: 0
    // })
    // workOrderFormRef.value?.clearValidate()

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

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

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

// 工单表单容器
.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 { // 修复：原样式类名是submit-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-tabs) {
  background: #fff;
}
</style>