/**
 * 安检详情数据服务（af-safecheck 固定用法）
 * 供 XInspectionDetailDrawer 内置使用
 */
import {
  getInspectionFullDetail,
  approveInspection,
  fetchHistoryList
} from './inspectionDetailApi'
import { getConfigByNameAsync } from '@vue2-client/services/api/common'

class InspectionService {
  constructor () {
    this.cache = new Map()
    this.serviceName = 'af-safecheck'
  }

  async getFullDetail (id, userInfoId) {
    try {
      const cacheKey = `detail_${id}_${userInfoId || 'single'}`
      if (this.cache.has(cacheKey)) return this.cache.get(cacheKey)
      const rawData = await this.fetchRawData(id, userInfoId)
      const processedData = await this.processDetailData(rawData)
      this.cache.set(cacheKey, processedData)
      return processedData
    } catch (error) {
      console.error('获取安检详情失败:', error)
      throw new Error(error?.message || error)
    }
  }

  async fetchRawData (id) {
    if (!id) throw new Error('该用户暂无安检记录!')
    return getInspectionFullDetail(id)
  }

  async getHistoryList (userInfoId) {
    const list = await fetchHistoryList(userInfoId)
    return this.formatHistoryList(list)
  }

  async switchToHistoryDetail (historyId, mainId, userInfoId) {
    return historyId === mainId
      ? this.getFullDetail(mainId, userInfoId)
      : this.getFullDetail(historyId, userInfoId)
  }

  async approve (params) {
    try {
      const result = await approveInspection({
        paperId: params.id,
        reviewStatus: params.state,
        approvedNote: params.note,
        user: params.user
      })
      this.clearCache(params.id)
      return result
    } catch (error) {
      console.error('审核操作失败:', error)
      throw new Error('审核操作失败，请重试')
    }
  }

  async processDetailData (rawData) {
    const transformedData = await this.transformApiData(rawData)
    const config = await getConfigByNameAsync('webConfig', 'af-system')
    return {
      ...transformedData,
      basicInfo: this.formatBasicInfo(transformedData.basicInfo, config?.setting?.safeCheckDesensitizedField || null),
      historyList: this.formatHistoryList(transformedData.historyList),
      deviceList: this.formatDeviceList(transformedData.deviceList),
      checkItems: this.formatCheckItems(transformedData.checkItems),
      hazardList: this.formatHazardList(transformedData.hazardList),
      attachments: this.formatAttachments(transformedData.attachments)
    }
  }

  formatBasicInfo (basicInfo,desensitizedField) {
    if (!basicInfo) return {}
    return {
      ...basicInfo,
      f_user_phone_display: this.maskPhoneNumber(basicInfo.f_user_phone, desensitizedField),
      f_idnumber_display: this.maskIdNumber(basicInfo.f_idnumber, desensitizedField),
      auditStatus: this.getAuditStatus(basicInfo),
      statusClass: this.getStatusClass(basicInfo.f_user_status)
    }
  }

  formatHistoryList (historyList) {
    if (!Array.isArray(historyList)) return []
    return historyList.map(item => ({
      ...item,
      statusClass: this.getStatusClass(item.status),
      statusIcon: this.getStatusIcon(item.status),
      displayDate: item.inspectiondate
    }))
  }

  formatDeviceList (deviceList) {
    if (!Array.isArray(deviceList)) return []
    return deviceList.map(device => ({
      ...device,
      statusClass: this.getDeviceStatusClass(device.status),
      statusColor: this.getDeviceStatusColor(device.status)
    }))
  }

  formatCheckItems (checkItems) {
    if (!Array.isArray(checkItems)) return []
    return checkItems.map(category => ({
      ...category,
      items: category.items.map(item => ({
        ...item,
        statusClass: this.getCheckItemStatusClass(item.status),
        statusIcon: this.getCheckItemStatusIcon(item.status)
      })),
      stats: this.calculateCategoryStats(category.items)
    }))
  }

  formatHazardList (hazardList) {
    if (!Array.isArray(hazardList)) return []
    return hazardList.map(hazard => ({
      ...hazard,
      levelClass: this.getHazardLevelClass(hazard.level),
      levelColor: this.getHazardLevelColor(hazard.level)
    }))
  }

  formatAttachments (attachments) {
    if (!attachments) return {}
    return {
      ...attachments,
      signature: attachments.signature ? {
        ...attachments.signature,
        displayTime: this.formatDateTime(attachments.signature.signTime)
      } : null,
      recordings: Array.isArray(attachments.recordings)
        ? attachments.recordings.map(record => ({
          ...record,
          displayTime: this.formatDateTime(record.recordTime)
        }))
        : []
    }
  }

