<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1100px">
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" :row-key="getRowKey">
      <el-table-column type="index" :label="t('MoldManagement.TicketResultDialog.index')" align="center" width="70" />
      <el-table-column :label="t('MoldManagement.TicketResultDialog.inspectionItemName')" align="center" prop="inspectionItemName" min-width="200" />
      <el-table-column :label="t('MoldManagement.TicketResultDialog.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('MoldManagement.TicketResultDialog.judgmentCriteria')" align="center" prop="judgmentCriteria" min-width="180" />
      <el-table-column :label="t('MoldManagement.TicketResultDialog.inspectionResult')" align="center" prop="inspectionResult" min-width="140">
        <template #default="scope">
          <el-tag v-if="String(scope.row.inspectionResult) === '0'" type="info">{{ t('MoldManagement.TicketResultDialog.inspectionResultPending') }}</el-tag>
          <el-tag v-else-if="String(scope.row.inspectionResult) === '1'" type="success">{{ t('MoldManagement.TicketResultDialog.inspectionResultPass') }}</el-tag>
          <el-tag v-else-if="String(scope.row.inspectionResult) === '2'" type="danger">{{ t('MoldManagement.TicketResultDialog.inspectionResultFail') }}</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.TicketResultDialog.images')" align="center" prop="images" min-width="180">
        <template #default="scope">
          <UploadImg
v-if="String(scope.row.inspectionResult) === '0'" v-model="imageMap[String(scope.row.id)]"
            :drag="false" :show-btn-text="false" width="64px" height="64px" />
          <el-image
v-else-if="scope.row.images" :src="parseFirstImage(scope.row.images)"
            :preview-src-list="parseImages(scope.row.images)" preview-teleported fit="cover"
            style="width: 64px; height: 64px" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.TicketResultDialog.remark')" align="center" prop="remark" min-width="180" />
      <el-table-column :label="t('MoldManagement.TicketResultDialog.operate')" align="center" min-width="220" 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('MoldManagement.TicketResultDialog.pass') }}</el-radio>
            <el-radio :label="'2'">{{ t('MoldManagement.TicketResultDialog.fail') }}</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"
      :background="true" :page-sizes="[10, 20, 30, 50, 100]" :pager-count="7" :total="total"
      class="mt-15px mb-15px flex justify-end" layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <template #footer>
      <el-button @click="dialogVisible = false">{{ t('MoldManagement.TicketResultDialog.cancel') }}</el-button>
      <el-button type="primary" @click="handleSave" :loading="submitLoading">{{ t('MoldManagement.TicketResultDialog.save') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { TicketManagementApi, TicketResultVO } from '@/api/mold/ticketManagement'

defineOptions({ name: 'TicketResultDialog' })

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

const dialogVisible = ref(false)
const dialogTitle = ref('检验结果')
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 queryParams = reactive({
  pageNo: 1,
  pageSize: 10
})

const open = async (options: { managementId: number; title?: string }) => {
  dialogVisible.value = true
  dialogTitle.value = options.title || t('MoldManagement.TicketResultDialog.moduleName')
  managementId.value = options.managementId
  for (const key of Object.keys(decisionMap)) delete decisionMap[key]
  for (const key of Object.keys(imageMap)) delete imageMap[key]
  queryParams.pageNo = 1
  await getList()
}

defineExpose({ open })

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

    for (const row of list.value) {
      const id = row?.id
      if (!id) continue
      if (row.images && !imageMap[String(id)]) {
        imageMap[String(id)] = parseFirstImage(row.images)
      }
    }
  } finally {
    loading.value = false
  }
}

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 img = imageMap[String(row.id)]
    payload.push({ ...(row as any), inspectionResult: decision, images: img || row.images })
  }
  if (!payload.length) {
    message.error(t('MoldManagement.TicketResultDialog.selectDecisionTip'))
    return
  }
  submitLoading.value = true
  try {
    await TicketManagementApi.batchUpdateTicketResults(payload)
    message.success(t('MoldManagement.TicketResultDialog.updateSuccess'))
    dialogVisible.value = false
  } catch {
    message.error(t('MoldManagement.TicketResultDialog.updateFail'))
  } finally {
    submitLoading.value = false
  }
}

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

const parseFirstImage = (value: any): string => {
  return parseImages(value)[0] || ''
}
</script>

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