<template>
  <div class="exec-page">
    <div class="exec-header">
      <div class="title">设备点检</div>
      <div class="sub">设备ID：{{ deviceId }}<span v-if="categoryName">｜分类：{{ categoryName }}</span></div>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="card-header flex items-center justify-between">
          <span>本次点检项目</span>
          <div class="flex items-center gap-8px">
            <el-select v-if="isBatchMode" v-model="activeInstanceId" placeholder="选择设备" size="small"
              style="width: 220px;">
              <el-option v-for="inst in batchInstances" :key="inst.id"
                :label="(inst.deviceName || ('设备ID ' + inst.deviceId))"
                :value="inst.id" />
            </el-select>
            <el-button size="small" @click="refreshInstance" type="warning" plain
              v-if="!currentInstance && !isBatchMode">
              刷新任务实例
            </el-button>
            <el-button size="small" @click="goBack" type="info" plain>
              返回扫码
            </el-button>
          </div>
        </div>
      </template>

      <div v-if="loading" class="text-center py-20">加载中...</div>
      <div v-else>
        <div v-if="displayItems.length === 0" class="text-gray-500">暂无模板项目，请联系管理员配置。</div>
        <div v-for="(item, idx) in displayItems" :key="item.code" class="item-row">
          <div class="item-left">
            <div class="item-name flex items-center">
              <span class="mr-8px">{{ idx + 1 }}.</span>
              <span style="font-weight: 600; color: #1f2937;">{{ item.name }}</span>
              <el-text v-if="item.desc" type="info" class="ml-16px text-12px"
                style="color: #6b7280; background-color: #f9fafb; padding: 4px 8px; border-radius: 4px; margin-left: 16px;">{{
                  item.desc }}</el-text>
            </div>
          </div>
          <div class="item-right">
            <el-radio-group v-model="item.result" @change="onResultChange(item)">
              <el-radio label="ok">正常</el-radio>
              <el-radio label="bad">异常</el-radio>
            </el-radio-group>
          </div>
          <div v-if="item.result === 'bad'" class="issue-area">
            <el-input v-model="item.issueDesc" type="textarea" :rows="2" placeholder="请描述问题" />
            <el-upload class="mt-8px" action="" :http-request="handleUpload" list-type="picture-card"
              :file-list="item.photos"
              :on-success="(response, file, fileList) => onUploadSuccess(response, file, fileList, item)"
              :on-remove="(file, list) => onRemove(file, list, item)" :on-preview="(file) => onPreview(file)"
              :limit="10" multiple accept="image/*">
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </div>
        </div>
      </div>

      <div class="actions">
        <el-button v-if="!isBatchMode" @click="saveProgress" :loading="saving">保存进度</el-button>
        <el-button type="primary" @click="submit" :loading="submitting">{{ isBatchMode ? '批量提交点检' : '提交点检'
          }}</el-button>
      </div>
    </el-card>
  </div>

  <!-- 图片预览对话框 -->
  <el-dialog v-model="previewVisible" title="图片预览" width="80%" center>
    <img :src="previewImageUrl" style="width: 100%; max-height: 70vh; object-fit: contain;" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { Plus } from '@element-plus/icons-vue'
import { CheckLogApi } from '@/api/iot/check/log'
import { ProductApi } from '@/api/iot/product/product'
import { ProductCategoryApi } from '@/api/iot/product/category'
import { InspectionRecordApi } from '@/api/iot/inspection/record'
import { InspectionInstanceApi } from '@/api/iot/inspection/instance'

const route = useRoute()
const router = useRouter()
const deviceId = computed(() => route.params.deviceId as string)
const categoryName = ref<string>('')
const isBatchMode = computed(() => (route.query.batch as string) === '1')

const loading = ref(true)
const saving = ref(false)
const submitting = ref(false)

// 当前任务实例信息（单实例模式）
const currentInstance = ref<any>(null)
// 批量模式的实例列表
const batchInstances = ref<any[]>([])

// 防重复加载标志
const isLoaded = ref(false)

// 图片预览相关
const previewVisible = ref(false)
const previewImageUrl = ref('')

interface ExecItem {
  code: string
  name: string
  desc?: string
  result?: 'ok' | 'bad'
  issueDesc?: string
  photos: any[]
}

