<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
                <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="单位" prop="unit">
              <el-input v-model="queryParams.unit" placeholder="请输入单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="metricList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" prop="id" min-width="160" />
        <el-table-column label="类型" align="center" width="120">
          <template #default="scope">
            <dict-tag :options="device_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="指标名称" prop="metricName" min-width="140" />
        <el-table-column label="采集字段" prop="collectionField" min-width="190" />
        <el-table-column label="单位" prop="unit" align="center" width="120" />
        <el-table-column label="聚合规则" prop="aggregationRule" align="center" width="120">
          <template #default="scope">
            {{ getAggregationRuleLabel(scope.row.aggregationRule) }}
          </template>
        </el-table-column>
        <el-table-column label="预留3" prop="reserve3" min-width="120" />
        <el-table-column label="预留4" prop="reserve4" min-width="120" />
        <el-table-column label="预留5" prop="reserve5" min-width="120" />
        <el-table-column fixed="right" label="操作" align="center" width="120">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="560px">
      <el-form ref="metricFormRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="指标名称" prop="metricName">
          <el-input v-model="form.metricName" placeholder="请输入指标名称" />
        </el-form-item>
        <el-form-item label="采集字段" prop="collectionField">
          <el-select v-model="form.collectionField" placeholder="请选择采集字段" filterable clearable>
            <el-option v-for="item in collectionFieldOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="聚合规则" prop="aggregationRule">
          <el-select v-model="form.aggregationRule" placeholder="请选择聚合规则" clearable>
            <el-option v-for="item in aggregationRuleOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="预留3" prop="reserve3">
          <el-input v-model="form.reserve3" placeholder="请输入预留字段3" />
        </el-form-item>
        <el-form-item label="预留4" prop="reserve4">
          <el-input v-model="form.reserve4" placeholder="请输入预留字段4" />
        </el-form-item>
        <el-form-item label="预留5" prop="reserve5">
          <el-input v-model="form.reserve5" placeholder="请输入预留字段5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EnergyMetric" lang="ts">
import { addEnergyMetric, delEnergyMetric, getEnergyMetric, listEnergyMetric, updateEnergyMetric } from '@/api/ems/energyMetric';
import { EnergyMetricForm, EnergyMetricQuery, EnergyMetricVO } from '@/api/ems/energyMetric/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { device_type } = toRefs<any>(proxy?.useDict('device_type'));

const metricList = ref<EnergyMetricVO[]>([]);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const aggregationRuleOptions = [
  { label: '平均值', value: 'avg' },
  { label: '相加', value: 'sum' },
  { label: '相减', value: 'subtract' },
  { label: '最大值', value: 'max' },
  { label: '最小值', value: 'min' },
  { label: '最新值', value: 'latest' },
  { label: '正差值', value: 'positive_diff' },
  { label: '负差值', value: 'negative_diff' }
];
const collectionFieldOptions = [
  { label: '正向有功总电能', value: 'forward_active_total_energy' },
  { label: '正向无功总电能', value: 'forward_reactive_total_energy' },
  { label: '总有功功率', value: 'total_active_power' },
  { label: '总无功功率', value: 'total_reactive_power' },
  { label: 'A相电压', value: 'phase_a_voltage' },
  { label: 'B相电压', value: 'phase_b_voltage' },
  { label: 'C相电压', value: 'phase_c_voltage' },
  { label: 'A相电流', value: 'phase_a_current' },
  { label: 'B相电流', value: 'phase_b_current' },
  { label: 'C相电流', value: 'phase_c_current' },
  { label: '总功率因数', value: 'total_power_factor' },
  { label: '水表读数', value: 'water_meter_reading' },
  { label: '温度读数', value: 'temperature_reading' }
];

const queryFormRef = ref<ElFormInstance>();
const metricFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: EnergyMetricForm = {
  id: undefined,
  type: undefined,
  unit: '',
  metricName: '',
  collectionField: '',
  aggregationRule: '',
  reserve3: '',
  reserve4: '',
  reserve5: ''
};

const data = reactive<PageData<EnergyMetricForm, EnergyMetricQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: undefined,
    unit: ''
  },
  rules: {
    type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
    metricName: [{ required: true, message: '指标名称不能为空', trigger: 'blur' }],
    collectionField: [{ required: true, message: '采集字段不能为空', trigger: 'change' }],
    aggregationRule: [{ required: true, message: '聚合规则不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const getAggregationRuleLabel = (value?: string) => {
  return aggregationRuleOptions.find((item) => item.value === value)?.label || value || '';
};

const getList = async () => {
  loading.value = true;
  try {
    const res = await listEnergyMetric(queryParams.value);
    metricList.value = res.rows || [];
    total.value = res.total || 0;
  } finally {
    loading.value = false;
  }
};

const reset = () => {
  form.value = { ...initFormData };
  metricFormRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: EnergyMetricVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增能源指标';
};

const handleUpdate = async (row?: EnergyMetricVO) => {
  reset();
  const id = row?.id || ids.value[0];
  const res = await getEnergyMetric(id);
  form.value = { ...res.data };
  dialog.visible = true;
  dialog.title = '修改能源指标';
};

const submitForm = () => {
  metricFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    }
    if (form.value.id) {
      await updateEnergyMetric(form.value);
    } else {
      await addEnergyMetric(form.value);
    }
    proxy?.$modal.msgSuccess('操作成功');
    dialog.visible = false;
    await getList();
  });
};

const handleDelete = async (row?: EnergyMetricVO) => {
  const deleteIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除能源指标编号为"' + deleteIds + '"的数据项？');
  await delEnergyMetric(deleteIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const cancel = () => {
  dialog.visible = false;
  reset();
};

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