import React, { useState } from 'react';
import {
  SplitButtonGroup,
  CnBalloon,
  Button,
  Icon,
  Dropdown,
  Tree,
  MenuButton,
  CnTooltip,
} from '@cainiaofe/cn-ui';
import { ImportField } from './import-field';
import isPlainObject from 'lodash/isPlainObject';
import { handleI18nLabel } from '@/common/util/util';

const { CodeControl } = window?.VisualEngineUtils || {};

export const TableAddOneBtn = (props) => {
  const [importVisible, setImportVisible] = useState(false);
  const [visible, setVisible] = useState(false);
  const [code, setCode] = useState('');
  const { onAdd, prop, dataPrimaryKey, handleFieldList } = props;
  const currentId = prop?.getNode?.()?.id;

  const allInsert = () => {
    let result = getNewList();

    if (typeof handleFieldList === 'function') {
      result = handleFieldList(result);
    }
    if (result.length > 0) {
      props?.prop?.setValue(result);
      const sel = window?.AliLowCodeEngine?.project?.currentDocument?.selection;
      if (sel) {
        sel?.select?.();
        setTimeout(() => {
          sel?.select?.(currentId);
        });
      }
    }
  };

  const addInsert = () => {
    const primaryKey = dataPrimaryKey || 'dataIndex';
    const existColumns = props?.prop?.getValue() || [];
    const existMap = {};
    existColumns.forEach((item) => {
      if (item[primaryKey]) {
        existMap[item[primaryKey]] = true;
      }
    });
    let result = getNewList();
    if (typeof handleFieldList === 'function') {
      result = handleFieldList(result);
    }
    const toAddList = [...existColumns];
    if (result.length > 0) {
      result.forEach((item) => {
        if (item[primaryKey] && existMap[item[primaryKey]]) {
        } else {
          toAddList.push(item);
        }
      });
      if (toAddList.length > 0) {
        props?.prop?.setValue(toAddList);
        const sel =
          window?.AliLowCodeEngine?.project?.currentDocument?.selection;
        if (sel) {
          sel?.select?.();
          setTimeout(() => {
            sel?.select?.(currentId);
          });
        }
      }
    }
    setVisible(false);
  };

  const getNewList = () => {
    const list = [];
    try {
      const originList = JSON.parse(code);
      if (originList.length > 0) {
        originList.forEach((item = {}) => {
          let title;
          let dataIndex;
          const originTitle = handleI18nLabel(item.title);
          if (typeof originTitle === 'string') {
            title = originTitle;
          } else if (isPlainObject(originTitle) && originTitle?.zh_CN) {
            title = originTitle?.zh_CN;
          }
          title = handleI18nLabel(title);
          if (item.dataIndex) {
            dataIndex = item.dataIndex;
          } else if (item.dataKey) {
            dataIndex = item.dataKey;
          }
          if (dataIndex && title) {
            list.push({
              dataIndex,
              title,
              format: 'text',
            });
          }
        });
      }
    } catch (e) {}
    return list;
  };

  return (
    <SplitButtonGroup style={{ width: '100%', display: 'flex' }}>
      <Button onClick={() => onAdd?.()} type={'primary'} style={{ flex: 1 }}>
        添加一项
      </Button>
      <MenuButton autoWidth={false} type={'primary'} label='快速导入'>
        <MenuButton.Item onClick={() => setImportVisible(true)}>
          选择其他组件的字段并导入
        </MenuButton.Item>
        <MenuButton.Item onClick={() => setVisible(true)}>
          导入老Cone搭建的表格列配置
        </MenuButton.Item>
      </MenuButton>
      <CnBalloon
        // type={'primary'}
        visible={visible}
        align={'tr'}
        v2
        onVisibleChange={(v) => {
          setVisible(v);
        }}
        closable
        triggerType={'click'}
        title={
          <div className=''>
            粘贴要导入的表格列JSON{' '}
            <a
              target={'_blank'}
              href='https://yuque.antfin.com/docs/share/63fd9c72-a3a8-467f-a5dd-03d45a04c36e?#MuUS8'
            >
              使用文档
            </a>
          </div>
        }
        trigger={' '}
      >
        <div className=''>
          <div style={{ marginBottom: '10px' }}>
            请到老cone{' '}
            <CnTooltip v2 align={'tr'} trigger={<a>表头JSON</a>}>
              <div style={{ width: '260px', height: '190px' }}>
                <img
                  style={{ width: '100%' }}
                  src='https://img.alicdn.com/imgextra/i4/O1CN01UT7hFP1DLdyo9g5hs_!!6000000000200-0-tps-1812-1272.jpg'
                />
              </div>
            </CnTooltip>
            中复制，并粘贴到代码框中
          </div>
          <CodeControl
            value={code}
            options={{ minimap: { enabled: false }, lineNumbers: 'off' }}
            className=''
            mode='json' // 'javascript', 'json', 'html', 'css', 'jsx'
            fontSize={14}
            tabSize={2}
            // readOnly={false}
            style={{ width: '100%', height: 200 }}
            onChange={(code) => {
              setCode(code);
            }}
            // // 如果为 false 或者 0 则不启动节流阀
            throttle={600}
            lineNumbers={'off'}
            enableOutline={false}
            // enableSuggestion
            // defaultSuggestion
            // enableBlurChange
            // diyWordSuggestion
            // checkSyntax // 是否开启预编译检查（限js）
            // // customeSuggestion={getSuggestion}
            // onEditorDidMount={(editor, monaco) => {
            //   console.log('editor, monaco:::>>>', editor, monaco);
            // }} // 编辑器初始化完成
          />
          <div
            style={{
              paddingTop: '10px',
              borderTop: '1px solid #ddd',
              display: 'flex',
              justifyContent: 'flex-end',
            }}
          >
            <Button
              size={'small'}
              onClick={allInsert}
              // type={'secondary'}
            >
              覆盖导入
            </Button>
            &nbsp;&nbsp;
            <Button size={'small'} onClick={addInsert} type={'secondary'}>
              增量导入
            </Button>
          </div>
        </div>
      </CnBalloon>
      <ImportField
        visible={importVisible}
        setVisible={setImportVisible}
        prop={prop}
        dataPrimaryKey={dataPrimaryKey}
        trigger={<div />}
      />
    </SplitButtonGroup>
  );
};
