<template>
  <div class="page-container">
    <div class="header">
      <a-typography-title :heading="4" style="margin: 0">设备导入清洗公式模板</a-typography-title>
      <a-space>
        <a-upload :show-file-list="false" :custom-request="handleImport" accept=".xlsx">
            <template #upload-button>
                <a-button>
                    <template #icon><icon-upload /></template>
                    导入
                </a-button>
            </template>
        </a-upload>
        <a-button @click="handleExport">
            <template #icon><icon-download /></template>
            导出
        </a-button>
        <a-button type="primary" @click="openDialog()">
            <template #icon><icon-plus /></template>
            新增模板
        </a-button>
      </a-space>
    </div>

    <a-card :bordered="false">
      <a-table :data="tableData" :loading="loading" style="width: 100%" :pagination="{ pageSize: 10 }">
        <template #columns>
          <a-table-column title="模板名称" data-index="name" :width="200" />
          <a-table-column title="设备类型" data-index="equipmentType" :width="150">
            <template #cell="{ record }">
              <a-tag>{{ record.equipmentType }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="清洗公式配置" data-index="formula">
            <template #cell="{ record }">
              <a-popover title="配置详情" position="right">
                <a-typography-text code class="code-text" style="cursor: pointer; max-width: 300px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; display: block;">
                  {{ JSON.stringify(record.formula) }}
                </a-typography-text>
                <template #content>
                   <pre style="max-height: 400px; overflow: auto;">{{ JSON.stringify(record.formula, null, 2) }}</pre>
                </template>
              </a-popover>
            </template>
          </a-table-column>
          <a-table-column title="描述" data-index="description" />
          <a-table-column title="创建时间" data-index="createdAt" :width="180">
            <template #cell="{ record }">
              {{ formatTime(record.createdAt) }}
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="180">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="openDialog(record)">编辑</a-button>
                <a-button type="text" status="danger" size="small" @click="handleDelete(record)">删除</a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- Template Dialog -->
    <a-modal v-model:visible="dialogVisible" :title="form.id ? '编辑模板' : '新增模板'" width="800px" @ok="handleSubmit">
      <a-form :model="form" layout="vertical" ref="formRef">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="name" label="模板名称" :rules="[{ required: true, message: '请输入模板名称' }]">
              <a-input v-model="form.name" placeholder="例如：标准电力设备清洗模板" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="equipmentType" label="设备类型" :rules="[{ required: true, message: '请输入设备类型' }]">
              <a-select v-model="form.equipmentType" placeholder="请选择设备类型" allow-create>
                 <a-option v-for="item in DEVICE_TYPES" :key="item.value" :value="item.value">{{ item.label }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item field="description" label="描述">
          <a-textarea v-model="form.description" placeholder="请输入模板描述" />
        </a-form-item>

        <a-divider orientation="left">公式配置 (JSON)</a-divider>
        <a-form-item field="formulaStr" label="配置内容" :rules="[{ required: true, validator: validateJson }]">
           <a-textarea v-model="form.formulaStr" :auto-size="{ minRows: 5, maxRows: 15 }" placeholder='{ "voltage": "x * 1", "current": "x / 1000" }' style="font-family: monospace;" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import * as XLSX from 'xlsx';
import { ref, onMounted, reactive } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { IconPlus, IconUpload, IconDownload } from '@arco-design/web-vue/es/icon';
import { DEVICE_TYPES } from '@/constants/device';
import { getCleaningTemplates, createCleaningTemplate, updateCleaningTemplate, deleteCleaningTemplate, type CleaningTemplate } from '@/api/cleaningTemplate';
import dayjs from 'dayjs';

const loading = ref(false);
const tableData = ref<CleaningTemplate[]>([]);
const dialogVisible = ref(false);
const formRef = ref();

const form = reactive({
  id: '',
  name: '',
  equipmentType: '',
  description: '',
  formulaStr: '{}'
});

const validateJson = (value: any, cb: any) => {
  try {
    JSON.parse(value);
    cb();
  } catch (e) {
    cb('请输入有效的 JSON 格式');
  }
};

const fetchData = async () => {
  loading.value = true;
  try {
    const { data } = await getCleaningTemplates();
    tableData.value = data;
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const formatTime = (ts: number | undefined) => {
    if (!ts) return '-';
    // If timestamp is in seconds (10 digits), convert to ms
    if (ts.toString().length === 10) {
        return dayjs.unix(ts).format('YYYY-MM-DD HH:mm:ss');
    }
    return dayjs(ts).format('YYYY-MM-DD HH:mm:ss');
}

const handleExport = () => {
    const data = tableData.value.map(item => ({
        '模板名称': item.name,
        '设备类型': item.equipmentType,
        '描述': item.description,
        '清洗公式配置': JSON.stringify(item.formula)
    }));
    const ws = XLSX.utils.json_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
    XLSX.writeFile(wb, `清洗公式模板_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
};

const handleImport = async (option: any) => {
    const { fileItem } = option;
    const file = fileItem.file;
    const reader = new FileReader();
    reader.onload = async (e) => {
        try {
            const data = e.target?.result;
            const workbook = XLSX.read(data, { type: 'binary' });
            const sheetName = workbook.SheetNames[0];
            const sheet = workbook.Sheets[sheetName];
            const json: any[] = XLSX.utils.sheet_to_json(sheet);
            
            let successCount = 0;
            let failCount = 0;

            loading.value = true;
            for (const item of json) {
                try {
                     const name = item['模板名称'] || item['name'] || item['Name'];
                     const type = item['设备类型'] || item['equipmentType'] || item['EquipmentType'];
                     const desc = item['描述'] || item['description'] || item['Description'];
                     const formulaRaw = item['清洗公式配置'] || item['formula'] || item['Formula'];

                     if (!name || !type) {
                         failCount++;
                         continue;
                     }

                     let formulaObj = {};
                     if (typeof formulaRaw === 'string') {
                         try {
                             formulaObj = JSON.parse(formulaRaw);
                         } catch (e) {
                             console.warn('Invalid JSON in formula', formulaRaw);
                             formulaObj = {}; 
                         }
                     } else if (typeof formulaRaw === 'object') {
                         formulaObj = formulaRaw;
                     }

                     const payload: CleaningTemplate = {
                        name: name,
                        equipmentType: type,
                        description: desc || '',
                        formula: formulaObj
                    };
                    
                    await createCleaningTemplate(payload);
                    successCount++;
                } catch (err) {
                    console.error("Import row error", err);
                    failCount++;
                }
            }
            Message.success(`导入完成: 成功 ${successCount} 条` + (failCount > 0 ? `, 失败 ${failCount} 条` : ''));
            fetchData();
        } catch (error) {
            console.error(error);
            Message.error('文件解析失败');
        } finally {
            loading.value = false;
        }
    };
    reader.readAsBinaryString(file);
};

const openDialog = (record?: CleaningTemplate) => {
  if (record) {
    form.id = record.id || '';
    form.name = record.name;
    form.equipmentType = record.equipmentType;
    form.description = record.description || '';
    form.formulaStr = JSON.stringify(record.formula, null, 2);
  } else {
    form.id = '';
    form.name = '';
    form.equipmentType = '';
    form.description = '';
    form.formulaStr = '{\n  "power": "x * 1"\n}';
  }
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  const errors = await formRef.value.validate();
  if (errors) return;

  try {
    const payload: CleaningTemplate = {
      name: form.name,
      equipmentType: form.equipmentType,
      description: form.description,
      formula: JSON.parse(form.formulaStr)
    };

    if (form.id) {
      await updateCleaningTemplate(form.id, payload);
      Message.success('更新成功');
    } else {
      await createCleaningTemplate(payload);
      Message.success('创建成功');
    }
    dialogVisible.value = false;
    fetchData();
  } catch (error) {
    console.error(error);
    Message.error('操作失败');
  }
};

const handleDelete = (record: CleaningTemplate) => {
  Modal.warning({
    title: '确认删除',
    content: `确定要删除模板 "${record.name}" 吗？`,
    onOk: async () => {
      try {
        if (record.id) {
            await deleteCleaningTemplate(record.id);
            Message.success('删除成功');
            fetchData();
        }
      } catch (error) {
        console.error(error);
        Message.error('删除失败');
      }
    }
  });
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.page-container {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.code-text {
  font-family: monospace;
  background-color: #f7f8fa;
  padding: 2px 4px;
  border-radius: 4px;
}
</style>