const items = ref<ExecItem[]>([])
// 批量模式：为每个实例维护独立点检项
const instanceIdToItems = ref<Record<string, ExecItem[]>>({})
const activeInstanceId = ref<number>(-1)
const displayItems = computed<ExecItem[]>(() => {
  if (!isBatchMode.value) return items.value
  if (!activeInstanceId.value || activeInstanceId.value <= 0) return []
  const key = String(activeInstanceId.value)
  return instanceIdToItems.value[key] || []
})

onMounted(async () => {
  // 防重复加载
  if (isLoaded.value) {
    console.log('🚫 页面已加载，跳过重复初始化')
    return
  }

  isLoaded.value = true

  if (!isBatchMode.value) {
    // 从sessionStorage获取任务实例信息
    const instanceData = sessionStorage.getItem('currentInspectionInstance')
    console.log('🔍 从sessionStorage获取的实例数据:', instanceData)

    if (instanceData) {
      try {
        currentInstance.value = JSON.parse(instanceData)
        console.log('📋 获取到任务实例信息:', currentInstance.value)
      } catch (e) {
        console.warn('⚠️ 解析任务实例信息失败:', e)
      }
    } else {
      console.warn('⚠️ sessionStorage中未找到任务实例信息')
      // 尝试重新获取任务实例信息
      await tryGetCurrentInstance()
    }
  }

  await loadProductInfo()
})

// 尝试重新获取任务实例信息
async function tryGetCurrentInstance() {
  try {
    console.log('🔄 尝试重新获取任务实例信息，设备ID:', deviceId.value)
    const response = await InspectionInstanceApi.getCurrentByDevice(deviceId.value)
    console.log('📋 重新获取到的任务实例响应:', response)

    // 检查响应结构，API返回的是 { code: 0, data: [...], msg: "" }
    const instances = response.data || response
    console.log('📋 解析后的任务实例数据:', instances)

    if (instances && instances.length > 0) {
      currentInstance.value = instances[0]
      console.log('✅ 成功获取任务实例信息:', currentInstance.value)

      // 重新存储到sessionStorage
      sessionStorage.setItem('currentInspectionInstance', JSON.stringify(currentInstance.value))
    } else {
      console.warn('⚠️ 该设备当前没有进行中的任务实例')
    }
  } catch (e: any) {
    console.error('❌ 重新获取任务实例失败:', e)
  }
}

async function loadProductInfo() {
  try {
    console.log('🔍 CheckExecute: 开始加载产品信息，ID:', deviceId.value)
    const product = await ProductApi.getProduct(Number(deviceId.value))
    console.log('📱 CheckExecute: 获取到产品信息:', product)
    categoryName.value = (product as any)?.categoryName as string

    if (!categoryName.value) {
      ElMessage.warning('设备未设置分类，无法匹配点检模板')
      return
    }

    // 保存分类ID用于后续获取模板
    const categoryId = (product as any)?.categoryId
    if (!categoryId) {
      ElMessage.warning('产品未设置分类ID，无法获取点检模板')
      return
    }

    if (isBatchMode.value) {
      await loadBatchInstances(product.id)
    }

    // 直接获取分类详情和模板（无论是否批量模式，模板相同）
    await loadTemplate(categoryId)
  } catch (e: any) {
    ElMessage.error('获取设备信息失败：' + (e?.message || '设备不存在'))
  }
}

async function loadTemplate(categoryId: number) {
  loading.value = true
  try {
    console.log('🏷️ CheckExecute: 开始加载模板，分类ID:', categoryId)
    // 直接获取分类详情和模板
    const category = await ProductCategoryApi.getProductCategory(categoryId)
    console.log('📋 CheckExecute: 获取到分类信息:', category)

    if (!category) {
      ElMessage.warning(`未找到分类信息`)
      return
    }

    // 检查是否有模板
    const templateField = category.inspectTemplate || category.inspectionTemplate || category.template
    if (!templateField || templateField.trim() === '') {
      ElMessage.warning(`未找到"${categoryName.value}"分类的点检模板`)
      return
    }

    let templateItems: any[] = []
    try {
      templateItems = JSON.parse(templateField)
    } catch (e) {
      ElMessage.error('模板格式错误')
      return
    }

    if (!templateItems.length) {
      ElMessage.warning(`"${categoryName.value}"分类的点检模板为空`)
      return
    }

    const baseItems: ExecItem[] = templateItems.map((item: any, idx: number) => ({
      code: `CHK-${String(idx + 1).padStart(3, '0')}`,
      name: item.name,
      desc: item.desc,
      result: 'ok',
      issueDesc: '',
      photos: []
    }))
    items.value = baseItems

    // 批量模式：为每个实例复制一份独立表单数据
    if (isBatchMode.value && batchInstances.value.length > 0) {
      const map: Record<string, ExecItem[]> = {}
      for (const inst of batchInstances.value) {
        map[String(inst.id)] = baseItems.map(b => ({ ...b, photos: [] }))
      }
      instanceIdToItems.value = map
      activeInstanceId.value = batchInstances.value[0]?.id || -1
    }
  } finally {
    loading.value = false
  }
}

