<template>
  <view class="page-container">
    <view class="work-order-form-content commonPageLRpadding">
      <up-form
          label-position="left"
          :model="workOrderForm"
          ref="workOrderFormRef"
          labelWidth="190rpx"
      >
        <!-- 1. 工单编号（只读展示，从URL获取） -->
        <up-form-item
            label="工单编号"
            border-bottom
        >
          <up-input
              v-model="workOrderForm.orderNo"
              border="none"
              readonly
              placeholder="暂无工单编号"
          ></up-input>
        </up-form-item>

        <!-- 2. 共同处理人（支持多选） -->
        <up-form-item
            label="共同处理人"
            prop="coProcessorName"
            border-bottom
            @click="handleActionSheetOpen('coProcessor'); hideKeyboard()"
        >
          <up-input
              v-model="workOrderForm.coProcessorName"
              disabled
              disabled-color="#ffffff"
              placeholder="请选择共同处理人（支持多选）"
              border="none"
          ></up-input>
          <template #right>
            <up-icon name="arrow-right" size="16"></up-icon>
          </template>
        </up-form-item>

        <!-- 3. 处理建议（处理情况描述，必填） -->
        <up-form-item
            label="处理情况描述"
            prop="reason"
            required
        >
          <up-textarea
              placeholder="请输入处理情况描述（必填，最多200字）"
              v-model.trim="workOrderForm.reason"
              count
              maxlength="200"
              rows="4"
              border="none"
              @blur="() => workOrderFormRef.validateField('reason')"
          ></up-textarea>
        </up-form-item>


      <!-- Tabs标签栏（图片切换：开始、进行中、结束、人员、材料） -->
      <view class="tabs-wrap commonPageLRpadding" style="margin-top: 30rpx;">
        <up-tabs
            v-model="activeTab"
            :list="tabList"
            line-width="40rpx"
            active-color="#1989fa"
            inactive-color="#666666"

            @change = "imgTabChange"
        ></up-tabs>
        <view class="tab-content" style="padding-top: 20rpx; background: #fff; padding-bottom: 20rpx;">
          <!-- 开始阶段图片上传 -->
          <view v-if="activeTab == 0">
            <up-form-item  prop="startImgs">
              <up-upload
                  :file-list="startImgs.imgList"
                  @after-read="startImgs.uploadImgs"
                  @delete="startImgs.deleteImg"
                  multiple
                  :max-count="startImgs.uploadConfig.maxCount"
                  :upload-text="startImgs.uploadConfig.uploadText"
                  :size-type="startImgs.uploadConfig.sizeType"
              ></up-upload>
            </up-form-item>
          </view>
          <!-- 进行中阶段图片上传 -->
          <view v-if="activeTab == 1">
            <up-form-item  prop="processingImgs">
              <up-upload
                  :file-list="processingImgs.imgList"
                  @after-read="processingImgs.uploadImgs"
                  @delete="processingImgs.deleteImg"
                  multiple
                  :max-count="processingImgs.uploadConfig.maxCount"
                  :upload-text="processingImgs.uploadConfig.uploadText"
                  :size-type="processingImgs.uploadConfig.sizeType"
              ></up-upload>
            </up-form-item>
          </view>
          <!-- 结束阶段图片上传 -->
          <view v-if="activeTab == 2">
            <up-form-item  prop="endImgs">
              <up-upload
                  :file-list="endImgs.imgList"
                  @after-read="endImgs.uploadImgs"
                  @delete="endImgs.deleteImg"
                  multiple
                  :max-count="endImgs.uploadConfig.maxCount"
                  :upload-text="endImgs.uploadConfig.uploadText"
                  :size-type="endImgs.uploadConfig.sizeType"
              ></up-upload>
            </up-form-item>
          </view>
          <!-- 人员配置图片上传 -->
          <view v-if="activeTab == 3">
            <up-form-item  prop="personImgs">
              <up-upload
                  :file-list="personImgs.imgList"
                  @after-read="personImgs.uploadImgs"
                  @delete="personImgs.deleteImg"
                  multiple
                  :max-count="personImgs.uploadConfig.maxCount"
                  :upload-text="personImgs.uploadConfig.uploadText"
                  :size-type="personImgs.uploadConfig.sizeType"
              ></up-upload>
            </up-form-item>
          </view>
          <!-- 材料使用图片上传 -->
          <view v-if="activeTab == 4">
            <up-form-item  prop="materialImgs">
              <up-upload
                  :file-list="materialImgs.imgList"
                  @after-read="materialImgs.uploadImgs"
                  @delete="materialImgs.deleteImg"
                  multiple
                  :max-count="materialImgs.uploadConfig.maxCount"
                  :upload-text="materialImgs.uploadConfig.uploadText"
                  :size-type="materialImgs.uploadConfig.sizeType"
              ></up-upload>
            </up-form-item>
          </view>
        </view>
      </view>
      </up-form>
    </view>

    <!-- 底部提交按钮（保留，按需可移除） -->
    <view class="fixed-bottom-btn-wrap">
      <up-button
          type="primary"
          text="提交工单"
          @click="submitWorkOrder"
      ></up-button>
    </view>

    <!-- 通用下拉弹窗（仅用于共同处理人多选） -->
    <up-action-sheet
        :show="showActionSheet"
        :actions="currentActionSheetData.list"
        :title="currentActionSheetData.title"
        @close="handleActionSheetClose"
        @select="handleActionSheetSelect"
    ></up-action-sheet>
  </view>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { onLoad, onReady, onShow } from '@dcloudio/uni-app';
