<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="82px">
            <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="commandType">
              <el-select v-model="queryParams.commandType" placeholder="请选择命令类型" clearable style="width: 160px">
                <el-option v-for="item in commandTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="执行状态" prop="executeStatus">
              <el-select v-model="queryParams.executeStatus" placeholder="请选择执行状态" clearable style="width: 160px">
                <el-option v-for="item in executeStatusOptions" :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:controlCommandLog: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:controlCommandLog: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:controlCommandLog:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['ems/base:controlCommandLog: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="controlCommandLogList" @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="180" show-overflow-tooltip>
          <template #default="scope">
            {{ resolveMonitorName(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns[3].visible" label="命令类型" align="center" width="110">
          <template #default="scope">
            <dict-tag :options="commandTypeOptions" :value="scope.row.commandType" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[4].visible" label="命令内容" align="center" prop="commandContent" min-width="240" show-overflow-tooltip />
        <el-table-column v-if="columns[5].visible" label="执行状态" align="center" width="110">
          <template #default="scope">
            <dict-tag :options="executeStatusOptions" :value="scope.row.executeStatus" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" label="响应内容" align="center" prop="responseContent" min-width="240" show-overflow-tooltip />
        <el-table-column v-if="columns[7].visible" label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <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:controlCommandLog:edit']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ems/base:controlCommandLog: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="controlCommandLogFormRef" :model="form" :rules="rules" label-width="96px">
        <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="命令类型" prop="commandType">
              <el-select v-model="form.commandType" placeholder="请选择命令类型" style="width: 100%">
                <el-option v-for="item in commandTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行状态" prop="executeStatus">
              <el-select v-model="form.executeStatus" placeholder="请选择执行状态" style="width: 100%">
                <el-option v-for="item in executeStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="命令内容" prop="commandContent">
          <editor v-model="form.commandContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="响应内容" prop="responseContent">
          <editor v-model="form.responseContent" :min-height="192" />
        </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="ControlCommandLog" lang="ts">
import { listIntegrationEndpointAll } from '@/api/ems/base/integrationEndpoint';
import { getMonitorInfoTree } from '@/api/ems/base/baseMonitorInfo';
import { listControlCommandLog, getControlCommandLog, delControlCommandLog, addControlCommandLog, updateControlCommandLog } from '@/api/ems/base/controlCommandLog';
import type { IntegrationEndpointVO } from '@/api/ems/base/integrationEndpoint/types';
import type { ControlCommandLogVO, ControlCommandLogQuery, ControlCommandLogForm } from '@/api/ems/base/controlCommandLog/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 commandTypeOptions = [
  { label: '读取指令', value: 'READ' },
  { label: '写入指令', value: 'WRITE' },
  { label: '心跳校验', value: 'PING' },
  { label: '复位指令', value: 'RESET' }
];

const executeStatusOptions = [
  { label: '待执行', value: 'PENDING' },
  { label: '执行中', value: 'PROCESSING' },
  { label: '执行成功', value: 'SUCCESS' },
  { label: '执行失败', value: 'FAIL' }
];

const endpointOptions = ref<IntegrationEndpointVO[]>([]);
const monitorTreeOptions = ref<MonitorTreeNode[]>([]);
const monitorNameMap = ref<Record<string, string>>({});

const controlCommandLogList = ref<ControlCommandLogVO[]>([]);
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 controlCommandLogFormRef = ref<ElFormInstance>();

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

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

const createFormData = (): ControlCommandLogForm => ({
  id: undefined,
  endpointId: undefined,
  endpointName: undefined,
  monitorCode: undefined,
  monitorName: undefined,
  commandType: 'WRITE',
  commandContent: undefined,
  executeStatus: 'PENDING',
  responseContent: undefined
});

const data = reactive<PageData<ControlCommandLogForm, ControlCommandLogQuery>>({
  form: createFormData(),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    endpointId: undefined,
    monitorCode: undefined,
    commandType: undefined,
    executeStatus: undefined,
    params: {}
  },
  rules: {
    endpointId: [{ required: true, message: '端点不能为空', trigger: 'change' }],
    monitorCode: [{ required: true, message: '点位不能为空', trigger: 'change' }],
    commandType: [{ 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) {
      monitorNameMap.value[key] = label;
    }
    return {
      ...node,
      label,
      value,
      children
    };
  });

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

const resolveMonitorName = (row?: Partial<ControlCommandLogVO> | Partial<ControlCommandLogForm> | null) =>
  row?.monitorName || monitorNameMap.value[String(row?.monitorCode || '')] || 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[];
  monitorNameMap.value = {};
  monitorTreeOptions.value = normalizeMonitorTree(((monitorRes as any).data ?? monitorRes ?? []) as MonitorTreeNode[]);
};

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

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

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

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

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

const handleSelectionChange = (selection: ControlCommandLogVO[]) => {
  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?: ControlCommandLogVO) => {
  reset();
  const targetId = row?.id ?? ids.value[0];
  if (!targetId) {
    return;
  }
  const res = await getControlCommandLog(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) => {
  form.value.monitorName = monitorNameMap.value[String(monitorCode || '')];
};

const submitForm = () => {
  controlCommandLogFormRef.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 updateControlCommandLog(form.value);
      } else {
        await addControlCommandLog(form.value);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

const handleDelete = async (row?: ControlCommandLogVO) => {
  const targetIds = row?.id ?? ids.value;
  await proxy?.$modal.confirm(`是否确认删除回写命令日志编号为"${targetIds}"的数据项？`);
  await delControlCommandLog(targetIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

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