<template>
  <div class="page-container">
    <div class="header">
      <a-typography-title :heading="4" style="margin: 0">数据源配置 (Data Source)</a-typography-title>
      <a-space>
        <a-button @click="handleExport">
          <template #icon><icon-export /></template>
          Excel 导出
        </a-button>
        <a-button @click="openExcelImportDialog">
          <template #icon><icon-import /></template>
          Excel 导入
        </a-button>
        <a-button type="primary" @click="openDialog()" v-hasPermi="['resource:datasource:add']">
          <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="180" />
          <a-table-column title="驱动类型" data-index="DriverType" :width="150">
            <template #cell="{ record }">
              <a-tag>{{ record.DriverType }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="配置信息" data-index="Config">
            <template #cell="{ record }">
              <a-typography-text code class="code-text">{{ JSON.stringify(record.Config) }}</a-typography-text>
            </template>
          </a-table-column>
          <a-table-column title="状态" data-index="Status" :width="100">
            <template #cell="{ record }">
              <a-tag :color="record.Status === 'ONLINE' ? 'green' : 'gray'">
                {{ record.Status || 'UNKNOWN' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="250">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="openImportDialog(record)" v-if="record.DriverType === 'HOME_ASSISTANT'" v-hasPermi="['resource:datasource:edit']">导入设备</a-button>
                <a-button type="text" size="small" @click="handleSync(record)" v-else v-hasPermi="['resource:datasource:edit']">立即同步</a-button>
                
                <a-tooltip content="已关联设备，不可编辑" v-if="record.DeviceCount > 0">
                   <a-button type="text" size="small" disabled>编辑</a-button>
                </a-tooltip>
                <a-button v-else type="text" size="small" @click="openDialog(record)" v-hasPermi="['resource:datasource:edit']">编辑</a-button>
                
                <a-tooltip content="已关联设备，不可删除" v-if="record.DeviceCount > 0">
                   <a-button type="text" status="danger" size="small" disabled>删除</a-button>
                </a-tooltip>
                <a-button v-else type="text" status="danger" size="small" @click="handleDelete(record)" v-hasPermi="['resource:datasource:remove']">删除</a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- Excel Import Dialog -->
    <a-modal v-model:visible="excelImportVisible" title="批量导入接入源" width="700px" @ok="handleExcelImport" :ok-loading="importing" ok-text="开始导入">
      <a-steps :current="importStep" style="margin-bottom: 20px">
        <a-step description="上传Excel文件">上传文件</a-step>
        <a-step description="配置列映射">字段映射</a-step>
      </a-steps>

      <!-- Step 1: Upload -->
      <div v-if="importStep === 1" style="text-align: center; padding: 40px 0;">
        <a-upload
          draggable
          :custom-request="customUploadPreview"
          :show-file-list="false"
        >
          <template #upload-button>
            <div style="background-color: var(--color-fill-2); padding: 40px; border-radius: 4px; border: 1px dashed var(--color-border-3); cursor: pointer;">
              <div><icon-import style="font-size: 32px; color: var(--color-text-3)" /></div>
              <div style="margin-top: 10px; font-weight: 500;">点击或拖拽 Excel 文件到此处</div>
              <div style="margin-top: 5px; color: var(--color-text-3); font-size: 12px;">支持 .xlsx 格式</div>
            </div>
          </template>
        </a-upload>
      </div>

      <!-- Step 2: Mapping -->
      <div v-if="importStep === 2">
        <a-form :model="importConfig" layout="vertical">
          <!-- Raw Preview & Header Selection -->
          <div style="margin-bottom: 20px; border: 1px solid var(--color-border-2); border-radius: 4px; padding: 10px;">
             <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                <span style="font-weight: 500;">数据预览 (前10行)</span>
                <div style="display: flex; align-items: center; gap: 10px;">
                    <span>数据起始行:</span>
                    <a-input-number v-model="headerRowIndex" :min="1" :max="10" size="small" style="width: 80px" />
                </div>
             </div>
             
             <div style="overflow-x: auto;">
                <table style="width: 100%; border-collapse: collapse; font-size: 12px;">
                    <tr>
                         <th style="border: 1px solid var(--color-border-2); padding: 4px 8px; background: var(--color-fill-2);">#</th>
                         <th v-for="h in excelHeaders" :key="h" style="border: 1px solid var(--color-border-2); padding: 4px 8px; background: var(--color-fill-2);">
                             {{ h }}
                         </th>
                    </tr>
                    <tr v-for="(row, rIdx) in excelRawRows" :key="rIdx" 
                        :style="{ backgroundColor: (rIdx + 1) < headerRowIndex ? 'var(--color-fill-2)' : 'transparent', opacity: (rIdx + 1) < headerRowIndex ? 0.5 : 1 }">
                        <td style="border: 1px solid var(--color-border-2); padding: 4px 8px; color: var(--color-text-3); width: 40px; text-align: center;">
                            {{ rIdx + 1 }}
                        </td>
                        <td v-for="(cell, cIdx) in row" :key="cIdx" style="border: 1px solid var(--color-border-2); padding: 4px 8px; white-space: nowrap;">
                            {{ cell }}
                        </td>
                    </tr>
                </table>
             </div>
             <div style="margin-top: 5px; color: var(--color-text-3); font-size: 12px;">
                * 请选择对应列名（如 A, B, C...）
             </div>
          </div>
        
          <a-form-item label="驱动类型" required>
            <a-select v-model="importConfig.driver_type" placeholder="选择驱动类型">
              <a-option value="HOME_ASSISTANT">Home Assistant</a-option>
            </a-select>
          </a-form-item>

          <a-divider orientation="left">字段映射 (Excel列 -> 系统字段)</a-divider>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="源名称 (Name)" required>
                <a-select v-model="importConfig.mapping.name" placeholder="选择对应列">
                  <a-option v-for="h in excelHeaders" :key="h" :value="h">{{ h }}</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>

          <!-- Dynamic Config Fields based on Driver Type -->
          <template v-if="importConfig.driver_type === 'HOME_ASSISTANT'">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="Base URL" required>
                   <a-select v-model="importConfig.mapping.config.url" placeholder="选择对应列">
                      <a-option v-for="h in excelHeaders" :key="h" :value="h">{{ h }}</a-option>
                   </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="Access Token" required>
                   <a-select v-model="importConfig.mapping.config.token" placeholder="选择对应列">
                      <a-option v-for="h in excelHeaders" :key="h" :value="h">{{ h }}</a-option>
                   </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </template>

          <div style="margin-top: 10px; background: var(--color-fill-1); padding: 10px; border-radius: 4px;">
            <div style="margin-bottom: 5px; font-weight: 500;">导入数据预览 (基于当前映射):</div>
             <!-- Simple mock preview based on raw data logic -->
             <div style="font-size: 12px; color: var(--color-text-3);">
                将在点击导入时处理全部数据。
             </div>
          </div>
        </a-form>
      </div>
    </a-modal>

    <!-- Import Dialog -->
    <a-modal v-model:visible="importVisible" title="从 Home Assistant 导入设备" width="900px" :footer="false">
      <a-alert style="margin-bottom: 20px">将多个 Home Assistant 实体组合为一个 EMS 设备</a-alert>
      
      <a-form :model="compositeForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="设备名称" required>
              <a-input v-model="compositeForm.Name" placeholder="例如：客厅空调" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
             <a-form-item label="设备类型" required>
                <a-select v-model="compositeForm.DeviceType" @change="handleCompositeTypeChange">
                  <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 label="清洗公式模板">
             <a-select v-model="compositeForm.CleaningTemplateId" placeholder="选择清洗公式模板（可选）" @change="handleTemplateChange" allow-clear>
                <a-option v-for="tpl in cleaningTemplates" :key="tpl.id" :value="tpl.id">
                    {{ tpl.name }}
                </a-option>
             </a-select>
             <template #help>选择模板后，将自动填充清洗公式</template>
        </a-form-item>

        <a-divider orientation="left">实体关联</a-divider>

        <a-form-item label="设备主实体 (Main Entity)">
             <a-select v-model="compositeForm.BaseEntity" allow-search placeholder="请选择 HA 设备 (先选设备可自动筛选关联实体)" @change="handleDeviceChange" allow-clear>
                <a-option v-for="dev in haDevices" :key="dev.id" :value="dev.id">
                    {{ dev.name }}
                </a-option>
             </a-select>
             <template #help>选择设备后，下方属性列表将自动筛选出该设备下的所有实体</template>
        </a-form-item>
        
        <template v-if="compositeForm.DeviceType">
           <div v-for="(label, key) in currentTemplate" :key="key" style="margin-bottom: 16px; border-bottom: 1px dashed var(--color-border-2); padding-bottom: 10px;">
              <div style="margin-bottom: 8px; font-weight: 500;">{{ label }}</div>
              <a-row :gutter="8">
                <a-col :span="14">
                   <a-select v-model="compositeForm.AttributeMapping[key]" allow-search placeholder="选择关联的 HA 实体" allow-clear>
                      <a-option v-for="item in getFilteredCandidates(key)" :key="item.entity_id" :value="item.entity_id" :label="item.entity_id">
                         <div class="entity-option">
                           <div class="entity-id" :title="item.entity_id">{{ item.entity_id }}</div>
                           <div class="entity-name" :title="item.attributes?.friendly_name || item.state">{{ item.attributes?.friendly_name || item.state }}</div>
                         </div>
                      </a-option>
                   </a-select>
                </a-col>
                <a-col :span="10">
                    <a-input v-if="key !== 'switch'" v-model="compositeForm.AttributeMapping[key + '_formula']" placeholder="清洗公式 f(x)=">
                       <template #prepend>fx</template>
                    </a-input>
                    <div v-else style="line-height: 32px; color: #86909c; padding-left: 10px;">
                        无需公式 (默认: 1/0)
                    </div>
                </a-col>
              </a-row>
           </div>
        </template>
        <div v-else style="text-align: center; color: #999; padding: 20px">
          请先选择设备类型
        </div>

        <div style="margin-top: 20px; display: flex; justify-content: flex-end; gap: 10px;">
           <a-button @click="openSaveTemplateDialog" v-if="compositeForm.DeviceType">保存为模板</a-button>
           <a-button type="primary" @click="handleCompositeImport" :loading="importLoading">完成 并 继续创建下一个</a-button>
        </div>
      </a-form>
    </a-modal>

    <!-- Save Template Modal -->
    <a-modal v-model:visible="saveTemplateVisible" title="保存为清洗模板" @ok="handleSaveTemplate">
      <a-form :model="saveTemplateForm" layout="vertical">
        <a-form-item label="模板名称" required>
          <a-input v-model="saveTemplateForm.name" placeholder="请输入模板名称" />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea v-model="saveTemplateForm.description" placeholder="模板描述" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- Dialog -->
    <a-modal
      v-model:visible="dialogVisible"
      :title="isEdit ? '编辑接入源' : '新增接入源'"
      @ok="saveSource"
      @cancel="dialogVisible = false"
      width="600px"
    >
      <a-form :model="form" ref="formRef" layout="vertical">
        <a-form-item field="Name" label="名称" :rules="[{ required: true, message: '请输入名称' }]">
          <a-input v-model="form.Name" placeholder="例如：主楼HA网关" allow-clear />
        </a-form-item>
        <a-form-item field="DriverType" label="驱动类型" :rules="[{ required: true, message: '请选择类型' }]">
          <a-select v-model="form.DriverType" placeholder="请选择" @change="handleTypeChange">
            <a-option label="Home Assistant" value="HOME_ASSISTANT" />
          </a-select>
        </a-form-item>

        <!-- Dynamic Config Fields -->
        <template v-if="form.DriverType === 'HOME_ASSISTANT'">
          <a-form-item field="Config.url" label="Base URL" :rules="[{ required: true, message: '请输入 Base URL' }]">
            <a-input v-model="form.Config.url" placeholder="http://192.168.1.x:8123" allow-clear />
          </a-form-item>
          <a-form-item field="Config.token" label="Access Token" :rules="[{ required: true, message: '请输入 Token' }]">
            <a-input-password v-model="form.Config.token" allow-clear />
          </a-form-item>
        </template>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="testConnection" :loading="testing" :disabled="saving">连接测试</a-button>
          <a-button @click="dialogVisible = false">取消</a-button>
          <a-button type="primary" @click="saveSource" :loading="saving" :disabled="testing">保存</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { IconPlus, IconImport, IconExport } from '@arco-design/web-vue/es/icon';
import { DEVICE_TYPES } from '@/constants/device';
import { getSources, createSource, updateSource, deleteSource, testSourceConnection, syncSource, getSourceDevices, getSourceDeviceEntities, createDevice } from '@/api/resource';
import axios from 'axios';
import type { IntegrationSource, HAEntity } from '@/api/resource';
import { getCleaningTemplates, createCleaningTemplate, type CleaningTemplate } from '@/api/cleaningTemplate';
import * as XLSX from 'xlsx';

// --- State ---
const loading = ref(false);
const tableData = ref<IntegrationSource[]>([]);
const dialogVisible = ref(false);
const isEdit = ref(false);
const testing = ref(false);
const saving = ref(false);

// Import State
const importVisible = ref(false);
const excelImportVisible = ref(false);
const importStep = ref(1);
const headerRowIndex = ref(1);
const excelRawRows = ref<string[][]>([]);
const importedFile = ref<File | null>(null);
const importing = ref(false);

// Helper to generate excel column letters (A, B, ... Z, AA, AB)
const getColumnLabel = (index: number) => {
    let label = '';
    let i = index;
    while (i >= 0) {
        label = String.fromCharCode((i % 26) + 65) + label;
        i = Math.floor(i / 26) - 1;
    }
    return label;
};

const excelHeaders = computed(() => {
    if (excelRawRows.value.length === 0) return [];
    // Generate A, B, C... based on max columns in first 10 rows
    const maxCols = Math.max(...excelRawRows.value.map(row => row.length));
    const headers = [];
    for (let i = 0; i < maxCols; i++) {
        headers.push(getColumnLabel(i));
    }
    return headers;
});

const importConfig = reactive({
  driver_type: 'HOME_ASSISTANT',
  mapping: {
    name: '',
    config: {} as Record<string, string>
  }
});

const authHeaders = computed(() => {
  return {
    Authorization: `Bearer ${localStorage.getItem('token')}`
  };
});

const candidateData = ref<HAEntity[]>([]);
const candidateLoading = ref(false);
const selectedCandidateKeys = ref<string[]>([]);
const importLoading = ref(false);
const currentImportSourceId = ref('');
const cleaningTemplates = ref<CleaningTemplate[]>([]);

// Composite Import State
const compositeForm = reactive({
  Name: '',
  DeviceType: '',
  BaseEntity: '',
  CleaningTemplateId: '',
  AttributeMapping: {} as Record<string, string>
});

const currentTemplate = ref<Record<string, string>>({});

// Save Template State
const saveTemplateVisible = ref(false);
const saveTemplateForm = reactive({
  name: '',
  description: ''
});

// Device list cache
const haDevices = ref<{id: string, name: string}[]>([]);

// Filtered candidates cache or computed logic
const filterKeyword = ref('');

const templates: Record<string, Record<string, string>> = {
  'ELEC': {
    'switch': '开关 (Switch)',
    'power': '电功率 (Power, W)',
    'voltage': '电压 (Voltage, V)',
    'current': '电流 (Current, A)',
    'energy': '耗电量 (Energy, kWh)',
    'temperature': '温度 (Temperature, °C)'
  },
  'WATER': {
    'flow_rate': '瞬时流量 (m³/h)',
    'consumption': '累计用水量 (m³)',
    'pressure': '水压 (Bar)'
  },
  'GAS': {
    'flow_rate': '瞬时流量 (m³/h)',
    'consumption': '累计用气量 (m³)',
    'pressure': '气压 (kPa)'
  }
};

const formRef = ref();
const form = reactive<Partial<IntegrationSource>>({
  Name: '',
  DriverType: 'HOME_ASSISTANT',
  Config: {},
  Status: 'OFFLINE'
});

// --- Lifecycle ---
onMounted(() => {
  loadData();
});

// --- Methods ---
const loadData = async () => {
  loading.value = true;
  try {
    const res = await getSources();
    tableData.value = (res as any).data || res; 
  } catch (error) {
    Message.error('加载失败');
  } finally {
    loading.value = false;
  }
};

const handleExport = () => {
    if (tableData.value.length === 0) {
        Message.warning('暂无数据可导出');
        return;
    }

    try {
        const exportData = tableData.value.map(d => ({
            '名称': d.Name,
            '驱动类型': d.DriverType,
            '配置信息': JSON.stringify(d.Config),
            '状态': d.Status === 'ONLINE' ? '在线' : '离线',
            '设备数量': d.DeviceCount || 0
        }));

        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.json_to_sheet(exportData);

        ws['!cols'] = [
            { wch: 20 }, // 名称
            { wch: 15 }, // 驱动类型
            { wch: 50 }, // 配置信息
            { wch: 8 },  // 状态
            { wch: 10 }  // 设备数量
        ];

        XLSX.utils.book_append_sheet(wb, ws, "数据源列表");

        const fileName = `数据源列表_${new Date().toISOString().slice(0, 10)}.xlsx`;
        XLSX.writeFile(wb, fileName);

        Message.success('导出成功');
    } catch (error) {
        console.error(error);
        Message.error('导出失败');
    }
};

const openDialog = (row?: IntegrationSource) => {
  dialogVisible.value = true;
  if (row) {
    isEdit.value = true;
    Object.assign(form, JSON.parse(JSON.stringify(row))); // Deep copy
    // Ensure config is object
    if (typeof form.Config === 'string') {
        try { form.Config = JSON.parse(form.Config); } catch (e) { form.Config = {}; }
    }
  } else {
    isEdit.value = false;
    form.ID = undefined;
    form.Name = '';
    form.DriverType = 'HOME_ASSISTANT';
    form.Config = { url: '', token: '' }; // Default for HA
    form.Status = 'OFFLINE';
  }
};

const handleTypeChange = (val: string | number | Record<string, any>) => {
  // Arco select passes value directly.
  const typeStr = val as string;
  // Reset config template based on type
  if (typeStr === 'HOME_ASSISTANT') {
    form.Config = { url: '', token: '' };
  }
};

const testConnection = async () => {
  testing.value = true;
  try {
    await testSourceConnection(form);
    Message.success('连接成功');
    form.Status = 'ONLINE';
  } catch (error) {
    Message.error('连接失败');
    form.Status = 'OFFLINE';
  } finally {
    testing.value = false;
  }
};

const saveSource = async () => {
  if (!formRef.value) return;
  const errors = await formRef.value.validate();
  if (!errors) {
      saving.value = true;
      try {
        if (isEdit.value && form.ID) {
          await updateSource(form.ID, form);
        } else {
          await createSource(form);
        }
        Message.success('保存成功');
        dialogVisible.value = false;
        loadData();
      } catch (error: any) {
        Message.error(error.response?.data?.error || '保存失败');
      } finally {
        saving.value = false;
      }
  }
};

const handleSync = async (row: IntegrationSource) => {
  try {
    await syncSource(row.ID);
    Message.success('同步指令已下发');
  } catch (error) {
    Message.error('同步失败');
  }
};

const handleDelete = (row: IntegrationSource) => {
  Modal.confirm({
    title: '警告',
    content: '确定删除该数据源?',
    onOk: async () => {
      try {
        await deleteSource(row.ID);
        Message.success('已删除');
        loadData();
      } catch (error: any) {
        Message.error(error.response?.data?.error || '删除失败');
      }
    }
  });
};

// --- Excel Import Methods ---

const openExcelImportDialog = () => {
  excelImportVisible.value = true;
  importStep.value = 1;
  headerRowIndex.value = 1;
  excelRawRows.value = [];
  importedFile.value = null;
  importConfig.driver_type = 'HOME_ASSISTANT';
  importConfig.mapping = { name: '', config: {} };
};

const customUploadPreview = async (option: any) => {
    const { fileItem, onSuccess, onError } = option;
    const formData = new FormData();
    formData.append('file', fileItem.file);
    
    try {
        const res = await axios.post('/api/v1/sources/import/preview', formData, {
            headers: { 
                'Content-Type': 'multipart/form-data',
                ...authHeaders.value 
            }
        });
        
        excelRawRows.value = res.data.rows;
        importedFile.value = fileItem.file; 
        importStep.value = 2;
        onSuccess(res.data);
    } catch (e) {
        onError(e);
    }
};

const handleExcelImport = async () => {
    if (importStep.value !== 2) return;
    if (!importConfig.mapping.name) {
        Message.warning('请选择名称对应的列');
        return;
    }
    
    importing.value = true;
    const formData = new FormData();
    if (importedFile.value) {
        formData.append('file', importedFile.value);
    }
    formData.append('config', JSON.stringify(importConfig));
    formData.append('header_row', headerRowIndex.value.toString());
    
    try {
        await axios.post('/api/v1/sources/import/execute', formData, {
            headers: { 
                'Content-Type': 'multipart/form-data',
                ...authHeaders.value 
            }
        });
        Message.success('导入成功');
        excelImportVisible.value = false;
        importStep.value = 1; // Reset step
        loadData();
    } catch (error: any) {
        Message.error(error.response?.data?.error || '导入失败');
    } finally {
        importing.value = false;
    }
};

// --- Import Methods ---

const openImportDialog = async (row: IntegrationSource) => {
  currentImportSourceId.value = row.ID;
  importVisible.value = true;
  candidateLoading.value = true;
  candidateData.value = [];
  selectedCandidateKeys.value = [];
  haDevices.value = [];
  
  // Load templates
  try {
      const res = await getCleaningTemplates();
      cleaningTemplates.value = (res as any).data || res;
  } catch (e) {
      console.error(e);
  }

  try {
    const res = await getSourceDevices(row.ID);
    const devices = (res as any).data || res;
    
    haDevices.value = devices.map((d: any) => ({
        id: d.id,
        name: `${d.name} (${d.id})`
    })).sort((a: any, b: any) => a.name.localeCompare(b.name));

  } catch (error: any) {
    Message.error(error.response?.data?.error || '获取设备列表失败');
  } finally {
    candidateLoading.value = false;
  }
};

const handleTemplateChange = (val: any) => {
    const tpl = cleaningTemplates.value.find(t => t.id === val);
    if (tpl && tpl.formula) {
        // Apply formula to current mapping
        Object.assign(compositeForm.AttributeMapping, tpl.formula);
        Message.success(`已应用模板：${tpl.name}`);
    }
};

const openSaveTemplateDialog = () => {
  saveTemplateForm.name = '';
  saveTemplateForm.description = '';
  saveTemplateVisible.value = true;
};

const handleSaveTemplate = async () => {
  if (!saveTemplateForm.name) {
    Message.warning('请输入模板名称');
    return;
  }

  // Extract formula from current mapping
  const formula: Record<string, string> = {};
  
  // Iterate over all attributes defined for the current device type
  for (const key in currentTemplate.value) {
    if (key === 'switch') continue; // Skip switch

    const formulaKey = key + '_formula';
    const val = compositeForm.AttributeMapping[formulaKey];
    // Use user provided value, or default to 'x'
    formula[formulaKey] = val ? val : 'x';
  }

  if (Object.keys(formula).length === 0) {
    Message.warning('当前设备类型没有可配置的公式项');
    return;
  }

  try {
    const res = await createCleaningTemplate({
      name: saveTemplateForm.name,
      equipmentType: compositeForm.DeviceType,
      description: saveTemplateForm.description,
      formula: formula
    });
    
    Message.success('模板保存成功');
    saveTemplateVisible.value = false;
    
    // Refresh templates list
    const resList = await getCleaningTemplates();
    cleaningTemplates.value = (resList as any).data || resList;

    // Select the new template
    const newTemplate = (res as any).data?.data || (res as any).data; // adjust based on actual response structure
    if (newTemplate && newTemplate.id) {
       compositeForm.CleaningTemplateId = newTemplate.id;
    }

  } catch (error) {
    console.error(error);
    Message.error('模板保存失败');
  }
};

const handleCompositeTypeChange = (val: any) => {
  const typeStr = val as string;
  currentTemplate.value = templates[typeStr] || {};
  compositeForm.AttributeMapping = {};
};

const handleDeviceChange = async (val: any) => {
  if (!val) {
    filterKeyword.value = '';
    candidateData.value = [];
    compositeForm.Name = '';
    return;
  }
  
  // val is device_id
  const device = haDevices.value.find((d: any) => d.id === val);
  if (device) {
      // Set name from device name (remove the id suffix)
      const name = device.name.replace(` (${val})`, '');
      if (!compositeForm.Name) {
          compositeForm.Name = name;
      }
      
      // Load entities for this device
      candidateLoading.value = true;
      try {
        const res = await getSourceDeviceEntities(currentImportSourceId.value, val);
        candidateData.value = (res as any).data || res;
      } catch (error: any) {
        Message.error(error.response?.data?.error || '加载设备实体失败');
        candidateData.value = [];
      } finally {
        candidateLoading.value = false;
      }
  }
};

const getFilteredCandidates = (attrKey?: string) => {
  let data = [...candidateData.value];
  if (!attrKey) return data;

  const keywords: Record<string, string[]> = {
    'switch': ['switch', 'relay', 'plug', 'outlet', '开关'],
    'power': ['power', '功率'],
    'voltage': ['voltage', '电压'],
    'current': ['current', '电流'],
    'energy': ['energy', '耗电', '电量'],
    'temperature': ['temperature', 'temp', '温度'],
    'flow_rate': ['flow', '流量'],
    'consumption': ['consumption', '用量'],
    'pressure': ['pressure', '压']
  };

  const targetKeywords = keywords[attrKey] || [attrKey];

  // Sort: matching keywords first
  data.sort((a, b) => {
      const aStr = (a.entity_id + (a.attributes?.friendly_name || '')).toLowerCase();
      const bStr = (b.entity_id + (b.attributes?.friendly_name || '')).toLowerCase();
      
      const aScore = targetKeywords.some(k => aStr.includes(k.toLowerCase())) ? 1 : 0;
      const bScore = targetKeywords.some(k => bStr.includes(k.toLowerCase())) ? 1 : 0;

      if (aScore !== bScore) {
          return bScore - aScore; // Match first
      }
      return a.entity_id.localeCompare(b.entity_id); // Then alphabetical
  });

  return data;
};

const handleCompositeImport = async () => {
  if (!compositeForm.Name || !compositeForm.DeviceType) {
    Message.warning('请填写设备名称并选择类型');
    return;
  }
  
  // Validation for ELECTRIC type
  if (compositeForm.DeviceType === 'ELEC') {
    const requiredMetrics = ['voltage', 'current', 'power', 'energy'];
    for (const metric of requiredMetrics) {
      const hasEntity = !!compositeForm.AttributeMapping[metric];
      const hasFormula = !!compositeForm.AttributeMapping[metric + '_formula'];
      
      if (!hasEntity && !hasFormula) {
        Message.warning(`电力设备属性 [${metric}] 未绑定实体时，必须填写公式`);
        return;
      }
    }
  }

  // Ensure full structure for ELECTRIC devices even if empty (though validation above ensures logic)
  if (compositeForm.DeviceType === 'ELEC') {
      ['switch', 'voltage', 'current', 'power', 'energy'].forEach(metric => {
          if (compositeForm.AttributeMapping[metric] === undefined) {
              compositeForm.AttributeMapping[metric] = '';
          }
          if (metric !== 'switch' && compositeForm.AttributeMapping[metric + '_formula'] === undefined) {
              compositeForm.AttributeMapping[metric + '_formula'] = '';
          }
      });
  }
  
  importLoading.value = true;
  try {
      // Determine ExternalID
      let externalID = '';
      
      // Ensure metrics exist if formula exists
      const finalMapping = { ...compositeForm.AttributeMapping };
      Object.keys(finalMapping).forEach(key => {
          if (key.endsWith('_formula')) {
              const metric = key.replace('_formula', '');
              if (finalMapping[metric] === undefined) {
                  finalMapping[metric] = '';
              }
          }
      });

      if (compositeForm.BaseEntity) {
          externalID = compositeForm.BaseEntity;
      } else {
          // Filter out formulas to find actual entity IDs
          const mappedValues = Object.entries(finalMapping)
            .filter(([k, v]) => !k.endsWith('_formula') && !!v)
            .map(([_, v]) => v);
            
          if (mappedValues.length > 0) {
              externalID = mappedValues[0];
          } else {
              externalID = `virtual-${Date.now()}`;
          }
      }

      await createDevice({
        SourceID: currentImportSourceId.value,
        ExternalID: externalID, 
        Name: compositeForm.Name,
        DeviceType: 'ELECTRIC', // Map ELEC to ELECTRIC standard
        Status: 'NORMAL',
        AttributeMapping: finalMapping
      });
      Message.success('组合设备创建成功');
      // importVisible.value = false; // Keep dialog open for continuous creation
      
      // Reset form but keep Template/Type/Formulas
      compositeForm.Name = '';
      compositeForm.BaseEntity = '';
      candidateData.value = [];
      
      // Only clear entity mappings, keep formulas
      Object.keys(compositeForm.AttributeMapping).forEach(key => {
          if (!key.endsWith('_formula')) {
              compositeForm.AttributeMapping[key] = '';
          }
      });
      
      filterKeyword.value = '';
  } catch (error: any) {
      Message.error(error.response?.data?.error || '创建失败');
  } finally {
      importLoading.value = false;
  }
};
</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;
  font-size: 0.85em;
  color: var(--color-text-3);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: block;
  max-width: 300px;
}

.entity-option {
  display: flex;
  flex-direction: column;
  padding: 2px 0;
}
.entity-id {
  font-weight: 500;
  font-size: 13px;
  line-height: 1.2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.entity-name {
  font-size: 12px;
  color: var(--color-text-3);
  margin-top: 2px;
  line-height: 1.2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
