<template>
  <div class="page-container">
    <a-tabs type="card">
      
      <!-- Tab 1: Electricity Price -->
      <a-tab-pane key="price" title="电价配置 (TOU)">
        <div class="config-section">
          <div class="header">
             <h3>分时电价策略</h3>
             <a-button type="primary" size="small" @click="savePriceConfig">保存配置</a-button>
          </div>
          <a-alert type="info" :show-icon="true" style="margin-bottom: 20px">
            请设置各时段的单价 (元/kWh) 和时间范围
          </a-alert>

          <a-form :model="priceConfig" layout="vertical">
             <a-divider orientation="left">时段单价</a-divider>
             <a-row :gutter="20">
               <a-col :span="6">
                 <a-form-item field="price.peak" label="尖峰 (Peak)">
                   <a-input-number v-model="priceConfig.price.peak" :precision="4" :step="0.01" />
                 </a-form-item>
               </a-col>
               <a-col :span="6">
                 <a-form-item field="price.high" label="高峰 (High)">
                   <a-input-number v-model="priceConfig.price.high" :precision="4" :step="0.01" />
                 </a-form-item>
               </a-col>
               <a-col :span="6">
                 <a-form-item field="price.flat" label="平段 (Flat)">
                   <a-input-number v-model="priceConfig.price.flat" :precision="4" :step="0.01" />
                 </a-form-item>
               </a-col>
               <a-col :span="6">
                 <a-form-item field="price.valley" label="低谷 (Valley)">
                   <a-input-number v-model="priceConfig.price.valley" :precision="4" :step="0.01" />
                 </a-form-item>
               </a-col>
             </a-row>

             <a-divider orientation="left">时段定义 (24小时制)</a-divider>
             <div v-for="(range, index) in priceConfig.ranges" :key="index" class="range-item">
                <a-select v-model="range.start" placeholder="开始时间" style="width: 120px">
                  <a-option v-for="t in timeOptions" :key="t" :value="t">{{ t }}</a-option>
                </a-select>
                <span class="sep">至</span>
                <a-select v-model="range.end" placeholder="结束时间" style="width: 120px">
                   <a-option v-for="t in timeOptions" :key="t" :value="t">{{ t }}</a-option>
                </a-select>
                
                <a-select v-model="range.type" placeholder="类型" style="width: 120px; margin-left: 10px">
                  <a-option label="尖峰" value="peak" />
                  <a-option label="高峰" value="high" />
                  <a-option label="平段" value="flat" />
                  <a-option label="低谷" value="valley" />
                </a-select>
                <a-button type="primary" status="danger" shape="circle" size="small" style="margin-left: 10px" @click="removeRange(index)">
                  <template #icon><icon-delete /></template>
                </a-button>
             </div>
             <a-button type="dashed" style="width: 100%; margin-top: 10px" @click="addRange">+ 添加时段</a-button>
          </a-form>
        </div>
      </a-tab-pane>

      <!-- Tab 2: System Config -->
      <a-tab-pane key="system" title="系统配置">
        <a-form :model="sysConfig" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" style="max-width: 600px; margin-top: 20px">
          <a-form-item field="appName" label="平台名称">
            <a-input v-model="sysConfig.appName" />
          </a-form-item>
          <a-form-item field="logoUrl" label="Logo URL">
            <a-input v-model="sysConfig.logoUrl" />
          </a-form-item>
          <a-form-item field="retentionDays" label="历史数据保留 (天)">
             <a-input-number v-model="sysConfig.retentionDays" />
          </a-form-item>
          <a-form-item field="language" label="默认语言">
             <a-select v-model="sysConfig.language">
               <a-option label="简体中文" value="zh-CN" />
               <a-option label="English" value="en-US" />
             </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="saveSysConfig">保存系统配置</a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>

    </a-tabs>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import { IconDelete } from '@arco-design/web-vue/es/icon';
import * as sysApi from '../../api/system';

// Generate time options 00:00 - 24:00 with step 1h
const timeOptions = Array.from({ length: 25 }, (_, i) => {
  const h = i.toString().padStart(2, '0');
  return `${h}:00`;
});

// --- Price Config ---
const priceConfig = reactive({
  price: { peak: 1.5, high: 1.2, flat: 0.8, valley: 0.4 },
  ranges: [
    { start: '00:00', end: '08:00', type: 'valley' },
    { start: '08:00', end: '12:00', type: 'high' },
    { start: '12:00', end: '14:00', type: 'flat' },
    { start: '14:00', end: '18:00', type: 'high' },
    { start: '18:00', end: '22:00', type: 'peak' },
    { start: '22:00', end: '24:00', type: 'flat' },
  ]
});

const addRange = () => {
  priceConfig.ranges.push({ start: '00:00', end: '01:00', type: 'flat' });
};
const removeRange = (idx: number) => {
  priceConfig.ranges.splice(idx, 1);
};

const savePriceConfig = async () => {
  try {
    const payload = {
      ConfigKey: 'electricity_price_tou',
      ConfigValue: JSON.stringify(priceConfig),
      ConfigType: 'JSON',
      Remark: '分时电价配置'
    };
    await sysApi.updateConfig(payload);
    Message.success('电价配置已保存');
  } catch (e) {
    Message.error('保存失败');
  }
};

// --- System Config ---
const sysConfig = reactive({
  appName: '企业能耗管理平台',
  logoUrl: '/logo.png',
  retentionDays: 365,
  language: 'zh-CN'
});

const saveSysConfig = async () => {
   try {
    const payload = {
      ConfigKey: 'system_base_config',
      ConfigValue: JSON.stringify(sysConfig),
      ConfigType: 'JSON',
      Remark: '系统基础配置'
    };
    await sysApi.updateConfig(payload);
    Message.success('系统配置已保存');
  } catch (e) {
    Message.error('保存失败');
  }
};

// --- Init ---
onMounted(async () => {
  // Load existing configs
  const res: any = await sysApi.getAllConfigs();
  if (res) {
    res.forEach((item: any) => {
      if (item.ConfigKey === 'electricity_price_tou') {
        try {
          const val = JSON.parse(item.ConfigValue);
          Object.assign(priceConfig, val);
        } catch (e) {}
      }
      if (item.ConfigKey === 'system_base_config') {
        try {
           const val = JSON.parse(item.ConfigValue);
           Object.assign(sysConfig, val);
        } catch (e) {}
      }
    });
  }
});

</script>

<style scoped>
.page-container {
  padding: 20px;
}
.config-section {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.range-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.sep {
  margin: 0 10px;
  color: #666;
}
</style>
