<template>
  <div class="ticket-result-page">
    <ContentWrap>
      <div class="ticket-result-header">
        <el-button @click="handleClose">{{ t('common.back') }}</el-button>
        <span class="ticket-result-title">{{ pageTitle }}</span>
      </div>

      <el-descriptions :title="t('EquipmentManagement.WorkOrderManagement.basicInfo')" :column="4" border>
        <el-descriptions-item :label="t('EquipmentManagement.WorkOrderManagement.planNo')">
          {{ currentRow?.planNo || '-' }}
        </el-descriptions-item>
        <el-descriptions-item :label="t('EquipmentManagement.WorkOrderManagement.deviceName')">
          {{ currentRow?.deviceName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item :label="t('EquipmentManagement.WorkOrderManagement.planType')">
          <el-tag v-if="String(currentRow?.planType) === '1'" type="primary">
            {{ t('EquipmentManagement.WorkOrderManagement.planTypeInspect') }}
          </el-tag>
          <el-tag v-else-if="String(currentRow?.planType) === '2'" type="success">
            {{ t('EquipmentManagement.WorkOrderManagement.planTypeMaintain') }}
          </el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item :label="t('EquipmentManagement.WorkOrderManagement.jobStatus')">
          <dict-tag :type="'job_status'" :value="jobStatus" />
        </el-descriptions-item>
        <el-descriptions-item :label="t('EquipmentManagement.WorkOrderManagement.configName')">
          {{ currentRow?.configName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item :label="t('EquipmentManagement.WorkOrderManagement.operatorName')">
          {{ currentRow?.operatorName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item :label="t('EquipmentManagement.WorkOrderManagement.taskTime')">
          {{ formatDisplayTime(currentRow?.taskTime) }}
        </el-descriptions-item>
        <el-descriptions-item :label="t('EquipmentManagement.WorkOrderManagement.taskEndTime')">
          {{ formatDisplayTime(currentRow?.taskEndTime) }}
        </el-descriptions-item>
        <el-descriptions-item :label="t('EquipmentManagement.WorkOrderManagement.jobResult')">
          <el-tag v-if="currentRow?.jobResult == '1' || currentRow?.jobResult == 'OK'" type="success">
            {{ t('EquipmentManagement.WorkOrderManagement.jobResultOk') }}
          </el-tag>
          <el-tag v-else-if="currentRow?.jobResult == '2' || currentRow?.jobResult == 'NG'" type="danger">
            {{ t('EquipmentManagement.WorkOrderManagement.jobResultNg') }}
          </el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item v-if="String(jobStatus) === '4'"
          :label="t('EquipmentManagement.WorkOrderManagement.cancelReason')" :span="3">
          {{ cancelReason || '-' }}
        </el-descriptions-item>
      </el-descriptions>
    </ContentWrap>

    <ContentWrap>
      <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" :row-key="getRowKey">
        <el-table-column type="index" :label="t('EquipmentManagement.WorkOrderManagement.index')" align="center" width="70" />
        <el-table-column :label="t('EquipmentManagement.WorkOrderManagement.inspectionItemName')" align="center"
          prop="inspectionItemName" min-width="200" sortable />
        <el-table-column :label="t('EquipmentManagement.WorkOrderManagement.inspectionMethod')" align="center"
          prop="inspectionMethod" min-width="160">
          <template #default="scope">
            <dict-tag type="Inspection_method" :value="scope.row.inspectionMethod" />
          </template>
        </el-table-column>
        <el-table-column :label="t('EquipmentManagement.WorkOrderManagement.judgmentCriteria')" align="center"
          prop="judgmentCriteria" min-width="180" />
        <el-table-column :label="t('EquipmentManagement.WorkOrderManagement.inspectionResult')" align="center"
          prop="inspectionResult" min-width="140">
          <template #default="scope">
            <el-tag v-if="String(scope.row.inspectionResult) === '0'" type="info">{{
              t('EquipmentManagement.WorkOrderManagement.jobResultPending') }}</el-tag>
            <el-tag v-else-if="String(scope.row.inspectionResult) === '1'" type="success">{{
              t('EquipmentManagement.WorkOrderManagement.jobResultOk') }}</el-tag>
            <el-tag v-else-if="String(scope.row.inspectionResult) === '2'" type="danger">{{
              t('EquipmentManagement.WorkOrderManagement.jobResultNg') }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('EquipmentManagement.WorkOrderManagement.images')" align="center" prop="images" min-width="260">
          <template #default="scope">
            <div v-if="String(scope.row.inspectionResult) === '0'" v-loading="isImageUploading(String(scope.row.id))"
              :element-loading-text="t('EquipmentManagement.WorkOrderManagement.uploading')" class="ticket-result-images"
              :class="{ 'is-full': (imageMap[String(scope.row.id)] || []).length >= 3 }">
              <UploadImgs v-model="imageMap[String(scope.row.id)]" :limit="3" width="64px" height="64px"
                @uploading-change="setImageUploading(String(scope.row.id), $event)" />
            </div>
            <div v-else-if="parseImages(scope.row.images).length" class="ticket-result-images">
              <el-image v-for="image in parseImages(scope.row.images)" :key="image" :src="image"
                :preview-src-list="parseImages(scope.row.images)" preview-teleported fit="cover"
                class="ticket-result-image" />
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('EquipmentManagement.DvSubject.valueType')" align="center" prop="valueType" width="120" sortable>
          <template #default="scope">
            <el-tag
              v-if="scope.row.valueType !== undefined && scope.row.valueType !== null && String(scope.row.valueType) !== ''"
              effect="light" :type="getTagType('value_types', scope.row.valueType)"
              :color="getTagColor('value_types', scope.row.valueType)"
              :style="getTagStyle('value_types', scope.row.valueType)" disable-transitions>
              {{ getTagLabel('value_types', scope.row.valueType) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('EquipmentManagement.WorkOrderManagement.inputValue')" align="center" min-width="200">
          <template #default="scope">
            <el-input
              v-if="String(scope.row.valueType) === '0' || String(scope.row.valueType) === '2'"
              v-model="scope.row.textInput"
              :disabled="String(scope.row.inspectionResult) !== '0'"
              clearable
              :rows="2"
              type="textarea"
              style="resize: both;"
              :placeholder="t('EquipmentManagement.WorkOrderManagement.placeholderInputValue')"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('EquipmentManagement.WorkOrderManagement.remark')" align="center" prop="remark" min-width="180" />
        <el-table-column :label="t('EquipmentManagement.WorkOrderManagement.operate')" align="center" width="200" fixed="right">
          <template #default="scope">
            <el-radio-group v-if="String(scope.row.inspectionResult) === '0'" v-model="decisionMap[String(scope.row.id)]">
              <el-radio :label="'1'">{{ t('EquipmentManagement.WorkOrderManagement.ok') }}</el-radio>
              <el-radio :label="'2'">{{ t('EquipmentManagement.WorkOrderManagement.ng') }}</el-radio>
            </el-radio-group>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-show="total > 0"
        v-model:current-page="queryParams.pageNo"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total" class="mt-15px mb-15px flex justify-end"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />

      <div class="ticket-result-footer">
        <el-button v-if="String(jobStatus) === '0'" type="primary" @click="handleSave" :loading="submitLoading"
          :disabled="hasImageUploading">
          {{ t('EquipmentManagement.WorkOrderManagement.dialogSave') }}
        </el-button>
      </div>
    </ContentWrap>
  </div>
</template>

<script setup lang="ts">
import { formatDate } from '@/utils/formatTime'
import { getStrDictOptions } from '@/utils/dict'
import { useDictStoreWithOut } from '@/store/modules/dict'
import { TicketManagementApi, TicketResultVO } from '@/api/mes/ticketManagement'
import { isHexColor } from '@/utils/color'
import UploadImgs from '@/components/UploadFile/src/UploadImgs.vue'

const { t } = useI18n()
const message = useMessage()
const dictStore = useDictStoreWithOut()

const props = defineProps<{
  ticketRow?: any
  title?: string
}>()

const emit = defineEmits<{
  success: []
  closed: []
}>()

const dictReady = ref(false)
const pageTitle = computed(() => props.title || t('EquipmentManagement.WorkOrderManagement.dialogTitleDefault'))

const currentRow = computed(() => props.ticketRow)
const jobStatus = computed(() => props.ticketRow?.jobStatus)
const cancelReason = computed(() => props.ticketRow?.cancelReason)

const loading = ref(false)
const submitLoading = ref(false)
const list = ref<TicketResultVO[]>([])
const total = ref(0)
const managementId = ref<number | undefined>(undefined)
const decisionMap = reactive<Record<string, '1' | '2' | undefined>>({})
const imageMap = reactive<Record<string, string[]>>({})
const imageUploadingMap = reactive<Record<string, boolean>>({})

const hasImageUploading = computed(() => Object.values(imageUploadingMap).some(Boolean))

const setImageUploading = (key: string, value: boolean) => {
  if (!key) return
  if (value) {
    imageUploadingMap[key] = true
  } else {
    delete imageUploadingMap[key]
  }
}

const isImageUploading = (key: string) => {
  return !!imageUploadingMap[key]
}

const getTagDict = (dictType: string, value: any) => {
  if (!dictReady.value) return undefined
  const v = value === '' || value === null || value === undefined ? undefined : String(value)
  if (!v) return undefined
  return getStrDictOptions(dictType).find((d) => d.value === v)
}

const getTagLabel = (dictType: string, value: any) => {
  const found = getTagDict(dictType, value)
  return found?.label ?? (value ?? '')
}

const getTagType = (dictType: string, value: any) => {
  const found = getTagDict(dictType, value)
  const type = found?.colorType
  if (type + '' === 'primary' || type + '' === 'default') return '' as any
  return (type ?? '') as any
}

const getTagColor = (dictType: string, value: any) => {
  const found = getTagDict(dictType, value)
  if (found?.cssClass && isHexColor(found.cssClass)) return found.cssClass
  return ''
}

const getTagStyle = (dictType: string, value: any) => {
  const color = getTagColor(dictType, value)
  if (!color) return ''
  return 'color: #fff'
}

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10
})

const resetResultState = () => {
  for (const key of Object.keys(decisionMap)) delete decisionMap[key]
  for (const key of Object.keys(imageMap)) delete imageMap[key]
  for (const key of Object.keys(imageUploadingMap)) delete imageUploadingMap[key]
  
  list.value = []
  total.value = 0
  queryParams.pageNo = 1
}

onMounted(async () => {
  await dictStore.setDictMap()
  dictReady.value = true
})

const getList = async () => {
  const id = managementId.value
  if (!id) return
  loading.value = true
  try {
    const data = await TicketManagementApi.getTicketResultsPage({
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      managementId: id
    })
    list.value = data.list
    total.value = data.total

    for (const row of list.value) {
      const id = row?.id
      if (!id) continue
      if (!imageMap[String(id)]) {
        imageMap[String(id)] = parseImages(row.images).slice(0, 3)
      }
    }
  } finally {
    loading.value = false
  }
}

watch(
  () => props.ticketRow?.id,
  async (id) => {
    resetResultState()
    managementId.value = id
    if (id) await getList()
  },
  { immediate: true }
)

const handleSizeChange = () => {
  queryParams.pageNo = 1
  getList()
}

const handleCurrentChange = () => {
  getList()
}


const handleSave = async () => {
  const payload: TicketResultVO[] = []
  for (const row of list.value) {
    if (!row?.id) continue
    if (String(row.inspectionResult) !== '0') continue
    const decision = decisionMap[String(row.id)]
    if (!decision) continue
    const images = imageMap[String(row.id)]
    payload.push({ ...(row as any), inspectionResult: decision, images: Array.isArray(images) ? images.join(',') : row.images })
  }
  if (!payload.length) {
    message.error(t('EquipmentManagement.WorkOrderManagement.selectDecisionError'))
    return
  }
  submitLoading.value = true
  try {
    await TicketManagementApi.batchUpdateTicketResults(payload)
    message.success(t('EquipmentManagement.WorkOrderManagement.updateSuccess'))
    emit('success')
  } catch {
    message.error(t('EquipmentManagement.WorkOrderManagement.updateFail'))
  } finally {
    submitLoading.value = false
  }
}

const handleClose = () => {
  emit('closed')
}

const formatDisplayTime = (value: any) => {
  return value ? formatDate(value) : '-'
}

const getRowKey = (row: TicketResultVO) => {
  return String(row.id ?? '')
}

const parseImages = (value: any): string[] => {
  if (!value) return []
  if (Array.isArray(value)) return value.map(String).filter(Boolean)
  return String(value)
    .split(',')
    .map((v) => v.trim())
    .filter(Boolean)
}

</script>

<style scoped lang="scss">
:deep(.el-upload) {
  margin: 0 auto;
}

.ticket-result-images {
  display: flex;
  justify-content: center;
  min-height: 64px;
}

.ticket-result-images :deep(.el-upload-list--picture-card) {
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
  gap: 8px;
}

.ticket-result-images.is-full :deep(.el-upload--picture-card) {
  display: none;
}

.ticket-result-image {
  width: 64px;
  height: 64px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
  margin-right: 6px;
}

.ticket-result-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.ticket-result-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.ticket-result-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