import { useUploadImgs } from '@/common/utils/useUploadImgs'
import { getYlWorkersPage, ylWorkerExcuteWOrder } from '@/api/work-order-manage/work-order-manage'
import { useUserStore } from '@/pinia/user';

const userStore = useUserStore();

// 表单Ref
const workOrderFormRef = ref(null)

// 页面状态
const showActionSheet = ref(false)
const currentActionSheetData = reactive({
  type: '',
  list: [],
  title: '',
})

// Tabs配置（图片切换用）
const activeTab = ref(0)
const tabList = ref([
  { name: '开始' },
  { name: '进行中' },
  { name: '结束' },
  { name: '人员' },
  { name: '材料' }
])

// 共同处理人列表
const coProcessorList = ref([])

// 工单表单数据（仅保留需要的字段）
const workOrderForm = reactive({
  orderNo: '',                  // 工单编号
  coProcessorId: '',            // 共同处理人ID数组（多选）
  coProcessorName: '',          // 共同处理人名称数组（多选）
  reason: '',                   // 处理情况描述
})

// ========== 图片上传配置（5个Tab分别配置，均限制3张，与参考示例一致） ==========
// 开始阶段图片
const startImgs = useUploadImgs({
  maxCount: 3,
  uploadText: '选择开始阶段照片',
  sizeType: ['compressed'],
  formRef: workOrderFormRef,
  fieldName: 'startImgs'
})
// 进行中阶段图片
const processingImgs = useUploadImgs({
  maxCount: 3,
  uploadText: '选择进行中阶段照片',
  sizeType: ['compressed'],
  formRef: workOrderFormRef,
  fieldName: 'processingImgs'
})
// 结束阶段图片
const endImgs = useUploadImgs({
  maxCount: 3,
  uploadText: '选择结束阶段照片',
  sizeType: ['compressed'],
  formRef: workOrderFormRef,
  fieldName: 'endImgs'
})
// 人员配置图片
const personImgs = useUploadImgs({
  maxCount: 3,
  uploadText: '选择人员配置照片',
  sizeType: ['compressed'],
  formRef: workOrderFormRef,
  fieldName: 'personImgs'
})
// 材料使用图片
const materialImgs = useUploadImgs({
  maxCount: 3,
  uploadText: '选择材料使用照片',
  sizeType: ['compressed'],
  formRef: workOrderFormRef,
  fieldName: 'materialImgs'
})

// ========== 核心修复：监听每个上传实例的响应式数组变化，解决u-upload不刷新问题 ==========
watch(() => startImgs.rawImgList.value, (newVal) => {
  startImgs.imgList = newVal
}, { deep: true })

watch(() => processingImgs.rawImgList.value, (newVal) => {
  processingImgs.imgList = newVal
}, { deep: true })

watch(() => endImgs.rawImgList.value, (newVal) => {
  endImgs.imgList = newVal
}, { deep: true })

watch(() => personImgs.rawImgList.value, (newVal) => {
  personImgs.imgList = newVal
}, { deep: true })

watch(() => materialImgs.rawImgList.value, (newVal) => {
  materialImgs.imgList = newVal
}, { deep: true })

// 表单校验规则（新增5个图片字段校验，复用上传校验规则）
const workOrderFormRules = reactive({
  orderNo: [
    { type: 'string', trigger: ['change'] }
  ],

  reason: [
    { type: 'string', required: true, message: '请输入处理情况描述', trigger: ['change', 'blur'] },
    { type: 'string', max: 200, message: '处理情况描述最多200字', trigger: ['change', 'blur'] }
  ],
  // 新增5个图片字段校验
  startImgs: [startImgs.imgValidateRule],
  processingImgs: [processingImgs.imgValidateRule],
  endImgs: [endImgs.imgValidateRule],
  personImgs: [personImgs.imgValidateRule],
  materialImgs: [materialImgs.imgValidateRule]
})

// 生命周期 - 从URL获取工单编号
onLoad((options) => {
  if (options && options.orderNo) {
    workOrderForm.orderNo = options.orderNo
  }
  console.log('从URL获取工单编号：', workOrderForm.orderNo)
})

