<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" label-width="90px">
            <el-form-item label="端点名称" prop="endpointId">
              <el-select v-model="queryParams.endpointId" placeholder="请选择端点" clearable filterable style="width: 220px">
                <el-option v-for="item in endpointOptions" :key="item.id" :label="item.endpointName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="点位名称" prop="monitorCode">
              <el-tree-select
                v-model="queryParams.monitorCode"
                :data="monitorTreeOptions"
                :props="monitorTreeProps"
                placeholder="请选择点位"
                clearable
                filterable
                check-strictly
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item label="第三方源点位" prop="sourcePointCode">
              <el-input v-model="queryParams.sourcePointCode" placeholder="请输入第三方源点位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="第三方目标点位" prop="targetPointCode">
              <el-input v-model="queryParams.targetPointCode" placeholder="请输入第三方目标点位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="数据格式" prop="dataFormat">
              <el-select v-model="queryParams.dataFormat" placeholder="请选择数据格式" clearable style="width: 160px">
                <el-option v-for="item in dataFormatOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="启用状态" prop="isEnable">
              <el-select v-model="queryParams.isEnable" placeholder="请选择启用状态" clearable style="width: 160px">
                <el-option v-for="item in enableStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </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="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['ems/base:integrationPointMap:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['ems/base:integrationPointMap:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['ems/base:integrationPointMap:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['ems/base:integrationPointMap:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="integrationPointMapList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="columns[0].visible" label="序号" type="index" width="60" align="center" />
        <el-table-column v-if="columns[1].visible" label="端点名称" align="center" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            {{ resolveEndpointName(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns[2].visible" label="点位名称" align="center" min-width="220" show-overflow-tooltip>
          <template #default="scope">
            <div>{{ resolveMonitorName(scope.row) }}</div>
            <div class="sub-text">{{ scope.row.metricCode || '-' }}</div>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[3].visible" label="第三方源点位" align="center" prop="sourcePointCode" min-width="180" show-overflow-tooltip />
        <el-table-column v-if="columns[4].visible" label="第三方目标点位" align="center" prop="targetPointCode" min-width="180" show-overflow-tooltip />
        <el-table-column v-if="columns[5].visible" label="数据格式" align="center" width="110">
          <template #default="scope">
            <dict-tag :options="dataFormatOptions" :value="scope.row.dataFormat" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" label="启用状态" align="center" width="110">
          <template #default="scope">
            <dict-tag :options="enableStatusOptions" :value="scope.row.isEnable" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[7].visible" label="转换脚本" align="center" prop="transformScript" min-width="220" show-overflow-tooltip />
        <el-table-column label="操作" align="center" fixed="right" width="110" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ems/base:integrationPointMap:edit']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ems/base:integrationPointMap:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

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

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="720px" append-to-body>
      <el-form ref="integrationPointMapFormRef" :model="form" :rules="rules" label-width="104px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="端点名称" prop="endpointId">
              <el-select v-model="form.endpointId" placeholder="请选择端点" filterable style="width: 100%" @change="handleEndpointChange">
                <el-option v-for="item in endpointOptions" :key="item.id" :label="item.endpointName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="点位名称" prop="monitorCode">
              <el-tree-select
                v-model="form.monitorCode"
                :data="monitorTreeOptions"
                :props="monitorTreeProps"
                placeholder="请选择点位"
                filterable
                check-strictly
                style="width: 100%"
                @change="handleMonitorChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="测量项编码">
              <el-input v-model="form.metricCode" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据格式" prop="dataFormat">
              <el-select v-model="form.dataFormat" placeholder="请选择数据格式" style="width: 100%">
                <el-option v-for="item in dataFormatOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="第三方源点位" prop="sourcePointCode">
              <el-input v-model="form.sourcePointCode" placeholder="请输入第三方源点位编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="第三方目标点位" prop="targetPointCode">
              <el-input v-model="form.targetPointCode" placeholder="请输入第三方目标点位编码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="转换脚本" prop="transformScript">
          <el-input
            v-model="form.transformScript"
            type="textarea"
            :rows="4"
            placeholder="请输入转换说明或脚本片段，留空时默认按原值透传"
          />
        </el-form-item>

        <el-form-item label="启用状态" prop="isEnable">
          <el-radio-group v-model="form.isEnable">
            <el-radio v-for="item in enableStatusOptions" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="IntegrationPointMap" lang="ts">
import { listIntegrationEndpointAll } from '@/api/ems/base/integrationEndpoint';
import { getMonitorInfoTree } from '@/api/ems/base/baseMonitorInfo';
import { listIntegrationPointMap, getIntegrationPointMap, delIntegrationPointMap, addIntegrationPointMap, updateIntegrationPointMap } from '@/api/ems/base/integrationPointMap';
import type { IntegrationEndpointVO } from '@/api/ems/base/integrationEndpoint/types';
import type { IntegrationPointMapVO, IntegrationPointMapQuery, IntegrationPointMapForm } from '@/api/ems/base/integrationPointMap/types';
import type { EmsTreeNode } from '@/api/ems/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface MonitorTreeNode extends EmsTreeNode {
  label?: string;
  value?: string | number;
  children?: MonitorTreeNode[];
}

const dataFormatOptions = [
  { label: 'JSON', value: 'JSON' },
  { label: 'XML', value: 'XML' }
];

const enableStatusOptions = [
  { label: '启用', value: '0' },
  { label: '停用', value: '1' }
];

const endpointOptions = ref<IntegrationEndpointVO[]>([]);
const monitorTreeOptions = ref<MonitorTreeNode[]>([]);
const monitorInfoMap = ref<Record<string, { monitorName?: string; metricCode?: string }>>({});

const integrationPointMapList = ref<IntegrationPointMapVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const columns = ref<FieldOption[]>([
  { key: 0, label: '序号', visible: true, children: [] },
  { key: 1, label: '端点名称', visible: true, children: [] },
  { key: 2, label: '点位名称', visible: true, children: [] },
  { key: 3, label: '第三方源点位', visible: true, children: [] },
  { key: 4, label: '第三方目标点位', visible: true, children: [] },
  { key: 5, label: '数据格式', visible: true, children: [] },
  { key: 6, label: '启用状态', visible: true, children: [] },
  { key: 7, label: '转换脚本', visible: true, children: [] }
]);

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

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

const monitorTreeProps = {
  label: 'label',
  value: 'value',
  children: 'children'
};

const createFormData = (): IntegrationPointMapForm => ({
  id: undefined,
  endpointId: undefined,
  endpointName: undefined,
  monitorCode: undefined,
  monitorName: undefined,
  metricCode: undefined,
  sourcePointCode: undefined,
  targetPointCode: undefined,
  transformScript: undefined,
  dataFormat: 'JSON',
  isEnable: '0'
});

const data = reactive<PageData<IntegrationPointMapForm, IntegrationPointMapQuery>>({
  form: createFormData(),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    endpointId: undefined,
    monitorCode: undefined,
    sourcePointCode: undefined,
    targetPointCode: undefined,
    dataFormat: undefined,
    isEnable: undefined,
    params: {}
  },
  rules: {
    endpointId: [{ required: true, message: '端点不能为空', trigger: 'change' }],
    monitorCode: [{ required: true, message: '点位不能为空', trigger: 'change' }],
    sourcePointCode: [{ required: true, message: '第三方源点位不能为空', trigger: 'blur' }],
    dataFormat: [{ required: true, message: '数据格式不能为空', trigger: 'change' }]
  }
});

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

const normalizeMonitorTree = (nodes: MonitorTreeNode[] = []): MonitorTreeNode[] =>
  nodes.map((node) => {
    const children = Array.isArray(node.children) ? normalizeMonitorTree(node.children) : [];
    const label = node.monitorName || node.label || node.name || node.monitorCode || String(node.value ?? '');
    const value = node.monitorCode || node.value || node.monitorId || node.objId || node.id;
    const key = String(value ?? '');
    if (key) {
      monitorInfoMap.value[key] = {
        monitorName: node.monitorName || label,
        metricCode: node.metricCode as string | undefined
      };
    }
    return {
      ...node,
      label,
      value,
      children
    };
  });

const resolveEndpointName = (row?: Partial<IntegrationPointMapVO> | null) =>
  row?.endpointName || endpointOptions.value.find((item) => item.id === row?.endpointId)?.endpointName || (row?.endpointId ? String(row.endpointId) : '-');

const resolveMonitorName = (row?: Partial<IntegrationPointMapVO> | Partial<IntegrationPointMapForm> | null) =>
  row?.monitorName || monitorInfoMap.value[String(row?.monitorCode || '')]?.monitorName || row?.monitorCode || '-';

const loadOptions = async () => {
  const [endpointRes, monitorRes] = await Promise.all([
    listIntegrationEndpointAll(),
    getMonitorInfoTree({
      monitorTypeList: [5, 6, 7, 8, 9, 10]
    } as any)
  ]);
  endpointOptions.value = (((endpointRes as any).rows ?? (endpointRes as any).data ?? endpointRes) || []) as IntegrationEndpointVO[];
  monitorInfoMap.value = {};
  monitorTreeOptions.value = normalizeMonitorTree(((monitorRes as any).data ?? monitorRes ?? []) as MonitorTreeNode[]);
};

const getList = async () => {
  loading.value = true;
  try {
    const res = await listIntegrationPointMap(queryParams.value);
    integrationPointMapList.value = ((res as any).rows ?? []) as IntegrationPointMapVO[];
    total.value = Number((res as any).total ?? 0);
  } finally {
    loading.value = false;
  }
};

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

const reset = () => {
  form.value = createFormData();
  integrationPointMapFormRef.value?.resetFields();
};

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

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

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

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加对接点位映射';
};

const handleUpdate = async (row?: IntegrationPointMapVO) => {
  reset();
  const targetId = row?.id ?? ids.value[0];
  if (!targetId) {
    return;
  }
  const res = await getIntegrationPointMap(targetId);
  form.value = {
    ...createFormData(),
    ...((res as any).data ?? {})
  };
  dialog.visible = true;
  dialog.title = '修改对接点位映射';
};

const handleEndpointChange = (endpointId?: string | number) => {
  form.value.endpointName = endpointOptions.value.find((item) => item.id === endpointId)?.endpointName;
};

const handleMonitorChange = (monitorCode?: string | number) => {
  const matched = monitorInfoMap.value[String(monitorCode || '')];
  // 点位名称和测量项编码都来自同一条点位档案，表单里不再让用户手填，避免前后端关联错位。
  form.value.monitorName = matched?.monitorName;
  form.value.metricCode = matched?.metricCode;
};

const submitForm = () => {
  integrationPointMapFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    }
    buttonLoading.value = true;
    try {
      handleEndpointChange(form.value.endpointId);
      handleMonitorChange(form.value.monitorCode);
      if (form.value.id) {
        await updateIntegrationPointMap(form.value);
      } else {
        await addIntegrationPointMap(form.value);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

const handleDelete = async (row?: IntegrationPointMapVO) => {
  const targetIds = row?.id ?? ids.value;
  await proxy?.$modal.confirm(`是否确认删除对接点位映射编号为"${targetIds}"的数据项？`);
  await delIntegrationPointMap(targetIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleExport = () => {
  proxy?.download(
    'ems/base/integrationPointMap/export',
    {
      ...queryParams.value
    },
    `integrationPointMap_${new Date().getTime()}.xlsx`
  );
};

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

<style scoped>
.sub-text {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  line-height: 18px;
}
</style>
