<template>
  <main class="safety-platform-container__main">
    <el-form
      ref="formRef"
      :model="ruleFormData"
      :rules="formRules"
      label-width="auto"
      class="check-template-form"
    >
      <el-form-item label="检查单模版名称：" prop="templateName">
        <el-input
          v-model="ruleFormData.templateName"
          placeholder="请输入检查单模版名称"
          :disabled="isViewMode"
        />
      </el-form-item>
      <el-form-item label="类别名称：" prop="categoryName">
        <el-select
          v-model="ruleFormData.categoryCode"
          placeholder="请选择类别名称"
          :disabled="isViewMode"
          style="width: 100%"
          @change="onCategoryChange"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.categoryCode"
            :label="item.label"
            :value="item.categoryCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务工作：" prop="businessWork">
        <el-input
          v-model="ruleFormData.businessWork"
          placeholder="请输入业务工作"
          :disabled="isViewMode"
        />
      </el-form-item>
      <el-form-item label="填写说明：" prop="fillInstruction">
        <el-input
          v-model="ruleFormData.fillInstruction"
          type="textarea"
          :rows="5"
          placeholder="请输入填写说明（限300字）"
          :disabled="isViewMode"
          maxlength="300"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <div class="check-items-section">
      <div class="section-header">
        <el-upload
          v-if="isEditMode && props.id"
          :show-file-list="false"
          :http-request="handleImportItem"
          accept=".xlsx,.xls"
        >
          <el-button type="primary" size="small">批量导入明细</el-button>
        </el-upload>
      </div>
      <div class="check-items-table">
        <el-table :data="checkItems" border>
          <el-table-column label="编号" type="index" width="80" align="center" />
          <el-table-column label="检查内容" min-width="180">
            <template #header>
              <span>检查内容<span style="color: red">*</span></span>
            </template>
            <template #default="scope">
              <el-input
                v-model="scope.row.checkContent"
                placeholder="请输入检查内容"
                :disabled="isViewMode"
              />
            </template>
          </el-table-column>
          <el-table-column label="检查标准" min-width="180">
            <template #default="scope">
              <el-input
                v-model="scope.row.checkStandard"
                placeholder="请输入检查标准"
                :disabled="isViewMode"
              />
            </template>
          </el-table-column>
          <el-table-column label="检查结果" min-width="150" align="center">
            <template #default="scope">
              <el-radio-group v-model="scope.row.checkResult" :disabled="isViewMode">
                <el-radio value="合格">合格</el-radio>
                <el-radio value="不合格">不合格</el-radio>
                <el-radio value="待检">待检</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column label="检查发现问题" min-width="200">
            <template #default="scope">
              <el-input
                v-model="scope.row.checkProblem"
                placeholder="请输入检查发现问题"
                :disabled="isViewMode"
              />
            </template>
          </el-table-column>
          <el-table-column v-if="!isViewMode" label="操作" fixed="right" width="350" align="center">
            <template #default="scope">
              <el-button type="primary" link @click="handleAddItem(scope.$index)">新增</el-button>
              <el-button type="primary" link @click="handleMoveUp(scope.$index)">向上插入分类</el-button>
              <el-button type="primary" link @click="handleMoveDown(scope.$index)">向下插入分类</el-button>
              <el-button type="danger" link @click="handleDeleteItem(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">返回</el-button>
    <el-button v-if="!isViewMode" type="primary" @click="handleSubmit">
      {{ isCreateMode ? '提交' : '保存' }}
    </el-button>
  </footer>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import type { FormInstance } from 'element-plus';
  import { CHECK_TEMPLATE_FORM_DATA, CHECK_TEMPLATE_FORM_RULES } from '../configs/form';
  import {
    queryChecklistTemplateDetail,
    saveChecklistTemplate,
    updateChecklistTemplate,
    importChecklistTemplateItem,
    type ChecklistTemplateItem,
  } from '@/api/production-safety-system';
  import { queryDictTypeDetail } from '@/api/dict';

  const props = defineProps<{
    id?: number;
  }>();

  const router = useRouter();
  const route = useRoute();

  const operate = computed(() => (route.query.operate as string) || 'check-template-create');
  const isCreateMode = computed(() => operate.value === 'check-template-create');
  const isEditMode = computed(() => operate.value === 'check-template-edit');
  const isViewMode = computed(() => operate.value === 'check-template-view');

  const formRef = ref<FormInstance>();
  const ruleFormData = ref({ ...CHECK_TEMPLATE_FORM_DATA });
  const formRules = CHECK_TEMPLATE_FORM_RULES;

  const checkItems = ref<CheckItemRow[]>([]);

  interface CategoryOption {
    label: string;
    categoryName: string;
    categoryCode: string;
  }

  const categoryOptions = ref<CategoryOption[]>([]);

  const loadCategoryOptions = async () => {
    try {
      const res = await queryDictTypeDetail('checklist_template');
      categoryOptions.value = (res?.sysDictDataList || []).map((item) => ({
        label: item.itemValue,
        categoryName: item.itemValue,
        categoryCode: item.itemCode,
      }));
    } catch (e) {
      console.error('获取类别名称字典失败:', e);
    }
  };

  const onCategoryChange = (categoryCode: string) => {
    const opt = categoryOptions.value.find((c) => c.categoryCode === categoryCode);
    if (opt) ruleFormData.value.categoryName = opt.categoryName;
  };

  interface CheckItemRow {
    id?: number;
    templateId?: number;
    checkContent: string;
    checkStandard: string;
    checkResult: string; // 合格/不合格/待检
    checkProblem: string;
  }

  const handleValidate = async () => {
    if (!formRef.value) return;
    return new Promise((resolve) => {
      formRef.value?.validate((valid: boolean) => {
        resolve(valid);
      });
    });
  };

  const handleAddItem = (index: number) => {
    checkItems.value.splice(index + 1, 0, createEmptyCheckItem());
  };

  /** 向上插入分类：在当前行之前插入一条空白数据 */
  const handleMoveUp = (index: number) => {
    checkItems.value.splice(index, 0, createEmptyCheckItem());
  };

  /** 向下插入分类：在当前行之后插入一条空白数据 */
  const handleMoveDown = (index: number) => {
    checkItems.value.splice(index + 1, 0, createEmptyCheckItem());
  };

  const handleDeleteItem = (index: number) => {
    if (checkItems.value.length <= 1) {
      ElMessage.warning('至少需要保留一条数据');
      return;
    }
    checkItems.value.splice(index, 1);
  };

  const handleImportItem = async (options: { file: File }) => {
    if (!props.id) return;
    try {
      await importChecklistTemplateItem(options.file, props.id);
      ElMessage.success('导入成功');
      await getDetail();
    } catch (e: any) {
      ElMessage.error(e?.message || e?.data || '导入失败');
    }
  };

  const getDetail = async () => {
    if (!props.id) return;

    try {
      const detail = await queryChecklistTemplateDetail(props.id);
      if (!detail) return;

      ruleFormData.value.templateName = detail.templateName || '';
      ruleFormData.value.categoryName = detail.categoryName || '';
      ruleFormData.value.categoryCode = detail.categoryCode || '';
      ruleFormData.value.businessWork = detail.businessWork || '';
      ruleFormData.value.fillInstruction = detail.fillInstruction || '';

      const items = detail.ChecklistTemplateItem;
      if (items && items.length > 0) {
        checkItems.value = items
          .filter((it) => !it.isDeleted || it.isDeleted === 0)
          .map((item) => ({
            id: item.id,
            templateId: item.templateId,
            checkContent: item.checkContent || '',
            checkStandard: item.checkStandard || '',
            checkResult: item.checkResult || '待检',
            checkProblem: item.checkProblem || '',
          }));
      }
      if (checkItems.value.length === 0) checkItems.value = [createEmptyCheckItem()];
    } catch (e: any) {
      console.error('获取检查单模版详情失败:', e);
      ElMessage.error(e?.message || e?.data || '获取详情失败，请重试');
    }
  };

  const createEmptyCheckItem = (): CheckItemRow => ({
    checkContent: '',
    checkStandard: '',
    checkResult: '待检',
    checkProblem: '',
  });

  const validateCheckItems = (): boolean => {
    for (let i = 0; i < checkItems.value.length; i++) {
      const item = checkItems.value[i];
      if (!item.checkContent || !item.checkContent.trim()) {
        ElMessage.warning(`第 ${i + 1} 行的检查内容不能为空`);
        return false;
      }
    }
    return true;
  };

  const handleSubmit = async () => {
    const valid = await handleValidate();
    if (!valid) return;

    if (!validateCheckItems()) return;

    try {
      const items: ChecklistTemplateItem[] = checkItems.value.map((item) => ({
        id: item.id,
        templateId: props.id ?? item.templateId,
        checkContent: item.checkContent || '',
        checkStandard: item.checkStandard || '',
        checkResult: item.checkResult || '待检',
        checkProblem: item.checkProblem || '',
        isDeleted: 0,
      }));

      const payload = {
        templateName: ruleFormData.value.templateName || '',
        categoryName: ruleFormData.value.categoryName || '',
        categoryCode: ruleFormData.value.categoryCode || '',
        businessWork: ruleFormData.value.businessWork || '',
        fillInstruction: ruleFormData.value.fillInstruction || '',
        ChecklistTemplateItem: items,
      };

      if (isEditMode.value && props.id) {
        await updateChecklistTemplate({ id: props.id, ...payload });
        ElMessage.success('保存成功');
      } else {
        await saveChecklistTemplate(payload);
        ElMessage.success('创建成功');
      }

      router.back();
    } catch (e: any) {
      console.error('保存检查单模版失败:', e);
      ElMessage.error(e?.message || e?.data || '保存失败，请重试');
    }
  };

  onMounted(async () => {
    await loadCategoryOptions();
    if (isEditMode.value || isViewMode.value) {
      await getDetail();
    } else {
      checkItems.value = [createEmptyCheckItem()];
    }
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;

  .check-template-form {
    display: flex;
    flex-direction: column;
    width: 600px;
    gap: 32px;

    :deep(.el-form-item) {
      margin-bottom: 0;
    }

    :deep(.el-form-item__label) {
      padding: 0;
    }
  }

  .check-items-section {
    margin-top: 32px;
  }

  .section-header {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
  }

  .check-items-table {
    width: 100%;
  }
</style>
