import { computed } from 'vue';

import { z } from '@vben/common-ui';

import dayjs from 'dayjs';

import {
  getCommonGetSelectList,
  postAggregationIoTplatformGetIoTplatformProductInfoAsync,
} from '#/api-client';
import { $t } from '#/locales';

// 查询表单配置
export const querySchema = computed(() => [
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatform',
    label: $t('abp.deviceInfos.ioTPlatform'),
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'IoTPlatformTypeEnum',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      placeholder:
        $t('common.pleaseSelect') + $t('abp.deviceInfos.ioTPlatform'),
      afterFetch: (res: any) => {
        if (Array.isArray(res)) {
          return res;
        }
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        return [];
      },
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformProductId',
    label: $t('common.BelongingProductName'),
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatform;
      },
      triggerFields: ['ioTPlatform'],
    },
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;

      return {
        api: platform
          ? postAggregationIoTplatformGetIoTplatformProductInfoAsync
          : null,
        // 聚合服务要求 JSON Body 传参
        params: {
          body: {
            ioTPlatformType:
              typeof platform === 'string'
                ? Number.parseInt(platform)
                : platform,
          },
        },
        labelField: 'productName',
        valueField: 'ioTPlatformProductId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder:
          $t('common.pleaseSelect') + $t('common.BelongingProductName'),
        afterFetch: (res: any) => {
          if (Array.isArray(res)) {
            return res;
          }
          if (res && Array.isArray(res.items)) {
            return res.items;
          }
          if (res && Array.isArray(res.data)) {
            return res.data;
          }
          if (res && res.data && Array.isArray(res.data.items)) {
            return res.data.items;
          }
          return [];
        },
      };
    },
  },
  {
    component: 'Input',
    fieldName: 'SearchKeyWords',
    label: $t('common.SearchKeyWords'),
  },
]);

// 列表列配置
export const tableSchema = computed(() => [
  {
    field: 'deviceModelName',
    title: '设备端物模型名称',
    minWidth: 180,
    showOverflow: 'tooltip',
  },
  {
    field: 'ioTPlatform',
    title: $t('abp.deviceInfos.ioTPlatform'),
    minWidth: 120,
    showOverflow: 'tooltip',
    formatter: ({ cellValue }: { cellValue: any }) => {
      const map: Record<number | string, string> = {
        1: 'CTWing',
        2: 'OneNET',
      };
      return map[cellValue] || cellValue || '-';
    },
  },
  {
    field: 'ioTPlatformProductId',
    title: '平台产品ID',
    minWidth: 160,
    showOverflow: 'tooltip',
  },
  {
    field: 'scriptName',
    title: '脚本函数名称',
    minWidth: 160,
    showOverflow: 'tooltip',
  },
  {
    field: 'functionAnalysisFlag',
    title: '解析启用',
    minWidth: 100,
    slots: { default: 'functionAnalysisFlag' },
  },
  {
    field: 'creationTime',
    title: $t('common.creationTime'),
    minWidth: 180,
    formatter: ({ cellValue }: { cellValue: any }) => {
      return cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') : '-';
    },
  },
  {
    field: 'action',
    title: $t('common.action'),
    width: 250,
    fixed: 'right',
    slots: { default: 'action' },
  },
]);

