import {
  nocobaseCpt2PisellCptMap,
  systemFields,
} from '../data-source-form/constants';
import { clearVariables, createFormItemSchema, createFormGroup } from '../data-source-form/utils';
import {
  getVariable,
  getAllVariables,
  createSubmitButton,
  fields2ChildrenSchemas,
} from '../data-source-form/utils';
import { omit } from '../_utils/utils';

const createRenderSchema = (field: any) => {
  let props: Record<string, any> = {
    mode: 'view',
    noStyle: true,
    value: {
      type: 'JSExpression',
      value: 'this.text',
    },
  };

  let componentName = field.uiSchema['x-component'];

  if (
    field.uiSchema['x-validator'] &&
    field.uiSchema['x-validator'] !== 'integer'
  ) {
    props.typeobj = {
      type: field.uiSchema['x-validator'],
      enabled: true,
    };
  }
  if (field.uiSchema['x-component'] === 'Input.JSON') {
    props.normalize = {
      type: 'JSExpression',
      value:
        '(value) => {\n  try {\n    return JSON.parse(value);\n  } catch(error) {\n    console.log(error)\n  }\n  return value\n}',
    };
    props.getValueProps = {
      type: 'JSExpression',
      value:
        '(value) => {\n  try {\n   return { value: value != "" && typeof value === \'object\' ? JSON.stringify(value) : value};\n  } catch(error) {\n    console.log(error)\n  }\n  return {value: value}\n}',
    };
    props.validator = {
      type: 'JSExpression',
      value:
        "async (value) => {\n try {\n    if (typeof value === 'string' && value.trim() !== '') {\n      JSON.parse(value);\n    }\n  } catch (err) {\n    return Promise.reject(new Error(err.message));\n  }\n}",
    };
  }

  if (
    ['Select', 'Radio.Group', 'Checkbox.Group'].includes(
      field.uiSchema['x-component']
    ) &&
    field.uiSchema?.enum?.length > 0
  ) {
    if (
      ['Radio.Group', 'Checkbox.Group'].includes(field.uiSchema['x-component'])
    ) {
      props.direction = 'horizontal';
    }
    props.options = field?.uiSchema?.enum || [];
  }

  // 如果设置了x-read-pretty，则设置为只读
  if (field.uiSchema['x-read-pretty']) {
    props.renderMode = 'view';
  }

  if (field.uiSchema['x-component'] === 'ColorPicker') {
    props.defaultValue = field.uiSchema.default;
  }

  return {
    componentName: nocobaseCpt2PisellCptMap[componentName],
    props,
  };
};

export const getFieldComponent = (field: any) => {
  return createFormItemSchema(field, 'edit').componentName === 'JsonWrapper' ? 'FormItemInput.JSON' : createFormItemSchema(field, 'edit').componentName
}

export const fields2Columns = (fields: any[]) => {
  if (!fields || !fields.length) return [];

  return fields
    .filter((field) => !systemFields.includes(field.name))
    .map((field) => ({
      title: field.uiSchema.title,
      dataIndex: field.name,
      key: field.name,
      align: 'left',
      fixed: '',
      // render: {
      //   type: 'JSSlot',
      //   params: ['text', 'record', 'index'],
      //   value: [createRenderSchema(field)],
      //   id: 'node_ocm49b0bm71',
      // },
      fieldComponent: getFieldComponent(field)
      // fieldProps
    }));
};

export const columns2Options = (columns: any[], allFields: any[] = []) => {
  const showFields: any[] = [];

  const hiddenFields: any[] = [];

  const columnsMap = columns.reduce((acc, column) => {
    acc[column.dataIndex] = column;
    return acc;
  }, {});

  allFields.forEach((field) => {
    if (columnsMap[field.name]) {
      showFields.push({
        isGroup: false,
        label: field.uiSchema.title,
        value: field.name,
        isShow: true,
        children: [],
      });
    } else {
      hiddenFields.push({
        isGroup: false,
        label: field.uiSchema.title,
        value: field.name,
        isShow: false,
        children: [],
      });
    }
  });

  return [
    {
      isGroup: true,
      label: '显示',
      value: 'show',
      isShow: true,
      children: showFields,
    },
    {
      isGroup: true,
      label: '隐藏',
      value: 'hidden',
      children: hiddenFields,
    },
  ];
};

// 生成数据源的值的key
export const genDataSourceValueKey = (target: any, key: string) => {
  return `{{${target.node.id}.value.${key}}}`;
};

