<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>

        <!-- 原有：工单位置（地图选择） -->
        <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>

        <!-- 原有：道路名称（下拉框） -->
        <up-form-item
            label="道路名称"
            prop="roadName"
            border-bottom
            required
            @click="handleActionSheetOpen('roadName'); hideKeyboard()"
        >
          <up-input
              v-model="workOrderForm.roadName"
              readonly
              disabled-color="#ffffff"
              placeholder="请先选择工单位置"
              border="none"
          ></up-input>
          <template #right>
            <up-icon name="arrow-right" size="16"></up-icon>
          </template>
        </up-form-item>

        <!-- 原有：工单名称（下拉框） -->
        <up-form-item
            label="工单名称"
            prop="orderName"
            border-bottom
            required
            @click="handleActionSheetOpen('orderName'); 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>

        <!-- 原有：紧急程度选择 -->
        <up-form-item
            label="紧急程度"
            prop="pressingTypeName"
            border-bottom
            required
            @click="handleActionSheetOpen('pressingType'); hideKeyboard()"
        >
          <up-input
              v-model="workOrderForm.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>

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

        <!-- 原有：问题照片 -->
        <up-form-item label="问题照片" prop="problemImgs" required>
          <up-upload
              :file-list="problemImgs.imgList"
              @after-read="problemImgs.uploadImgs"
              @delete="problemImgs.deleteImg"
              multiple
              :max-count="problemImgs.uploadConfig.maxCount"
              :upload-text="problemImgs.uploadConfig.uploadText"
              :size-type="problemImgs.uploadConfig.sizeType"
          ></up-upload>
        </up-form-item>

        <!-- 原有：完成时间 -->
        <up-form-item
            label="希望完成时间"
            prop="finishDate"
            @click="show=true;hideKeyboard()"
        >
          <up-input
              v-model="workOrderForm.finishDate"
              border="none"
              readonly
              placeholder="点击选择时间"
          ></up-input>
          <template #right>
            <up-icon name="arrow-right" size="16"></up-icon>
          </template>
        </up-form-item>
      </up-form>

      <!-- 4. 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"
        ></up-tabs>
        <!-- Tab对应内容容器（可根据需求填充具体内容） -->
        <view class="tab-content" style="padding-top: 20rpx;">
          <view v-if="activeTab === 0">开始阶段相关内容</view>
          <view v-if="activeTab === 1">进行中阶段相关内容</view>
          <view v-if="activeTab === 2">结束阶段相关内容</view>
          <view v-if="activeTab === 3">人员配置相关内容</view>
          <view v-if="activeTab === 4">材料使用相关内容</view>
        </view>
      </view>
    </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>

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

<script setup>
import { ref, reactive, watch, onLoad } from 'vue'
import { onReady, onShow } from '@dcloudio/uni-app';
import { useUploadImgs } from '@/common/utils/useUploadImgs'
import { getRoadListByLatLng } from '@/api/common'
import { workorderCreate, getYlWorkersPage, ylTeamLeaderAssignWOrder, ylWorkerExcuteWOrder } from '@/api/work-order-manage/work-order-manage'
import { timeFormat } from '@/uni_modules/uview-plus'

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

// ========== 公共上传逻辑复用 ==========
const problemImgs = useUploadImgs({
  maxCount: 3,
  uploadText: '选择问题照片',
  sizeType: ['compressed'],
  formRef: workOrderFormRef,
  fieldName: 'problemImgs'
})

// 核心修复：监听响应式数组变化，同步更新纯数组
watch(() => problemImgs.rawImgList.value, (newVal) => {
  problemImgs.imgList = newVal
}, { deep: true })

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

// 新增：Tabs配置
const activeTab = ref(0) // 默认选中第一个标签
const tabList = ref([
  { name: '开始' },
  { name: '进行中' },
  { name: '结束' },
  { name: '人员' },
  { name: '材料' }
])

// ========== 下拉列表数据 ==========
const roadNameList = ref([])
const orderNameList = ref([])
const pressingTypeList = ref([])
const coProcessorList = ref([]) // 新增：共同处理人列表（来自getYlWorkersPage）

// ========== 工单表单数据（新增字段） ==========
const workOrderForm = reactive({
  orderNo: '',                  // 新增：工单编号（URL获取）
  coProcessorId: '',            // 新增：共同处理人ID（非必选，提交接口用）
  coProcessorName: '',          // 新增：共同处理人名称（显示用）
  reason: '',                   // 新增：处理建议（必填）
  roadId: 0,
  roadName: '',
  workLocation: '',
  orderName: '',
  pressingType: '',
  pressingTypeName: '',
  problemDesc: '',
  lat: 0,
  lon: 0,
  finishDate: '',
})

// ========== 表单校验规则（更新：新增处理建议必填、共同处理人非必填） ==========
const workOrderFormRules = reactive({
  orderNo: [                    // 工单编号仅展示，无校验
    { type: 'string', trigger: ['change'] }
  ],
  coProcessorName: [            // 共同处理人非必填，仅长度兜底
    { type: 'string', max: 50, message: '共同处理人名称过长', trigger: ['change'] }
  ],
  reason: [                     // 处理建议必填+长度限制
    { type: 'string', required: true, message: '请输入处理建议', trigger: ['change', 'blur'] },
    { type: 'string', max: 200, message: '处理建议最多200字', trigger: ['change', 'blur'] }
  ],
  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'] }
  ],
  pressingTypeName: [
    { type: 'string', required: true, message: '请选择紧急程度', trigger: ['change'] }
  ],
  problemDesc: [
    { type: 'string', required: true, message: '请输入情况描述', trigger: ['change', 'blur'] },
    { type: 'string', min: 3, max: 200, message: '情况描述需3-200字', trigger: ['change', 'blur'] }
  ],
  problemImgs: [problemImgs.imgValidateRule]
})