// 新增设备端物模型表单
export const addDeviceThingModelFormSchema = computed(() => [
  {
    component: 'Input',
    fieldName: 'deviceModelName',
    label: '设备端物模型名称',
    rules: z.preprocess(
      (v) => (v == null ? '' : v),
      z.string().min(1, $t('common.required')),
    ),
    componentProps: {
      placeholder: `${$t('common.pleaseInput')}设备端物模型名称`,
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatform',
    label: $t('abp.deviceInfos.ioTPlatform'),
    rules: z.preprocess(
      (v) => (v == null ? '' : v),
      z.string().min(1, $t('common.required')),
    ),
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'IoTPlatformTypeEnum',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      placeholder:
        $t('common.pleaseSelect') + $t('abp.deviceInfos.ioTPlatform'),
      afterFetch: (res: any) => {
        if (Array.isArray(res)) {
          return res;
        }
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        return [];
      },
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformProductId',
    label: $t('common.BelongingProductName'),
    rules: z.preprocess(
      (v) => (v == null ? '' : v),
      z.string().min(1, $t('common.required')),
    ),
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;

      return {
        api: platform
          ? postAggregationIoTplatformGetIoTplatformProductInfoAsync
          : null,
        params: {
          body: {
            ioTPlatformType:
              typeof platform === 'string'
                ? Number.parseInt(platform)
                : platform,
          },
        },
        labelField: 'productName',
        valueField: 'ioTPlatformProductId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder:
          $t('common.pleaseSelect') + $t('common.BelongingProductName'),
        afterFetch: (res: any) => {
          if (Array.isArray(res)) {
            return res;
          }
          if (res && Array.isArray(res.items)) {
            return res.items;
          }
          if (res && Array.isArray(res.data)) {
            return res.data;
          }
          if (res && res.data && Array.isArray(res.data.items)) {
            return res.data.items;
          }
          return [];
        },
      };
    },
  },
  {
    component: 'Input',
    fieldName: 'scriptName',
    label: '脚本函数名称',
    rules: z.preprocess(
      (v) => (v == null ? '' : v),
      z.string().min(1, $t('common.required')),
    ),
    componentProps: {
      placeholder: `${$t('common.pleaseInput')}脚本函数名称`,
    },
  },
  {
    component: 'Textarea',
    fieldName: 'functionScript',
    label: '脚本函数体',
    componentProps: {
      rows: 6,
      placeholder: '请输入脚本函数体（用于解析MODBUS设备数据）',
    },
  },
]);

// 编辑设备端物模型表单
export const editDeviceThingModelFormSchema = computed(() => [
  {
    component: 'Input',
    fieldName: 'deviceModelName',
    label: '设备端物模型名称',
    rules: z.preprocess(
      (v) => (v == null ? '' : v),
      z.string().min(1, $t('common.required')),
    ),
    componentProps: {
      placeholder: `${$t('common.pleaseInput')}设备端物模型名称`,
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatform',
    label: $t('abp.deviceInfos.ioTPlatform'),
    rules: z.preprocess(
      (v) => (v == null ? '' : v),
      z.string().min(1, $t('common.required')),
    ),
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'IoTPlatformTypeEnum',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      disabled: true, // 编辑时不允许修改平台
      placeholder:
        $t('common.pleaseSelect') + $t('abp.deviceInfos.ioTPlatform'),
      afterFetch: (res: any) => {
        if (Array.isArray(res)) {
          return res;
        }
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        return [];
      },
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformProductId',
    label: $t('common.BelongingProductName'),
    rules: z.preprocess(
      (v) => (v == null ? '' : v),
      z.string().min(1, $t('common.required')),
    ),
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;

      return {
        api: platform
          ? postAggregationIoTplatformGetIoTplatformProductInfoAsync
          : null,
        params: {
          body: {
            ioTPlatformType:
              typeof platform === 'string'
                ? Number.parseInt(platform)
                : platform,
          },
        },
        labelField: 'productName',
        valueField: 'ioTPlatformProductId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        disabled: true, // 编辑时不允许修改平台产品
        placeholder:
          $t('common.pleaseSelect') + $t('common.BelongingProductName'),
        afterFetch: (res: any) => {
          if (Array.isArray(res)) {
            return res;
          }
          if (res && Array.isArray(res.items)) {
            return res.items;
          }
          if (res && Array.isArray(res.data)) {
            return res.data;
          }
          if (res && res.data && Array.isArray(res.data.items)) {
            return res.data.items;
          }
          return [];
        },
      };
    },
  },
  {
    component: 'Input',
    fieldName: 'scriptName',
    label: '脚本函数名称',
    rules: z.preprocess(
      (v) => (v == null ? '' : v),
      z.string().min(1, $t('common.required')),
    ),
    componentProps: {
      placeholder: `${$t('common.pleaseInput')}脚本函数名称`,
    },
  },
  {
    component: 'Textarea',
    fieldName: 'functionScript',
    label: '脚本函数体',
    componentProps: {
      rows: 6,
      placeholder: '请输入脚本函数体（用于解析MODBUS设备数据）',
    },
  },
]);
