import {
  generateDataSource,
  isArrayNotEmpty,
} from '@/common/util/util';

// 组件复制时修复数据源
function fixComponentDataSource(config) {
  const { node } = config;
  const { id, componentName, propsData } = node || {};
  const { _dataSource, _dataSourceName } = propsData || {};
  window?.AliLowCodeEngine?.designer?.currentDocument?.nodesMap?.forEach?.(
    (item) => {
      const {
        id: itemId,
        componentName: itemComponentName,
        propsData: itemPropsData,
      } = item || {};
      if (id && id !== itemId && componentName === itemComponentName) {
        if (
          _dataSourceName &&
          _dataSourceName === itemPropsData?._dataSourceName
        ) {
          // 组件是复制的，需要修复下数据源
          const ds = generateDataSource({ componentName });
          if (ds?.name) {
            node?.setPropValue?.('_dataSourceName', ds.name);
            node?.setPropValue?.('_dataSource', {
              type: 'variable',
              variable: `state.${ds.name}`,
            });
            if (['CnDialog', 'CnFormDialog'].includes(componentName)) {
              const title = node?.getPropValue?.('title');
              if (title) {
                let newTitle;
                if (title.dm && !title?.dm?.includes?.('_副本')) {
                  newTitle = {
                    ...title,
                    dm: title?.dm + '_副本',
                  };
                } else if (
                  typeof title === 'string' &&
                  !title.includes?.('_副本')
                ) {
                  newTitle = title + '_副本';
                }
                if (newTitle) {
                  node.setPropValue('title', newTitle);
                }
              }
            }
            console.log('组件复制成功:', id);
          }
        }
      }
    },
  );

  if (!_dataSource && !_dataSourceName) {
    const ds = generateDataSource({ componentName: 'CnTable' });
    if (ds?.name) {
      node?.setPropValue?.('_dataSourceName', ds.name);
      node?.setPropValue?.('_dataSource', {
        type: 'variable',
        variable: `state.${ds.name}`,
      });
    }
  }
}

export function getStatusDataSource() {
  return [
    {
      label: '成功',
      value: 'success',
    },
    {
      label: '警告',
      value: 'warning',
    },
    {
      label: '错误',
      value: 'error',
    },
    {
      label: '提示',
      value: 'info',
    },
    {
      label: '无效',
      value: 'invalid',
    },
  ];
}

export { fixComponentDataSource };