// 生命周期 - 初始化表单规则
onReady(() => {
  if (workOrderFormRef.value) {
    workOrderFormRef.value.setRules(workOrderFormRules)
  }
  console.log('工单表单规则初始化完成')
})

// 生命周期 - 加载共同处理人列表
onShow(async () => {
  await loadCoProcessorList()
})

// 加载共同处理人列表
const loadCoProcessorList = async () => {
  try {
    uni.showLoading({ title: '获取处理人列表中...' })
    const queryData = {
      roleCode: 'yl_worker',
      busiLine: 'yl',
      pageNo: 1,
      pageSize: 100
    }
    const res = await getYlWorkersPage(queryData)
    uni.hideLoading()

    if (res.list && res.list.length > 0) {
      coProcessorList.value = res.list.map(item => ({
        name: item.nickname,
        value: item.id,
        id: item.id
      }))
      console.log('共同处理人列表：', coProcessorList.value)
    } else {
      coProcessorList.value = []
      uni.showToast({ title: '未查询到处理人数据', icon: 'none' })
    }
  } catch (err) {
    uni.hideLoading()
    console.error('获取共同处理人列表失败：', err)
    uni.showToast({ title: '获取处理人失败，请重试', icon: 'none' })
    coProcessorList.value = []
  }
}

// 打开通用下拉弹窗（仅共同处理人）
const handleActionSheetOpen = (type) => {
  // 共同处理人列表为空提示
  if (type === 'coProcessor' && coProcessorList.value.length === 0) {
    uni.showToast({ title: '暂无处理人数据可选', icon: 'none' })
    return
  }

  // 弹窗配置映射（仅保留共同处理人）
  const configMap = {
    coProcessor: {
      title: '请选择共同处理人',
      list: coProcessorList.value,
    }
  }

  currentActionSheetData.type = type
  currentActionSheetData.title = configMap[type].title
  currentActionSheetData.list = configMap[type].list
  showActionSheet.value = true
}

// 关闭通用下拉弹窗
const handleActionSheetClose = () => {
  showActionSheet.value = false
  currentActionSheetData.type = ''
  currentActionSheetData.list = []
  currentActionSheetData.title = ''
}

// 下拉弹窗选择事件（仅处理共同处理人多选）
const handleActionSheetSelect = (e) => {
  console.log(e)
  const { type } = currentActionSheetData
  // 多选场景（仅共同处理人）
  if (type === 'coProcessor') {
    workOrderForm.coProcessorName = e.name
    workOrderForm.coProcessorId = e.id
    workOrderFormRef.value?.validateField('coProcessorName')
  }
  showActionSheet.value = false
}

// 图片切换选择
const imgTabChange = (item)=> {
  console.log(item)
  activeTab.value = item.index
}

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

// 提交工单（整合所有图片URL，与参考示例一致）
const submitWorkOrder = async () => {
  try {
    // 表单校验
    await workOrderFormRef.value.validate()

    // 构造所有图片URL（按Tab分类，或合并为一个数组，可按需调整）
    const allImgs = {
      startImgs: startImgs.getSuccessImgUrls(),
      processingImgs: processingImgs.getSuccessImgUrls(),
      endImgs: endImgs.getSuccessImgUrls(),
      personImgs: personImgs.getSuccessImgUrls(),
      materialImgs: materialImgs.getSuccessImgUrls()
    }

    // 构造提交参数（可按需调整图片字段格式，此处既保留分类也提供合并数组）
    const submitData = {
      id: workOrderForm.orderNo,
      reason: workOrderForm.reason.trim(),
      coProcessorId: workOrderForm.coProcessorId, // 数组格式提交，如需字符串可.join(',')
      busiLine: 'yl',
      // 分类图片URL
      startImgs: allImgs.startImgs,
      processingImgs: allImgs.processingImgs,
      endImgs: allImgs.endImgs,
      personImgs: allImgs.personImgs,
      materialImgs: allImgs.materialImgs,
      // 合并所有图片为一个数组（若接口需要）
      imgs: [
        ...allImgs.startImgs,
        ...allImgs.processingImgs,
        ...allImgs.endImgs,
        ...allImgs.personImgs,
        ...allImgs.materialImgs
      ]
    }

    uni.showLoading({ title: '提交中...' })
    const res = await ylWorkerExcuteWOrder(submitData)
    uni.hideLoading()

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

    // 延迟跳转
    setTimeout(() => {
      uni.redirectTo({
        url: '/pages-sub/problem/work-order-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>
// 页面容器样式
.page-container {
  min-height: 100vh;
  padding-bottom: 100rpx; // 给底部按钮留空间，与参考示例一致
}

// 表单内容容器
.work-order-form-content {
  background: #fff;
  padding-bottom: 30rpx;
}

// Tabs容器样式
.tabs-wrap {
  background: #fff;
}

</style>