// 批量模式：根据产品ID查询同分类进行中的实例
async function loadBatchInstances(productId: number) {
  try {
    console.log('🔍 批量模式：按产品ID查询同分类实例，productId:', productId)
    const resp = await InspectionInstanceApi.getCurrentByProductCategory(productId)
    const instances = (resp as any)?.data || resp || []
    batchInstances.value = Array.isArray(instances) ? instances : []
    console.log('📋 批量实例列表:', batchInstances.value)
    if (batchInstances.value.length === 0) {
      ElMessage.warning('未找到同分类进行中的任务实例，将按单设备执行')
    }
  } catch (e: any) {
    console.error('❌ 加载批量实例失败:', e)
    ElMessage.error('加载同分类实例失败：' + (e?.message || '未知错误'))
  }
}

function onResultChange(item: ExecItem) {
  if (item.result !== 'bad') {
    item.issueDesc = ''
    item.photos = []
  }
}

async function handleUpload(options: any) {
  const { file, onSuccess, onError } = options
  try {
    const res = await CheckLogApi.uploadImage(file as File)
    // 传递完整的响应对象，包含 url, name, size, type
    onSuccess(res)
  } catch (e) {
    onError(e)
  }
}

function onUploadSuccess(response: any, file: any, fileList: any[], item: ExecItem) {
  // 更新对应项目的图片列表，使用服务器返回的真实URL
  item.photos = fileList.map(f => ({
    ...f,
    url: f.response?.url || f.url, // 优先使用服务器返回的URL
    name: f.response?.name || f.name,
    size: f.response?.size || f.size,
    type: f.response?.type || f.type
  }))
  console.log('📸 图片上传成功:', response, '更新后的图片列表:', item.photos)
}

function onRemove(_: any, list: any[], item: ExecItem) {
  item.photos = list
}

// 图片预览
function onPreview(file: any) {
  previewImageUrl.value = file.url || file.response?.url
  previewVisible.value = true
}

