import { ref } from 'vue';
import { BasicColumn, FormSchema } from '/@/components/Table';
import type { FormSchema as QFormSchema } from '/@/components/Form/index';
import moment from 'moment';
import { getOrganizationList } from '/@/api/system/system';
import { copyTransFun } from '/@/utils/fnUtils';
import { findDictItemByCode } from '/@/api/system/dict';
import { isTiming, isWeek, isMonth, isFixedTime } from './timeConfig';
import { AggregateDataEnum } from '../../device/localtion/cpns/TimePeriodForm/config';
import {
  getPacketIntervalByRange,
  getPacketIntervalByValue,
  intervalOption,
} from '../../device/localtion/cpns/TimePeriodForm/helper';

export enum QueryWay {
  LATEST = 'latest',
  TIME_PERIOD = 'timePeriod',
}
export enum SchemaFiled {
  WAY = 'queryMode',
  TIME_PERIOD = 'timePeriod',
  KEYS = 'keys',
  DATE_RANGE = 'dataRange',
  START_TS = 'startTs',
  END_TS = 'endTs',
  INTERVAL = 'interval',
  LIMIT = 'limit',
  AGG = 'agg',
  ORDER_BY = 'orderBy',
}
export const organizationId = ref('');

// 表格配置
export const columns: BasicColumn[] = [
  {
    title: '配置名称',
    dataIndex: 'name',
    width: 120,
  },
  {
    title: '所属组织',
    dataIndex: 'organizationDTO.name',
    width: 120,
  },
  {
    title: '数据类型',
    dataIndex: 'dataType',
    width: 120,
    format: (_text: string, record: Recordable) => {
      return record.dataType === 0 ? '原始数据' : '聚合数据';
    },
  },
  {
    title: '配置状态',
    dataIndex: 'status',
    width: 120,
    slots: { customRender: 'configStatus' },
  },
  {
    title: '执行方式',
    dataIndex: 'executeWay',
    width: 160,
    format: (_text: string, record: Recordable) => {
      return record.executeWay === 0 ? '立即执行' : '定时执行';
    },
  },
  {
    title: '执行设备',
    dataIndex: 'devices',
    width: 160,
    slots: { customRender: 'doDeviceSlot' },
  },
  {
    title: '创建人',
    dataIndex: 'createUserName',
    width: 180,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
  },
];
export const viewDeviceColumn: BasicColumn[] = [
  {
    title: '设备',
    dataIndex: 'device',
    width: 80,
  },
  {
    title: '属性',
    dataIndex: 'attribute',
    width: 120,
  },
];

// 查询配置
export const searchFormSchema: FormSchema[] = [
  {
    field: 'name',
    label: '配置名称',
    component: 'Input',
    colProps: { span: 6 },
    componentProps: {
      maxLength: 36,
      placeholder: '请输入配置名称',
    },
  },
  {
    field: 'status',
    label: '配置状态',
    component: 'Select',
    colProps: { span: 6 },
    componentProps: {
      options: [
        {
          label: '启用',
          value: 1,
        },
        {
          label: '禁用',
          value: 0,
        },
      ],
      placeholder: '请选择配置状态',
    },
  },
  {
    field: 'sendTime',
    label: '创建时间',
    component: 'RangePicker',
    componentProps: {
      showTime: {
        defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
      },
    },
    colProps: { span: 6 },
  },
];