// 获取当前target下的所有columns的dataIndex
export const getColumnsDataIndex = (target: any) => {
  return target
    .getProps()
    .getPropValue('columns')
    .map((column: any) => column.dataIndex);
};

// 重置表格的props
export const resetTableProps = (target: any) => {
  target.getProps().setPropValue('columns', []);
  target.getProps().setPropValue('title', '');
  target.getProps().setPropValue('operationContent', {});
  target.getProps().setPropValue('filter', {
    show: false,
    sortButtonShow: false,
    storageMode: '',
    quickFilterMaxLength: 3,
    list: [],
  });
  target.getProps().setPropValue('sort', {
    show: false,
    storageMode: 'localStorage',
  });
  target.getProps().setPropValue('search', {
    show: false,
    placeholder: {
      type: 'i18n',
      'en': 'Search',
      'zh-CN': '搜索',
      'zh-HK': '搜索',
    },
  });
  target.getProps().setPropValue('titleButtons', {
    show: false,
    items: [],
    maxCount: 3,
  });
  clearVariables(target);
};

export const getJsSlot = () => {
  return {
    type: 'JSSlot',
    params: [],
    value: [],
  };
};

const toastTitleMap: Record<'add' | 'edit', any> = {
  add: {
    type: 'i18n',
    en: 'Added successfully',
    'zh-CN': '添加成功',
    'zh-HK': '添加成功',
  },
  edit: {
    type: 'i18n',
    en: 'Updated successfully',
    'zh-CN': '更新成功',
    'zh-HK': '更新成功',
  },
}

export const getFormContent = (target: any, mode: 'add' | 'edit' | 'view') => {
  const fields = getVariable(target, 'currentFields');
  let childrenSchemas = [createFormGroup(fields2ChildrenSchemas(fields, mode))];
  const titleMap = {
    add: '表单(添加)',
    edit: '编辑',
    view: '详情',
  };
  const title = titleMap[mode];

  if (['add', 'edit'].includes(mode)) {
    childrenSchemas = childrenSchemas.concat(
      createSubmitButton({
        afterSubmitType: 'close',
        toastConfig: {
          enable: true,
          showAfterSubmit: true,
          title: toastTitleMap[mode as 'add' | 'edit'],
        },
        childrenString: {
          type: 'i18n',
          en: 'Save',
          'zh-CN': '保存',
          'zh-HK': '保存',
        },
      })
    );
  }

  // 过滤不需要继承的变量
  const variables = omit(getAllVariables(target), [
    'currentValueVariables',
    'dataSourceVariables',
  ]);

  return {
    type: 'JSSlot',
    params: [],
    value: [
      {
        componentName: 'DataSourceForm',
        title,
        props: {
          _variables: variables,
          dataSource: genDataSourceValueKey(target, 'currentDataSource'),
          showTitle: false,
          showDescription: false,
          groupInfoPosition: 'top',
          layout: 'vertical',
          size: 'large',
          renderMode: mode,
          currentValue:
            mode !== 'add'
              ? genDataSourceValueKey(target, 'currentRecord')
              : undefined,
          leaveConfirmConfig: mode !== 'view' ? {
            enable: true,
            title: {
              type: 'i18n',
              en: 'Unsaved changes',
              'zh-CN': '未保存的更改',
              'zh-HK': '未保存的更改',
            },
            content: {
              type: 'i18n',
              en: 'You have unsaved changes. Leave anyway?',
              'zh-CN': '您有未保存的更改，确定要离开？',
              'zh-HK': '您有未保存的更改，確定要離開？',
            },
            okText: {
              type: 'i18n',
              en: 'Leave',
              'zh-CN': '离开',
              'zh-HK': '離開',
            },
            cancelText: {
              type: 'i18n',
              en: 'Stay',
              'zh-CN': '返回',
              'zh-HK': '返回',
              },
            }
          : undefined,
        },
        children: childrenSchemas,
      },
    ],
  };
};