async function saveProgress() {
  if (!currentInstance.value) {
    console.warn('⚠️ 当前没有任务实例信息，尝试重新获取...')

    // 尝试重新获取任务实例
    await tryGetCurrentInstance()

    if (!currentInstance.value) {
      ElMessage.error('未找到任务实例信息，无法保存进度。请返回扫码页面重新扫描设备。')
      return
    }
  }

  saving.value = true
  try {
    const payload = buildInspectionRecordPayloadForSingle()
    // 保存进度时，将状态设为NORMAL（临时保存）
    payload.resultStatus = 'NORMAL' as const

    console.log('💾 保存点检进度:', payload)
    await InspectionRecordApi.createInspectionRecord(payload)
    ElMessage.success('已保存进度')
  } catch (e: any) {
    console.error('❌ 保存进度失败:', e)
    ElMessage.error('保存失败：' + (e?.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

async function submit() {
  if (!items.value.length) {
    ElMessage.warning('暂无点检项')
    return
  }

  if (!isBatchMode.value) {
    // 非批量：检查单实例存在
    if (!currentInstance.value) {
      console.warn('⚠️ 当前没有任务实例信息，尝试重新获取...')
      await tryGetCurrentInstance()
      if (!currentInstance.value) {
        ElMessage.error('未找到任务实例信息，无法提交点检记录。请返回扫码页面重新扫描设备。')
        return
      }
    }
  } else {
    // 批量：需要有批量实例
    if (!batchInstances.value.length) {
      ElMessage.error('未找到同分类进行中的任务实例，无法批量提交')
      return
    }
  }

  submitting.value = true
  try {
    if (!isBatchMode.value) {
      const payload = buildInspectionRecordPayloadForSingle()
      console.log('📤 提交点检记录:', payload)
      const result = await InspectionRecordApi.createInspectionRecord(payload)
      console.log('✅ 点检记录创建成功:', result)
      ElMessage.success('提交成功')
      goBack()
    } else {
      const batchPayload = buildInspectionRecordPayloadForBatch()
      console.log('📤 批量提交点检记录:', batchPayload)
      const result = await InspectionRecordApi.createInspectionRecordBatchMixed(batchPayload)
      console.log('✅ 批量点检记录创建成功:', result)
      ElMessage.success('批量提交成功')
      goBack()
    }
  } catch (e: any) {
    console.error('❌ 提交点检记录失败:', e)
    ElMessage.error('提交失败：' + (e?.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}

function buildInspectionRecordBaseSummary(targetItems: ExecItem[]) {
  const abnormalItems = targetItems.filter(i => i.result === 'bad')
  const hasAbnormal = abnormalItems.length > 0

  // 构建简化的数据结构，只保留有用信息
  const inspectionData = targetItems.map(item => {
    const baseItem = {
      name: item.name,
      desc: item.desc,
      status: item.result === 'ok' ? 'NORMAL' : 'ABNORMAL'
    }

    // 如果是异常项目，添加异常原因和图片
    if (item.result === 'bad') {
      return {
        ...baseItem,
        abnormal_reason: item.issueDesc || '',
        picurl: item.photos && item.photos.length > 0
          ? item.photos.map((photo: any) => photo.url).join(',')
          : ''
      }
    }

    return baseItem
  })

  // 将数据转换为JSON字符串作为结果摘要
  const resultSummary = JSON.stringify(inspectionData, null, 2)

  return { resultSummary, hasAbnormal }
}

function buildInspectionRecordPayloadForSingle() {
  const base = buildInspectionRecordBaseSummary(items.value)
  return {
    instanceId: currentInstance.value.id,
    resultStatus: (base.hasAbnormal ? 'ABNORMAL' : 'NORMAL') as 'ABNORMAL' | 'NORMAL',
    resultSummary: base.resultSummary,
    submitterUserId: currentInstance.value.assigneeUserId || '1001',
    submitterUserName: currentInstance.value.assigneeUserName || '当前用户'
  }
}

function buildInspectionRecordPayloadForBatch() {
  const itemsPayload = batchInstances.value.map(inst => {
    const perItems = instanceIdToItems.value[String(inst.id)] || items.value
    const base = buildInspectionRecordBaseSummary(perItems)
    return {
      instanceId: inst.id,
      resultStatus: (base.hasAbnormal ? 'ABNORMAL' : 'NORMAL') as 'ABNORMAL' | 'NORMAL',
      resultSummary: base.resultSummary
    }
  })

  // 取第一条实例的指派信息作为默认提交人，若后端需要认证用户可从上下文替换
  const submitterUserId = (batchInstances.value[0]?.assigneeUserId) || '1001'
  const submitterUserName = (batchInstances.value[0]?.assigneeUserName) || '当前用户'

  return {
    items: itemsPayload,
    submitterUserId,
    submitterUserName
  }
}


function goBack() {
  // 返回公开扫码页
  router.replace({ name: 'IoTCheckScanPublic' })
}

// 手动刷新任务实例
async function refreshInstance() {
  try {
    ElMessage.info('正在刷新任务实例...')
    await tryGetCurrentInstance()

    if (currentInstance.value) {
      ElMessage.success('任务实例刷新成功')
    } else {
      ElMessage.warning('未找到任务实例，请确保设备有进行中的任务')
    }
  } catch (e: any) {
    ElMessage.error('刷新失败：' + (e?.message || '未知错误'))
  }
}
</script>

<style scoped>
.exec-page {
  padding: 12px;
  height: 100vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  box-sizing: border-box;
}

.exec-header {
  margin-bottom: 12px;
}

.title {
  font-size: 18px;
  font-weight: 600;
}

.sub {
  color: #666;
  font-size: 12px;
}

.card-header {
  font-weight: 600;
}

.item-row {
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 0;
}

.item-left {
  margin-bottom: 8px;
}

.item-name {
  font-weight: 600;
}

.item-desc {
  color: #666;
  font-size: 12px;
  margin-top: 4px;
}

.item-right {
  margin: 8px 0;
}

.issue-area {
  margin-top: 8px;
}

.actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 12px;
}

.text-center {
  text-align: center;
}

.py-20 {
  padding: 20px 0;
}

.text-gray-500 {
  color: #909399;
}

.mt-8px {
  margin-top: 8px;
}
</style>