// 新增编辑配置
export const formSchema: QFormSchema[] = [
  {
    field: 'name',
    label: '报表名称',
    colProps: { span: 24 },
    required: true,
    component: 'Input',
    componentProps: {
      maxLength: 64,
      placeholder: '请输入报表名称',
    },
  },
  {
    field: 'organizationId',
    label: '所属组织',
    colProps: { span: 24 },
    component: 'ApiTreeSelect',
    required: true,
    componentProps: () => {
      return {
        maxLength: 250,
        placeholder: '请选择所属组织',
        api: async () => {
          const data = await getOrganizationList();
          copyTransFun(data as any as any[]);
          return data;
        },
        async onChange(e) {
          organizationId.value = e;
        },
      };
    },
  },
  {
    field: 'remark',
    label: '描述',
    colProps: { span: 24 },
    component: 'InputTextArea',
    componentProps: {
      maxLength: 255,
      placeholder: '请输入描述',
    },
  },
  {
    field: 'executeWay',
    component: 'RadioGroup',
    helpMessage: [
      `立即执行，在创建完报表配置后，启用配置即执行。
    定时执行，用户定义执行时间，启用后，
    在满足执行时间条件后，自动执行。`,
    ],
    label: '执行方式',
    colProps: {
      span: 24,
    },
    defaultValue: 0,
    componentProps: ({ formActionType }) => {
      const { updateSchema, setFieldsValue } = formActionType;
      const options = [
        {
          label: '立即执行',
          value: 0,
        },
        {
          label: '定时执行',
          value: 1,
        },
      ];
      return {
        options,
        placeholder: '请选择执行方式',
        onChange(e) {
          let dataCompareOpions: any = [];
          setFieldsValue({
            startTs: 1000,
            interval: 1000,
          });
          if (e.target.value == 0) {
            setFieldsValue({ queryMode: QueryWay.LATEST });
            dataCompareOpions = [
              { label: '固定周期', value: QueryWay.LATEST },
              { label: '自定义周期', value: QueryWay.TIME_PERIOD },
            ];
            updateSchema({
              field: SchemaFiled.WAY,
              componentProps: {
                options: dataCompareOpions,
              },
            });
          } else {
            setFieldsValue({ queryMode: QueryWay.LATEST });
            setFieldsValue({ startTs: 5000 });
            setFieldsValue({ interval: 1000 });
            dataCompareOpions = [{ label: '固定周期', value: QueryWay.LATEST }];
            updateSchema({
              defaultValue: QueryWay.LATEST,
              field: SchemaFiled.WAY,
              componentProps: {
                options: dataCompareOpions,
              },
            });
          }
        },
        maxLength: 250,
      };
    },
  },
  {
    field: 'cycleType',
    component: 'Select',
    label: '周期',
    required: true,
    colProps: { span: 24 },
    defaultValue: 0,
    componentProps: {
      placeholder: '请选择周期',
      options: [
        { label: '每日', value: 0 },
        { label: '每周', value: 1 },
        { label: '每月', value: 2 },
      ],
    },
    ifShow: ({ values }) => isTiming(values.executeWay),
  },
  {
    field: 'currentCycle',
    component: 'ApiSelect',
    label: '每周',
    required: true,
    colProps: { span: 24 },
    defaultValue: '0 0 0 ? * 1',
    componentProps: {
      placeholder: '请选择周期',
      api: findDictItemByCode,
      params: {
        dictCode: 'every_week',
      },
      labelField: 'itemText',
      valueField: 'itemValue',
    },
    ifShow: ({ values }) => isWeek(values.cycleType),
  },
  {
    field: 'cycleTime',
    component: 'ApiSelect',
    label: '每月',
    required: true,
    colProps: { span: 24 },
    defaultValue: '0 0 0 1 * ? *',
    componentProps: {
      placeholder: '请选择月份',
      api: findDictItemByCode,
      params: {
        dictCode: 'every_month',
      },
      labelField: 'itemText',
      valueField: 'itemValue',
    },
    ifShow: ({ values }) => isMonth(values.cycleType),
  },
  {
    field: 'cronTime',
    component: 'ApiSelect',
    label: '时间',
    required: true,
    colProps: { span: 24 },
    defaultValue: '0 0 0  * * ?',
    componentProps: {
      placeholder: '请选择时间',
      api: findDictItemByCode,
      params: {
        dictCode: 'every_day',
      },
      labelField: 'itemText',
      valueField: 'itemValue',
    },
    ifShow: ({ values }) => isTiming(values.executeWay),
  },
  {
    field: 'devices',
    label: '设备',
    component: 'Select',
    slot: 'devices',
    colProps: { span: 24 },
  },
  {
    field: 'dataType',
    label: '数据类型',
    required: true,
    component: 'Select',
    componentProps: ({ formActionType }) => {
      const { updateSchema, setFieldsValue } = formActionType;
      const options = [
        { label: '原始数据', value: 0 },
        { label: '聚合数据', value: 1 },
      ];
      return {
        options,
        onSelect(e) {
          let dataCompareOpions: any = [];
          if (e == 0) {
            setFieldsValue({ agg: 'NONE' });
            dataCompareOpions = [{ label: '空', value: AggregateDataEnum.NONE }];
            updateSchema({
              field: SchemaFiled.AGG,
              componentProps: {
                options: dataCompareOpions,
              },
            });
          } else {
            setFieldsValue({ agg: '' });
            dataCompareOpions = [
              { label: '最小值', value: AggregateDataEnum.MIN },
              { label: '最大值', value: AggregateDataEnum.MAX },
              { label: '平均值', value: AggregateDataEnum.AVG },
              { label: '求和', value: AggregateDataEnum.SUM },
              { label: '计数', value: AggregateDataEnum.COUNT },
            ];
            updateSchema({
              field: SchemaFiled.AGG,
              componentProps: {
                options: dataCompareOpions,
              },
            });
          }
        },
        maxLength: 250,
        placeholder: '请选择属性性质',
      };
    },
    colProps: { span: 24 },
  },
  {
    field: SchemaFiled.AGG,
    label: '聚合条件',
    component: 'Select',
    required: true,
    componentProps: {
      placeholder: '请选择聚合条件',
      getPopupContainer: () => document.body,
    },
  },
  {
    field: 'limit',
    required: true,
    label: '最大条数',
    component: 'InputNumber',
    defaultValue: 100,
    ifShow({ values }) {
      return values[SchemaFiled.AGG] === AggregateDataEnum.NONE;
    },
    colProps: { span: 12 },
    componentProps: {
      placeholder: '请输入最大条数',
      min: 7,
      max: 50000,
    },
  },
  {
    field: SchemaFiled.WAY,
    label: '查询周期',
    component: 'RadioGroup',
    defaultValue: QueryWay.LATEST,
    required: true,
    componentProps({ formActionType }) {
      const { setFieldsValue } = formActionType;
      return {
        placeholder: '请选择查询周期',
        options: [
          { label: '固定周期', value: QueryWay.LATEST },
          { label: '自定义周期', value: QueryWay.TIME_PERIOD },
        ],
        onChange(value) {
          console.log(value);
          value === QueryWay.LATEST
            ? setFieldsValue({
                [SchemaFiled.DATE_RANGE]: [],
                [SchemaFiled.START_TS]: null,
                [SchemaFiled.END_TS]: null,
              })
            : setFieldsValue({ [SchemaFiled.START_TS]: null });
        },
      };
    },
  },
  {
    field: SchemaFiled.DATE_RANGE,
    label: '时间段',
    component: 'RangePicker',
    required: true,
    ifShow({ values }) {
      return values[SchemaFiled.WAY] === QueryWay.TIME_PERIOD && !isFixedTime(values.executeWay);
    },
    componentProps: {
      showTime: {
        defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
      },
    },
    colProps: {
      span: 10,
    },
  },
  {
    field: SchemaFiled.START_TS,
    label: '最近时间',
    component: 'Select',
    required: true,
    ifShow({ values }) {
      return values[SchemaFiled.WAY] == QueryWay.LATEST;
    },
    componentProps({ formActionType }) {
      const { setFieldsValue } = formActionType;
      return {
        defaultValue: 1000,
        placeholder: '请选择近期时间',
        options: intervalOption,
        onChange() {
          setFieldsValue({ [SchemaFiled.INTERVAL]: null });
        },
      };
    },
  },
  {
    field: SchemaFiled.INTERVAL,
    label: '间隔时间',
    component: 'Select',
    required: true,
    ifShow({ values }) {
      return values[SchemaFiled.WAY] == QueryWay.LATEST;
    },
    componentProps({ formModel, formActionType }) {
      const options =
        formModel[SchemaFiled.WAY] === QueryWay.LATEST
          ? getPacketIntervalByValue(formModel[SchemaFiled.START_TS])
          : getPacketIntervalByRange(formModel[SchemaFiled.DATE_RANGE]);
      if (formModel[SchemaFiled.AGG] !== AggregateDataEnum.NONE) {
        formActionType.setFieldsValue({ [SchemaFiled.LIMIT]: null });
      }
      return {
        placeholder: '请选择间隔时间',
        options,
      };
    },
  },
];
