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

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import {
  Button,
  Card,
  Input,
  InputNumber,
  message,
  Select,
  Table,
} from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  createInspectionTemplate,
  getInspectionTemplate,
  updateInspectionTemplate,
} from '#/api/asset/inspection';
import { $t } from '#/locales';

import { INPUT_TYPE_OPTIONS, useFormSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<InspectionApi.Template>();
const items = ref<InspectionApi.TemplateItem[]>([]);

const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['验车模板'])
    : $t('ui.actionTitle.create', ['验车模板']);
});

const [BasicForm, basicFormApi] = useVbenForm({
  commonConfig: {
    componentProps: { class: 'w-full' },
    formItemClass: 'col-span-2',
    labelWidth: 120,
  },
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-4',
});

// 检查项列定义
const itemColumns = [
  { title: '序号', key: 'index', width: 60 },
  { title: '分类', key: 'category', width: 140 },
  { title: '检查项名称', key: 'itemName', width: 180 },
  { title: '检查项编码', key: 'itemCode', width: 140 },
  { title: '输入类型', key: 'inputType', width: 160 },
  { title: '排序', key: 'sort', width: 80 },
  { title: '必填', key: 'required', width: 80 },
  { title: '操作', key: 'action', width: 80, fixed: 'right' as const },
];

function handleAddItem() {
  items.value.push({
    category: '',
    itemName: '',
    itemCode: '',
    inputType: 'checkbox',
    sort: items.value.length,
    required: 1,
  });
}

function handleDeleteItem(index: number) {
  items.value.splice(index, 1);
}

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await basicFormApi.validate();
    if (!valid) return;

    if (items.value.length === 0) {
      message.warning('请至少添加一个检查项');
      return;
    }

    // 校验检查项必填字段
    for (let i = 0; i < items.value.length; i++) {
      const item = items.value[i]!;
      if (!item.category || !item.itemName || !item.itemCode) {
        message.warning(`第 ${i + 1} 项的分类、名称、编码不能为空`);
        return;
      }
    }

    modalApi.lock();
    const data = (await basicFormApi.getValues()) as InspectionApi.Template;
    data.items = items.value;

    try {
      await (formData.value?.id
        ? updateInspectionTemplate(data)
        : createInspectionTemplate(data));
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      items.value = [];
      return;
    }

    const data = modalApi.getData<InspectionApi.Template>();
    if (!data || !data.id) return;

    modalApi.lock();
    try {
      formData.value = await getInspectionTemplate(data.id);
      await basicFormApi.setValues(formData.value);
      items.value = formData.value.items || [];
    } finally {
      modalApi.unlock();
    }
  },
});
</script>

<template>
  <Modal :title="getTitle" class="w-4/5" style="max-width: 1200px">
    <div class="space-y-4" style="max-height: 75vh; overflow-y: auto">
      <!-- 基本信息 -->
      <Card title="基本信息" size="small">
        <BasicForm />
      </Card>

      <!-- 检查项列表 -->
      <Card title="检查项" size="small">
        <Table
          :columns="itemColumns"
          :data-source="items"
          :pagination="false"
          :scroll="{ x: 900 }"
          size="small"
          bordered
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'index'">
              {{ index + 1 }}
            </template>
            <template v-else-if="column.key === 'category'">
              <Input
                v-model:value="record.category"
                placeholder="分类"
                size="small"
              />
            </template>
            <template v-else-if="column.key === 'itemName'">
              <Input
                v-model:value="record.itemName"
                placeholder="检查项名称"
                size="small"
              />
            </template>
            <template v-else-if="column.key === 'itemCode'">
              <Input
                v-model:value="record.itemCode"
                placeholder="编码"
                size="small"
              />
            </template>
            <template v-else-if="column.key === 'inputType'">
              <Select
                v-model:value="record.inputType"
                :options="INPUT_TYPE_OPTIONS"
                size="small"
                style="width: 100%"
              />
            </template>
            <template v-else-if="column.key === 'sort'">
              <InputNumber
                v-model:value="record.sort"
                :min="0"
                size="small"
                style="width: 100%"
              />
            </template>
            <template v-else-if="column.key === 'required'">
              <Select
                v-model:value="record.required"
                :options="[
                  { label: '是', value: 1 },
                  { label: '否', value: 0 },
                ]"
                size="small"
                style="width: 100%"
              />
            </template>
            <template v-else-if="column.key === 'action'">
              <Button
                type="link"
                danger
                size="small"
                @click="handleDeleteItem(index)"
              >
                删除
              </Button>
            </template>
          </template>
        </Table>
        <Button type="dashed" block class="mt-3" @click="handleAddItem">
          + 添加检查项
        </Button>
      </Card>
    </div>
  </Modal>
</template>