// ========== 生命周期 ==========
// 新增：onLoad - 从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 () => {
  console.log(uni.$dict.getDictLabel('ai_image_status', 20))
  console.log(uni.$dict.getDictSimpleList('work_name'))

  // 初始化工单名称列表
  orderNameList.value = uni.$dict.transformLabelValueToNameValue(uni.$dict.getDictSimpleList('work_name'))
  console.log('工单名称列表：', orderNameList.value)

  // 初始化紧急程度列表
  pressingTypeList.value = uni.$dict.transformLabelValueToNameValue(uni.$dict.getDictSimpleList('workorder_pressing_type'))
  console.log('紧急程度列表：', pressingTypeList.value)

  // 新增：加载共同处理人列表（来自getYlWorkersPage）
  await loadCoProcessorList()
})

// ========== 新增：加载共同处理人列表 ==========
const loadCoProcessorList = async () => {
  try {
    uni.showLoading({ title: '获取处理人列表中...' })
    // 构造查询参数（可根据接口需求调整）
    const queryData = {
      roleCode: 'team_leader_yl',
      busiLine: 'yl',
      pageNo: 1,
      pageSize: 100
    }
    const res = await getYlWorkersPage(queryData)
    uni.hideLoading()

    // 适配接口返回格式（兼容res.data.list或res.records）
    let listData = []
    if (res && res.code === 0 && res.data && res.data.list) {
      listData = res.data.list
    } else if (res && res.records) {
      listData = res.records
    }

    if (Array.isArray(listData) && listData.length > 0) {
      // 格式化共同处理人列表（映射name和value）
      coProcessorList.value = listData.map(item => ({
        name: item.nickname || item.realName || item.userName || '未知处理人',
        value: item.id || item.workerId || '',
        id: item.id || item.workerId || ''
      }))
    } 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 === 'roadName' && !workOrderForm.workLocation) {
    uni.showToast({ title: '请先选择工单位置', icon: 'none' })
    return
  }

  // 共同处理人列表为空提示
  if (type === 'coProcessor' && coProcessorList.value.length === 0) {
    uni.showToast({ title: '暂无处理人数据可选', icon: 'none' })
    return
  }

  // 配置当前弹窗参数（新增coProcessor）
  const configMap = {
    coProcessor: {
      title: '请选择共同处理人',
      list: coProcessorList.value
    },
    roadName: {
      title: '请选择道路名称',
      list: roadNameList.value
    },
    orderName: {
      title: '请选择工单名称',
      list: orderNameList.value
    },
    pressingType: {
      title: '请选择紧急程度',
      list: pressingTypeList.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) => {
  const { type } = currentActionSheetData
  switch (type) {
    case 'coProcessor': // 新增：共同处理人选择
      workOrderForm.coProcessorName = e.name
      workOrderForm.coProcessorId = e.value
      workOrderFormRef.value?.validateField('coProcessorName')
      break
    case 'roadName':
      workOrderForm.roadName = e.name
      workOrderForm.roadId = e.code
      workOrderFormRef.value?.validateField('roadName')
      break
    case 'orderName':
      workOrderForm.orderName = e.name
      workOrderFormRef.value?.validateField('orderName')
      break
    case 'pressingType':
      workOrderForm.pressingType = e.value
      workOrderForm.pressingTypeName = e.name
      workOrderFormRef.value?.validateField('pressingType')
      break
  }
  showActionSheet.value = false
}

/**
 * 返回上一页
 */
const navigateBack = () => {
  uni.navigateBack()
}

/**
 * 选择工单位置
 */
const chooseWorkLocation = () => {
  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) => ({
            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' })
    }
  })
}

/**
 * 完成时间确认
 */
const finishDateConfirm = (e) => {
  console.log('选择的完成时间：', e)
  workOrderForm.finishDate = timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
  show.value = false
}

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

/**
 * 提交工单（改造：使用ylWorkerExcuteWOrder接口，传递新增参数）
 */
const submitWorkOrder = async () => {
  try {
    // 表单校验
    await workOrderFormRef.value.validate()

    // 构造提交参数（包含原有参数+新增字段）
    const submitData = {
      id: workOrderForm.orderNo,        // 工单编号（对应接口id）
      reason: workOrderForm.reason.trim(), // 处理建议（必填）
      coProcessorId: workOrderForm.coProcessorId, // 共同处理人ID（非必选）
      roadId: workOrderForm.roadId,
      roadName: workOrderForm.roadName,
      imgs: problemImgs.getSuccessImgUrls(),
      remark: workOrderForm.problemDesc.trim(),
      latLonType: 2,
      lat: workOrderForm.lat,
      lon: workOrderForm.lon,
      lonLatAddress: workOrderForm.workLocation,
      pressingType: workOrderForm.pressingType,
      orderName: workOrderForm.orderName,
      finishDate: workOrderForm.finishDate,
      sourceId: 1,
      sourceName: '园林',
      busiLine: 'yl'
    }

    // 显示加载中
    uni.showLoading({ title: '提交中...' })

    // 替换为指定接口：ylWorkerExcuteWOrder
    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; // 给底部按钮留空间
  background-color: #f5f5f5;
}

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

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


</style>