import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesCollectApi } from '#/api/mes/dv/collect';

/** 设备在线状态展示配置 */
export function getOnlineConfig(online?: boolean) {
  return online
    ? { color: 'green', label: '在线', value: true }
    : { color: 'default', label: '离线', value: false };
}

/** 运行状态展示配置 */
export function getStsConfig(sts?: number) {
  if (sts === 2) return { color: 'green', label: '生产' };
  if (sts === 1) return { color: 'orange', label: '待机' };
  return { color: 'default', label: '-' };
}

/** 解析 dataJson 里的数值型字段 */
export function parseDataJson(dataJson?: string): Record<string, number | string> {
  if (!dataJson) return {};
  try {
    const obj = JSON.parse(dataJson);
    const result: Record<string, number | string> = {};
    Object.keys(obj).forEach((k) => {
      const v = obj[k];
      if (typeof v === 'number') {
        // 浮点数保留 2 位，避免 1.9984014E-15 这类科学计数法
        result[k] = Number.isInteger(v) ? v : Number(v.toFixed(2));
      } else {
        result[k] = v;
      }
    });
    return result;
  } catch {
    return {};
  }
}

/** 从 dataJson 提取指定 key 的数值 */
export function getJsonNumber(
  dataJson: string | undefined,
  key: string,
): number | undefined {
  const parsed = parseDataJson(dataJson);
  const v = parsed[key];
  return typeof v === 'number' ? v : undefined;
}

/** 设备状态列表的查询表单 */
export function useDeviceSearchSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'keyword',
      label: '设备名称',
      component: 'Input',
      componentProps: {
        placeholder: '输入设备名称或编码搜索',
        allowClear: true,
      },
    },
    {
      fieldName: 'online',
      label: '在线状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        placeholder: '全部',
        options: [
          { label: '在线', value: true },
          { label: '离线', value: false },
        ],
      },
    },
  ];
}

/** 实时历史分页的查询表单 */
export function useHistorySearchSchema(
  deviceOptions: { label: string; value: string }[],
): VbenFormSchema[] {
  return [
    {
      fieldName: 'deviceCode',
      label: '数采设备',
      component: 'Select',
      componentProps: {
        allowClear: true,
        placeholder: '全部设备',
        options: deviceOptions,
        showSearch: true,
        optionFilterProp: 'label',
      },
    },
    {
      fieldName: 'collectTime',
      label: '采集时间',
      component: 'RangePicker',
      componentProps: {
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
      },
    },
  ];
}

/** 报警分页的查询表单 */
export function useAlarmSearchSchema(
  deviceOptions: { label: string; value: string }[],
): VbenFormSchema[] {
  return [
    {
      fieldName: 'deviceCode',
      label: '数采设备',
      component: 'Select',
      componentProps: {
        allowClear: true,
        placeholder: '全部设备',
        options: deviceOptions,
        showSearch: true,
        optionFilterProp: 'label',
      },
    },
    {
      fieldName: 'status',
      label: '报警状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        placeholder: '全部',
        options: [
          { label: '未消除', value: 0 },
          { label: '已消除', value: 1 },
        ],
      },
    },
    {
      fieldName: 'wmTime',
      label: '报警时间',
      component: 'RangePicker',
      componentProps: {
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
      },
    },
  ];
}

/** 设备状态表格列 */
export function useDeviceGridColumns(): VxeTableGridOptions<MesCollectApi.CollectDevice>['columns'] {
  return [
    {
      field: 'machineryName',
      title: '设备名称',
      minWidth: 140,
      slots: { default: 'machineryName' },
    },
    { field: 'machineryCode', title: '设备编码', width: 140 },
    // 网关上报报文首层 key 取的是网关设备名称，所以该值与「设备名称」相同，不是 C01 这类短编码
    { field: 'collectDeviceCode', title: '数采标识', width: 140 },
    {
      field: 'online',
      title: '在线状态',
      width: 100,
      slots: { default: 'online' },
    },
    {
      field: 'sts',
      title: '运行状态',
      width: 100,
      slots: { default: 'sts' },
    },
    {
      field: 'lastCollectTime',
      title: '最近采集',
      width: 170,
    },
    {
      field: 'currentData',
      title: '当前数据',
      minWidth: 260,
      slots: { default: 'currentData' },
    },
    {
      field: 'activeAlarmCount',
      title: '未消除报警',
      width: 110,
      slots: { default: 'alarm' },
    },
    {
      field: 'taskName',
      title: '当前任务',
      width: 160,
      formatter: ({ cellValue }: any) => cellValue || '-',
    },
    {
      field: 'workstationName',
      title: '工作站',
      width: 140,
      formatter: ({ cellValue }: any) => cellValue || '-',
    },
    {
      field: 'actions',
      title: '操作',
      width: 130,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}

/** 实时历史表格列 */
export function useHistoryGridColumns(): VxeTableGridOptions<MesCollectApi.CollectRealtime>['columns'] {
  return [
    { field: 'id', title: '编号', width: 90 },
    { field: 'deviceCode', title: '数采设备', width: 140 },
    { field: 'collectTime', title: '采集时间', width: 170 },
    {
      field: 'stsName',
      title: '运行状态',
      width: 100,
      formatter: ({ cellValue }: any) => cellValue || '-',
    },
    {
      field: 'dataJson',
      title: '采集数据',
      minWidth: 320,
      slots: { default: 'dataJson' },
    },
    { field: 'taskId', title: '任务编号', width: 100 },
    { field: 'workOrderId', title: '工单编号', width: 100 },
  ];
}

/** 报警表格列 */
export function useAlarmGridColumns(): VxeTableGridOptions<MesCollectApi.CollectAlarm>['columns'] {
  return [
    { field: 'id', title: '编号', width: 90 },
    { field: 'deviceCode', title: '数采设备', width: 140 },
    {
      field: 'wmMsg',
      title: '报警内容',
      minWidth: 200,
      formatter: ({ cellValue }: any) => cellValue || '-',
    },
    { field: 'wmTime', title: '报警时间', width: 170 },
    {
      field: 'statusName',
      title: '状态',
      width: 100,
      slots: { default: 'status' },
    },
    { field: 'clearTime', title: '消除时间', width: 170 },
    {
      field: 'actions',
      title: '操作',
      width: 120,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
