<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="pointCode">
              <el-input v-model="queryParams.pointCode" placeholder="请输入测控点编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="测控点名称" prop="pointName">
              <el-input v-model="queryParams.pointName" placeholder="请输入测控点名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="参数名称" prop="parameterName">
              <el-select v-model="queryParams.parameterName" placeholder="请选择参数" clearable filterable>
                <el-option v-for="item in metricOptions" :key="item.collectionField" :label="formatMetricLabel(item)" :value="item.collectionField" />
              </el-select>
            </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="pointList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="测控点编号" prop="pointCode" min-width="140" />
        <el-table-column label="测控点名称" prop="pointName" min-width="160" />
        <el-table-column label="所属计量器具" prop="measuringDeviceName" min-width="160" />
        <el-table-column label="参数名称" prop="parameterNameLabel" min-width="150" />
        <el-table-column label="标准单位" prop="standardUnit" width="100" />
        <el-table-column label="换算倍率" prop="conversionFactor" align="right" width="110" />
        <el-table-column label="数据占比(%)" prop="dataRatio" align="right" width="120" />
        <el-table-column label="原始单位" prop="originalUnit" width="100" />
        <el-table-column label="采集周期" prop="collectionCycle" width="100" />
        <el-table-column label="数据类型" prop="dataType" width="100" />
        <el-table-column label="寄存器地址/Tag" prop="registerAddress" min-width="150" />
        <el-table-column label="状态" prop="status" width="90" />
        <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="620px">
      <el-form ref="pointFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="测控点编号" prop="pointCode"><el-input v-model="form.pointCode" /></el-form-item>
        <el-form-item label="测控点名称" prop="pointName"><el-input v-model="form.pointName" /></el-form-item>
        <el-form-item label="所属计量器具" prop="measuringDeviceId">
          <el-select v-model="form.measuringDeviceId" filterable placeholder="请选择计量器具">
            <el-option v-for="item in deviceOptions" :key="item.id" :label="item.deviceName || item.deviceCode" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="参数名称" prop="parameterName">
          <el-select v-model="form.parameterName" placeholder="请选择参数" filterable @change="handleParameterChange">
            <el-option v-for="item in metricOptions" :key="item.collectionField" :label="formatMetricLabel(item)" :value="item.collectionField" />
          </el-select>
        </el-form-item>
        <el-form-item label="标准单位" prop="standardUnit"><el-input v-model="form.standardUnit" disabled /></el-form-item>
        <el-form-item label="换算倍率" prop="conversionFactor"><el-input-number v-model="form.conversionFactor" :min="0" :precision="6" controls-position="right" /></el-form-item>
        <el-form-item label="数据占比(%)" prop="dataRatio"><el-input-number v-model="form.dataRatio" :min="1" :precision="4" controls-position="right" /></el-form-item>
        <el-form-item label="原始单位" prop="originalUnit"><el-input v-model="form.originalUnit" /></el-form-item>
        <el-form-item label="采集周期" prop="collectionCycle"><el-input v-model="form.collectionCycle" /></el-form-item>
        <el-form-item label="数据类型" prop="dataType"><el-input v-model="form.dataType" /></el-form-item>
        <el-form-item label="寄存器地址/Tag" prop="registerAddress"><el-input v-model="form.registerAddress" /></el-form-item>
        <el-form-item label="状态" prop="status"><el-input v-model="form.status" /></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="MeasurementControlPoint" lang="ts">
import {
  addMeasurementControlPoint,
  delMeasurementControlPoint,
  getMeasurementControlPoint,
  listMeasurementControlPoint,
  updateMeasurementControlPoint
} from '@/api/ems/measurementControlPoint';
import { MeasurementControlPointForm, MeasurementControlPointQuery, MeasurementControlPointVO } from '@/api/ems/measurementControlPoint/types';
import { listMeasuringDevice } from '@/api/ems/measuringDevice';
import { MeasuringDeviceVO } from '@/api/ems/measuringDevice/types';
import { listEnergyMetric } from '@/api/ems/energyMetric';
import { EnergyMetricVO } from '@/api/ems/energyMetric/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const pointList = ref<MeasurementControlPointVO[]>([]);
const deviceOptions = ref<MeasuringDeviceVO[]>([]);
const metricOptions = 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 queryFormRef = ref<ElFormInstance>();
const pointFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({ visible: false, title: '' });

const initFormData: MeasurementControlPointForm = {
  id: undefined,
  pointCode: '',
  pointName: '',
  measuringDeviceId: undefined,
  parameterName: '',
  standardUnit: '',
  conversionFactor: 1,
  dataRatio: 100,
  originalUnit: '',
  collectionCycle: '',
  dataType: '',
  registerAddress: '',
  status: ''
};

const data = reactive<PageData<MeasurementControlPointForm, MeasurementControlPointQuery>>({
  form: { ...initFormData },
  queryParams: { pageNum: 1, pageSize: 10, pointCode: '', pointName: '', parameterName: '' },
  rules: {
    pointCode: [{ required: true, message: '测控点编号不能为空', trigger: 'blur' }],
    pointName: [{ required: true, message: '测控点名称不能为空', trigger: 'blur' }],
    measuringDeviceId: [{ required: true, message: '所属计量器具不能为空', trigger: 'change' }],
    parameterName: [{ required: true, message: '参数名称不能为空', trigger: 'change' }]
  }
});
const { queryParams, form, rules } = toRefs(data);

const formatMetricLabel = (metric: EnergyMetricVO) => `${metric.metricName || metric.collectionField}${metric.unit ? `(${metric.unit})` : ''}`;
const metricByField = (field?: string) => metricOptions.value.find((item) => item.collectionField === field);
const handleParameterChange = (value?: string) => {
  form.value.standardUnit = metricByField(value)?.unit || '';
};

const loadOptions = async () => {
  const [deviceRes, metricRes] = await Promise.all([
    listMeasuringDevice({ pageNum: 1, pageSize: 1000 }),
    listEnergyMetric({ pageNum: 1, pageSize: 1000 })
  ]);
  deviceOptions.value = (deviceRes as any).rows || [];
  metricOptions.value = (metricRes as any).rows || [];
};
const getList = async () => {
  loading.value = true;
  try {
    const res = await listMeasurementControlPoint(queryParams.value);
    pointList.value = res.rows || [];
    total.value = res.total || 0;
  } finally {
    loading.value = false;
  }
};
const reset = () => {
  form.value = { ...initFormData };
  pointFormRef.value?.resetFields();
};
const handleQuery = () => { queryParams.value.pageNum = 1; getList(); };
const resetQuery = () => { queryFormRef.value?.resetFields(); handleQuery(); };
const handleSelectionChange = (selection: MeasurementControlPointVO[]) => {
  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?: MeasurementControlPointVO) => {
  reset();
  const id = row?.id || ids.value[0];
  const res = await getMeasurementControlPoint(id);
  form.value = { ...res.data };
  dialog.visible = true;
  dialog.title = '修改测控点';
};
const submitForm = () => {
  pointFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    if (form.value.id) await updateMeasurementControlPoint(form.value);
    else await addMeasurementControlPoint(form.value);
    proxy?.$modal.msgSuccess('操作成功');
    dialog.visible = false;
    await getList();
  });
};
const handleDelete = async (row?: MeasurementControlPointVO) => {
  const deleteIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除测控点编号为"' + deleteIds + '"的数据项？');
  await delMeasurementControlPoint(deleteIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
const cancel = () => { dialog.visible = false; reset(); };

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