// 生成默认的operation和content
export const setDefaultOperationAndTitleButtons = (target: any) => {
  const operation = {
    show: true,
    title: {
      type: 'i18n',
      'en': 'Operation',
      'zh-CN': '操作',
      'zh-HK': '操作',
    },
    align: 'center',
    fixed: false,
    type: 'link',
    items: [
      {
        label: {
          type: 'i18n',
          'en': 'View',
          'zh-CN': '查看',
          'zh-HK': '查看',
        },
        openMode: 'drawer',
        openContentSize: 'middle',
        openTitle: {
          type: 'i18n',
          'en': 'Detail',
          'zh-CN': '详情',
          'zh-HK': '詳情',
        },
        actionType: 'view',
        key: 'view',
      },
      {
        label: {
          type: 'i18n',
          'en': 'Edit',
          'zh-CN': '编辑',
          'zh-HK': '編輯',
        },
        openMode: 'drawer',
        openContentSize: 'middle',
        openTitle: {
          type: 'i18n',
          'en': 'Edit',
          'zh-CN': '编辑',
          'zh-HK': '編輯',
        },
        actionType: 'edit',
        key: 'edit',
      },
      {
        label: {
          type: 'i18n',
          'en': 'Delete',
          'zh-CN': '删除',
          'zh-HK': '刪除',
        },
        actionType: 'delete',
      },
    ],
  };

  const titleButtons = {
    show: true,
    items: [
      {
        label: {
          type: 'i18n',
          'en': 'Add',
          'zh-CN': '添加',
          'zh-HK': '添加',
        },
        openMode: 'drawer',
        openContentSize: 'middle',
        openTitle: {
          type: 'i18n',
          'en': 'Add',
          'zh-CN': '添加',
          'zh-HK': '添加',
        },
        actionType: 'add',
        key: 'add',
        buttonProps: {
          type: 'primary',
          title: {
            type: 'i18n',
            'en': 'Add',
            'zh-CN': '添加',
            'zh-HK': '添加',
          },
        },
      },
    ],
    maxCount: 3,
  };

  target.getProps().setPropValue('titleButtons', titleButtons);
  target.getProps().setPropValue('operation', operation);

  const operationContent = {
    view: getFormContent(target, 'view'),
    edit: getFormContent(target, 'edit'),
    add: getFormContent(target, 'add'),
  };

  target.getProps().setPropValue('operationContent', operationContent);
};

// 默认显示的filter组件
const defaultShowFilterComponent = [
  'Select',
  'DatePicker',
  'Checkbox',
  'Radio.Group',
  'Checkbox.Group',
]

// 选择数据源后 生成默认的filter
export const setDefaultSearchFilter = (target: any, fields: any[]) => {
  const filterFields = fields
    .filter(
      (field) => !systemFields.includes(field.name) && field.type !== 'json'
    )
    .map((field) => {
      return {
        name: field.name,
        isCustom: false,
        label: field.uiSchema.title,
        value: field.name,
        isHidden: defaultShowFilterComponent.includes(field.uiSchema['x-component']) ? false : true,
      };
    });

  target.getProps().setPropValue('search', {
    show: true,
    placeholder: {
      type: 'i18n',
      'en': 'Search',
      'zh-CN': '搜索',
      'zh-HK': '搜索',
    },
  });

  target.getProps().setPropValue('filter', {
    show: true,
    storageMode: 'localStorage',
    mode: 'simple',
    quickFilterMaxLength: 3,
    items: filterFields,
  });
};

const sortTypeMap: Record<string, string> = {
  float: 'number',
  bigInt: 'number',
};

// 生成默认的排序
export const setDefaultSort = (target: any, fields: any[]) => {
  target.getProps().setPropValue('sort', {
    show: true,
    type: 'simple',
    storageMode: 'localStorage',
    list: fields
      .filter(
        (field) =>
          !systemFields.includes(field.name) &&
          ['string', 'number', 'date', 'bigInt', 'float'].includes(field.type)
      )
      .map((field) => ({
        label: field.uiSchema.title,
        type: sortTypeMap[field.type] || field.type,
        name: field.name,
        isHidden: false,
        localFilter: false,
      })),
  });
};

// 根据当前fields格式化 filter筛选字段的select options
export const fields2TableFilterOptions = (
  fields: any[],
  useFields: string[]
) => {
  if (!fields || !fields.length) return [];

  return fields
    .filter((field) => !systemFields.includes(field.name))
    .map((field) => ({
      title: field.uiSchema.title,
      value: field.name,
      disabled: useFields.includes(field.name),
    }));
};

export const filterTypes = [
  {
    label: '输入框',
    value: 'Input',
  },
  {
    label: '日期范围选择',
    value: 'DateRangePicker',
  },
  {
    label: '下拉选择',
    value: 'Select',
  },
];
