<script lang="ts" setup>
import type { InspectionApi } from '#/api/asset/inspection';

import { computed, ref, watch } from 'vue';

import {
  Button,
  Collapse,
  CollapsePanel,
  Image,
  Input,
  InputNumber,
  message,
  RadioButton,
  RadioGroup,
  Space,
  Spin,
  Upload,
} from 'ant-design-vue';

import {
  completeInspection,
  getInspectionRecord,
  updateInspectionRecordItem,
} from '#/api/asset/inspection';

const props = defineProps<{
  recordId: number;
  readonly?: boolean;
  onComplete?: () => void;
}>();

const loading = ref(false);
const submitting = ref(false);
const record = ref<InspectionApi.RecordDetail>();
const inspectorName = ref('');

// Group items by category
const groupedItems = computed(() => {
  if (!record.value?.items) return [];
  const map = new Map<string, InspectionApi.RecordItem[]>();
  for (const item of record.value.items) {
    const list = map.get(item.category) || [];
    list.push(item);
    map.set(item.category, list);
  }
  return [...map.entries()].map(([category, items]) => ({
    category,
    items,
  }));
});

// Active collapse keys (all open by default)
const activeKeys = computed(() =>
  groupedItems.value.map((g) => g.category),
);

// Whether inspection is already completed
const isCompleted = computed(() => record.value?.status === 2);

// Load inspection record
async function loadRecord() {
  if (!props.recordId) return;
  loading.value = true;
  try {
    record.value = await getInspectionRecord(props.recordId);
    inspectorName.value = record.value.inspectorName || '';
  } finally {
    loading.value = false;
  }
}

watch(
  () => props.recordId,
  () => loadRecord(),
  { immediate: true },
);

// Save single item on change
async function handleItemChange(item: InspectionApi.RecordItem) {
  if (props.readonly || isCompleted.value) return;
  try {
    await updateInspectionRecordItem({
      id: item.id,
      result: item.result,
      value: item.value,
      remark: item.remark,
      imageUrls: item.imageUrls,
    });
  } catch {
    message.error('保存检查项失败');
  }
}

// Complete inspection
async function handleComplete() {
  if (!inspectorName.value) {
    message.warning('请输入验车人姓名');
    return;
  }
  submitting.value = true;
  try {
    await completeInspection(props.recordId, inspectorName.value);
    message.success('验车完成');
    await loadRecord();
    props.onComplete?.();
  } catch {
    message.error('完成验车失败');
  } finally {
    submitting.value = false;
  }
}

// Result options for checkbox type
const resultOptions = [
  { label: '合格', value: 1 },
  { label: '不合格', value: 2 },
  { label: '不适用', value: 3 },
];

// Parse image URLs
function parseImageUrls(urls?: string): string[] {
  if (!urls) return [];
  return urls.split(',').filter(Boolean);
}

// Handle image upload (simplified - assumes backend returns URL)
function handleImageUpload(item: InspectionApi.RecordItem, info: any) {
  if (info.file.status === 'done' && info.file.response) {
    const url = info.file.response.data;
    const urls = parseImageUrls(item.imageUrls);
    urls.push(url);
    item.imageUrls = urls.join(',');
    handleItemChange(item);
  }
}

// Determine if inputs should be disabled
const isDisabled = computed(() => props.readonly || isCompleted.value);
</script>

<template>
  <Spin :spinning="loading">
    <div class="inspection-form">
      <!-- Inspector name -->
      <div class="mb-4 flex items-center gap-4">
        <label class="font-medium">验车人：</label>
        <Input
          v-model:value="inspectorName"
          :disabled="isDisabled"
          placeholder="请输入验车人姓名"
          style="width: 200px"
        />
        <span v-if="record?.inspectionTime" class="text-gray-500">
          验车时间：{{ record.inspectionTime }}
        </span>
        <span
          v-if="isCompleted"
          class="rounded bg-green-100 px-2 py-1 text-sm text-green-700"
        >
          已完成
        </span>
      </div>

      <!-- Inspection items grouped by category -->
      <Collapse :active-key="activeKeys" :bordered="true">
        <CollapsePanel
          v-for="group in groupedItems"
          :key="group.category"
          :header="group.category"
        >
          <div class="space-y-4">
            <div
              v-for="item in group.items"
              :key="item.id"
              class="rounded border border-gray-200 p-3"
            >
              <div class="mb-2 flex items-start justify-between">
                <span class="font-medium">{{ item.itemName }}</span>
                <span class="text-xs text-gray-400">{{ item.itemCode }}</span>
              </div>

              <div class="flex flex-wrap items-start gap-4">
                <!-- Checkbox type: radio group -->
                <div v-if="item.inputType === 'checkbox'" class="flex-1">
                  <RadioGroup
                    v-model:value="item.result"
                    :disabled="isDisabled"
                    button-style="solid"
                    size="small"
                    @change="handleItemChange(item)"
                  >
                    <RadioButton
                      v-for="opt in resultOptions"
                      :key="opt.value"
                      :value="opt.value"
                    >
                      {{ opt.label }}
                    </RadioButton>
                  </RadioGroup>
                </div>

                <!-- Number type: input number -->
                <div v-else-if="item.inputType === 'number'" class="flex-1">
                  <InputNumber
                    v-model:value="item.value"
                    :disabled="isDisabled"
                    placeholder="请输入数值"
                    size="small"
                    style="width: 200px"
                    @change="handleItemChange(item)"
                  />
                </div>

                <!-- Text type: input -->
                <div v-else class="flex-1">
                  <Input
                    v-model:value="item.value"
                    :disabled="isDisabled"
                    placeholder="请输入"
                    size="small"
                    style="width: 300px"
                    @change="handleItemChange(item)"
                  />
                </div>

                <!-- Remark -->
                <div class="flex-1">
                  <Input
                    v-model:value="item.remark"
                    :disabled="isDisabled"
                    placeholder="备注"
                    size="small"
                    @change="handleItemChange(item)"
                  />
                </div>
              </div>

              <!-- Images -->
              <div class="mt-2">
                <Space :size="8" wrap>
                  <Image
                    v-for="(url, idx) in parseImageUrls(item.imageUrls)"
                    :key="idx"
                    :src="url"
                    :width="60"
                    :height="60"
                    style="object-fit: cover; border-radius: 4px"
                  />
                  <Upload
                    v-if="!isDisabled"
                    :show-upload-list="false"
                    action="/admin-api/infra/file/upload"
                    name="file"
                    accept="image/*"
                    @change="(info: any) => handleImageUpload(item, info)"
                  >
                    <Button size="small" type="dashed">上传图片</Button>
                  </Upload>
                </Space>
              </div>
            </div>
          </div>
        </CollapsePanel>
      </Collapse>

      <!-- Overall remark -->
      <div v-if="record" class="mt-4">
        <label class="mb-1 block font-medium">整体备注：</label>
        <Input.TextArea
          v-model:value="record.remark"
          :disabled="isDisabled"
          :rows="3"
          placeholder="请输入整体备注"
        />
      </div>

      <!-- Complete button -->
      <div v-if="!isDisabled" class="mt-4 text-right">
        <Button
          type="primary"
          :loading="submitting"
          @click="handleComplete"
        >
          完成验车
        </Button>
      </div>
    </div>
  </Spin>
</template>