  maskPhoneNumber (phone, desensitizedField) {
    if (!phone) return ''
    if (desensitizedField && !desensitizedField.includes('f_user_phone')) return phone
    return String(phone).replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
  }

  maskIdNumber (idNumber, desensitizedField) {
    if (!idNumber) return ''
    if (desensitizedField && !desensitizedField.includes('f_idnumber')) return idNumber
    return String(idNumber).replace(/(\d{6})\d{8}(\d{4})/, '$1********$2')
  }

  getAuditStatus (basicInfo) {
    if (!basicInfo?.f_approved || basicInfo.f_approved === '未审核') return { text: '待审核', class: 'pending' }
    if (basicInfo.f_approved === '通过') return { text: '审核通过', class: 'approved' }
    if (basicInfo.f_approved === '不通过') return { text: '审核不通过', class: 'rejected' }
    return { text: '未知状态', class: 'unknown' }
  }

  getStatusClass (status) {
    const map = { 正常: 'status-pass', 有隐患: 'status-warn', 不通过: 'status-fail' }
    return map[status] || 'status-unknown'
  }

  getStatusIcon (status) {
    const map = { 正常: 'check-circle', 有隐患: 'exclamation-circle', 不通过: 'close-circle' }
    return map[status] || 'question-circle'
  }

  getDeviceStatusClass (status) {
    const map = { normal: 'device-pass', warning: 'device-warn', error: 'device-fail' }
    return map[status] || 'device-unknown'
  }

  getDeviceStatusColor (status) {
    const map = { normal: '#52c41a', warning: '#fa8c16', error: '#f5222d' }
    return map[status] || '#d9d9d9'
  }

  getCheckItemStatusClass (status) {
    const map = { pass: 'check-pass', warning: 'check-warn', fail: 'check-fail' }
    return map[status] || 'check-unknown'
  }

  getCheckItemStatusIcon (status) {
    const map = { pass: 'check', warning: 'exclamation', fail: 'close' }
    return map[status] || 'question'
  }

  calculateCategoryStats (items) {
    const stats = { pass: 0, warning: 0, fail: 0, total: items.length }
    items.forEach(item => {
      if (item.status === 'pass') stats.pass++
      else if (item.status === 'warning') stats.warning++
      else if (item.status === 'fail') stats.fail++
    })
    return stats
  }

  getHazardLevelClass (level) {
    const map = { high: 'hazard-high', medium: 'hazard-medium', low: 'hazard-low' }
    return map[level] || 'hazard-unknown'
  }

  getHazardLevelColor (level) {
    const map = { high: '#f5222d', medium: '#fa8c16', low: '#fadb14' }
    return map[level] || '#d9d9d9'
  }

  formatDateTime (dateTimeStr) {
    if (!dateTimeStr) return ''
    return String(dateTimeStr).replace('T', ' ').substring(0, 19)
  }

  async transformApiData (apiData) {
    if (!apiData.checkPaper && apiData.basicInfo) return apiData
    const checkPaper = apiData.checkPaper?.[0] || {}
    const defectList = apiData.defectList || []
    const checkResultJson = apiData.checkResultJson || []
    const signatureForm = apiData.signatureForm || {}
    const historyList = apiData.historyList || []
    return {
      basicInfo: {
        id: checkPaper.id,
        f_user_name: checkPaper.f_user_name,
        f_userinfo_code: checkPaper.f_userinfo_code,
        f_idnumber: checkPaper.f_idnumber,
        f_address: checkPaper.f_address,
        f_user_phone: checkPaper.f_user_phone,
        f_onsite_time: checkPaper.f_onsite_time,
        f_offsite_time: checkPaper.f_offsite_time,
        f_checker_name: checkPaper.f_checker_name,
        f_user_type: checkPaper.f_user_type,
        f_entry_status: checkPaper.f_entry_status,
        f_user_status: checkPaper.f_is_defect === '是' ? '有隐患' : '正常',
        f_arrive_time: checkPaper.f_onsite_time,
        f_leave_time: checkPaper.f_offsite_time,
        f_comments: checkPaper.f_comments,
        f_approved: checkPaper.f_approved,
        f_approved_time: checkPaper.f_approved_time,
        f_approved_name: checkPaper.f_approved_name,
        f_approved_note: checkPaper.f_approved_note
      },
      historyList,
      deviceList: await this.extractDeviceList(checkResultJson),
      checkItems: this.extractCheckItems(checkResultJson),
      hazardList: this.transformDefectList(defectList),
      attachments: this.extractAttachments(signatureForm)
    }
  }

  async extractDeviceList (checkResultJson) {
    const deviceList = []
    const gasDeviceSection = checkResultJson.find(s => s.slotName === 'gasDevice')
    if (!gasDeviceSection?.items) return deviceList

    for (const [index, device] of gasDeviceSection.items.entries()) {
      const photos = []
      const hazardPhotos = []
      const safetyChecks = []
      let hasHighRisk = false
      let defectCount = 0

      if (device.items) {
        device.items.forEach(item => {
          if (item.f_defect_paths && Array.isArray(item.f_defect_paths)) {
            hazardPhotos.push(...item.f_defect_paths.map(photoData => ({
              id: typeof photoData === 'object' ? photoData.id : photoData,
              fileId: photoData,
              title: item.itemname,
              description: `${item.itemname}: ${item.value}`
            })))
          }
          if (item.type === 'files' && item.itemname) {
            const photoData = this.extractDevicePhoto(item)
            if (photoData?.length) photos.push(...photoData)
          } else if (item.itemname && item.value !== undefined) {
            const option = item.options?.find(opt => opt.data === item.value)
            const isRisk = item.f_process_mode != null && option?.isdefect
            if (isRisk) {
              defectCount++
              if (option && ['重大隐患', '严重隐患'].includes(option.level)) hasHighRisk = true
            }
            safetyChecks.push({
              name: item.itemname,
              value: item.value,
              status: isRisk ? 'fail' : 'pass',
              isRisk,
              processMode: item.f_process_mode || '',
              level: item.level || ''
            })
          }
        })
      }

      let status = 'normal'
      let statusText = '正常'
      if (hasHighRisk) { status = 'error'; statusText = '隐患' }
      else if (defectCount > 0) { status = 'warning'; statusText = '需关注' }

      const deviceFormFields = []
      const deviceType = device.deviceType || '未知设备'
      try {
        const formConfig = await this.getFormConfigByDeviceName(deviceType)
        if (device.form && formConfig?.formJson) {
          formConfig.formJson.forEach(fc => {
            const v = device.form[fc.model]
            if (v !== undefined && v !== null && v !== '' && fc.addOrEdit !== 'silenceAdd') {
              deviceFormFields.push({ label: fc.name, key: fc.model, value: v, type: fc.type || 'text' })
            }
          })
        }
      } catch (e) {
        console.warn('获取设备表单配置失败:', deviceType, e)
      }

      const brand = device.form?.f_devices_model || deviceFormFields.find(f => f.key.includes('brand'))?.value || '—'
      const model = device.form?.f_devices_type || deviceFormFields.find(f => f.key.includes('model'))?.value || '—'
      const processingAdvice = hasHighRisk
        ? '发现严重隐患，请立即停用并联系专业人员处理。'
        : defectCount > 0
          ? `发现 ${defectCount} 项问题，建议及时处理以确保使用安全。`
          : '设备运行正常，建议定期检查维护。'

      deviceList.push({
        id: device.deviceId || `device_${index + 1}`,
        name: device.deviceType || '未知设备',
        status,
        statusText,
        statusColor: this.getDeviceStatusColor(status),
        statusClass: this.getDeviceStatusClass(status),
        deviceIcon: this.getDeviceIcon(device.deviceType || '未知设备'),
        brand,
        model,
        safetyChecks,
        hazardPhotos,
        processingAdvice,
        defectCount,
        hasHighRisk,
        inspector: device.form?.f_operator || '',
        remark: device.form?.f_comments || '',
        formFields: deviceFormFields,
        photos: photos.length ? photos : []
      })
    }
    return deviceList
  }

  extractDevicePhoto (item) {
    if (!item.value) return null
    const arr = []
    if (Array.isArray(item.value)) {
      item.value.forEach((pd, i) => {
        if (typeof pd === 'object' && (pd.id || pd.url)) {
          arr.push({
            id: pd.id || `${item.itemname}_${i + 1}`,
            fileId: pd,
            url: pd.url,
            title: item.itemname,
            description: pd.f_real_name || `${item.itemname} (${i + 1}/${item.value.length})`
          })
        }
      })
    }
    return arr.length ? arr : null
  }

  getDeviceIcon (deviceType) {
    const s = String(deviceType || '')
    if (s.includes('热水器')) return 'fa-shower'
    if (s.includes('壁挂炉') || s.includes('灶') || s.includes('灶具') || s.includes('锅炉')) return 'fa-fire-burner'
    if (s.includes('烤箱')) return 'fa-fire'
    return 'fa-tools'
  }

  extractCheckItems (checkResultJson) {
    const checkItems = []
    checkResultJson.forEach(rs => {
      if (rs.type === 'checkItem' && rs.items) {
        const categoryItems = []
        rs.items.forEach(item => {
          let result = item.value || '--'
          let status = 'unknown'
          if (item.type === 'files') {
            result = item.value ? '正常' : '--'
            status = item.value ? 'pass' : 'unknown'
          } else {
            if (item.f_process_mode) status = 'fail'
            else if (result === '正常' || result === '否') status = 'pass'
            else if (result === '是' && item.options) {
              const opt = item.options.find(o => o.data === result)
              status = opt?.isdefect ? 'fail' : 'pass'
            } else if (typeof result === 'string' && result !== '--') status = 'pass'
            else if (typeof result === 'number') status = 'pass'
          }
          const photos = this.extractCheckItemPhotos(item)
          categoryItems.push({
            name: item.itemname,
            result,
            status,
            processMode: item.f_process_mode || null,
            level: item.level || null,
            aging: item.f_aging || null,
            photos,
            originalItem: { type: item.type, value: item.value, f_defect_paths: item.f_defect_paths }
          })
        })
        if (categoryItems.length) checkItems.push({ category: rs.itemname, items: categoryItems })
      }
    })
    return checkItems
  }

  extractCheckItemPhotos (item) {
    const photos = []
    if (item.type === 'files' && item.value) {
      if (Array.isArray(item.value)) {
        item.value.forEach((pd, i) => {
          if (typeof pd === 'object' && (pd.id || pd.url)) {
            const fileId = pd.id || pd
            photos.push({
              id: pd.id || `${item.itemname}_files_${i + 1}`,
              fileId,
              url: pd.url,
              title: item.itemname,
              description: pd.f_real_name || `${item.itemname} (${i + 1}/${item.value.length})`
            })
          }
        })
      }
    } else if (Array.isArray(item.f_defect_paths) && item.f_defect_paths.length) {
      item.f_defect_paths.forEach((pd, i) => {
        const fileId = typeof pd === 'object' ? (pd.id || pd) : pd
        photos.push({
          id: typeof pd === 'object' ? (pd.id || i) : pd,
          fileId,
          title: item.itemname,
          description: `${item.itemname} - 隐患照片 ${i + 1}`
        })
      })
    }
    return photos
  }

  transformDefectList (defectList) {
    return (defectList || []).map(d => ({
      id: d.id,
      type: d.f_item_type,
      title: d.f_defect_info,
      level: d.f_defect_level,
      levelClass: this.getHazardLevelClass(d.f_defect_level),
      description: `${d.f_item_name}: ${d.f_item_value}`,
      handleMethod: d.f_deal_dispose,
      f_defect_paths: d.f_defect_paths || [],
      f_process_paths: d.f_process_paths || []
    }))
  }

  extractAttachments (signatureForm) {
    const attachments = { signature: {}, recordings: [], filePhotos: [], imagePhotos: [], refusephotos: [], contractPhotos: [] }
    if (signatureForm?.signaturePhoto?.[0]?.url) {
      attachments.signature.imageUrl = signatureForm.signaturePhoto[0].url
    }
    if (signatureForm?.refusephotos) {
      attachments.refusephotos = signatureForm.refusephotos
        .filter(p => p?.url)
        .map(p => ({ imageUrl: p.url }))
    }
    if (signatureForm?.recordFile) {
      attachments.recordings = signatureForm.recordFile
        .filter(p => p?.url)
        .map((r, i) => ({ id: i + 1, name: r.photo_name || `录音 ${i + 1}`, url: r.url || '#' }))
    }
    if (signatureForm?.FilesId) {
      attachments.filePhotos = signatureForm.FilesId
        .filter(p => p?.url)
        .map((p, i) => ({ id: i + 1, url: p.url }))
    }
    if (signatureForm?.Images) {
      attachments.imagePhotos = signatureForm.Images
        .filter(p => p?.url)
        .map((p, i) => ({ id: i + 1, url: p.url }))
    }
    if (signatureForm?.f_contract_photo) {
      attachments.contractPhotos = signatureForm.f_contract_photo
        .filter(p => p?.url)
        .map((p, i) => ({ id: i + 1, url: p.url }))
    }
    return attachments
  }

  async getFormConfigNameByDeviceName (deviceName) {
    try {
      const dic = await getConfigByNameAsync('devicesTypeDic')
      const t = dic?.value?.find(item =>
        item.value === deviceName ||
        item.label === deviceName ||
        deviceName.includes(item.value) ||
        deviceName.includes(item.label)
      )
      return t?.formConfig || null
    } catch (e) {
      return null
    }
  }

  async getFormConfigByDeviceName (deviceName) {
    try {
      const name = await this.getFormConfigNameByDeviceName(deviceName)
      return name ? getConfigByNameAsync(name, 'af-revenue') : null
    } catch (e) {
      return null
    }
  }

  clearCache (id) {
    if (id) {
      Array.from(this.cache.keys())
        .filter(k => k.includes(`detail_${id}`))
        .forEach(k => this.cache.delete(k))
    } else {
      this.cache.clear()
    }
  }

  async getAICheckConfig() {
    return await getConfigByNameAsync('AICheckConfig')
  }
}

export default new InspectionService()
