import React, { memo, useState } from 'react';
import { useDrag } from 'react-dnd';
import Thumb from 'components/Thumb';
import styles from './GalleryGroupItem.less';
import { connect } from 'react-redux';
import { updateVersion } from 'models/updateVersion';
import message from 'components/message';
import { ComponentIcon } from 'components/IconButton';
import EasyvModal, { useActionModalRef } from 'components/EasyvModal';
import EasyvButton from 'components/EasyvButton';
import { getComponent } from 'utils/component';
import EasyGUI,{ Utils } from '@easyv/react-gui';
import { useProductionInfo } from 'components/easyUse';
import {getAssetsUrl} from 'utils/utils'

const { reduceConfig } = Utils;

function GalleryGroupItem({ base, addComponent, updateVersion }) {
  const { name, moduleName, version, thumb, lock, edition } = base;
  const [chartPresetConfigValue, setChartPresetConfigValue] = useState<Array<any>>([]); //选中的第三方图表数据
  const modalRef = useActionModalRef();
  const [defaultPresetConfigration, setDefaultPresetConfigration] = useState<any[]>([]);
  const [configuration, setConfiguration] = useState<Array<any>>([]);
  const [position, setPosition] = useState<{ x: number; y: number }>();
  const productionInfo = useProductionInfo();
  const { isRenew = false } = productionInfo;
  const [, drag] = useDrag({
    item: { name, type: 'component' },
    end: async (item, monitor) => {
      const dropResult = monitor.getDropResult();
      if (item && dropResult) {
        createComponent({
          name,
          moduleName,
          version,
          position: { x: dropResult.position.x + 50, y: dropResult.position.y + 30 }
        });
      }
    },
    canDrag: () => {
      return !lock;
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging
    })
  });

  const createComponent = async ({
    name,
    moduleName,
    version,
    position
  }: {
    name: string;
    moduleName: string;
    version: string;
    position?: { x: number; y: number }; // position不传默认创建在视图中间,否则创建在拖拽的位置
  }) => {
    const hide = message.loading('正在导入组件资源...', 0);
    const component = await getComponent(moduleName, version);
    if (component) {
      hide();
      const { presetConfigration = [], configuration = [] } = component.getDefaultConfig();
      if (presetConfigration.length) {
        setDefaultPresetConfigration(presetConfigration);
        setConfiguration(configuration);
        setChartPresetConfigValue([]);
        setPosition(position);
        modalRef.current?.show();
      } else {
        addComponent({ name, moduleName, version, position });
      }
      return;
    }
    hide();
    message.error('操作失败');
  };

  const handleClick = async () => {
    // 在这里做相应的判断操作
    if (lock) {
      const targetV = edition === 2 ? 'saas_advanced' : edition === 3 ? 'saas_vip' : null;
      if (targetV) {
        updateVersion({ show: true, targetVersion: targetV });
      } else {
        message.error('组件未分配权限，请联系平台运营人员处理');
      }
    } else {
      createComponent({ name, moduleName, version });
    }
  };

  const handleDrag = (e) => {
    // 通过 effectAllowed 来区别图片/视频的拖拽上传
    e.dataTransfer.effectAllowed = 'move';
  };
  return (
    <>
      <li ref={drag} className={styles.cpnt} onClick={handleClick} onDragStart={handleDrag}>
        <Thumb className={styles.img} src={thumb ? getAssetsUrl(`${thumb}`) : undefined} />
        <p className={styles.name}>{name}</p>
        <ComponentIcon isRenew={isRenew} measureType={edition} className={styles.lock} renderType="layout" />
      </li>
      <EasyvModal.ActionModal
        ref={modalRef}
        title="选择图表"
        className={styles.modalWrapper}
        width={620}
        maxHeight={'100%'}
        content={
          <div className={styles.modalContent}>
            <p>请选择需要添加的{name}图表</p>
            <EasyGUI
              config={defaultPresetConfigration}
              onChange={(e) => {
                setChartPresetConfigValue(e);
                setDefaultPresetConfigration(e);
              }}
            />
          </div>
        }
        onCancel={() => modalRef.current?.close()}
        closable={true}
        keyboard={false}
        maskClosable={false}
        footer={
          <EasyvButton
            theme="primary"
            disabled={!chartPresetConfigValue.length}
            onClick={async () => {
              const component = await getComponent(moduleName, version);
              component
                .onCreate(reduceConfig(chartPresetConfigValue), configuration)
                .then((res) => {
                  addComponent({ name, moduleName, version, configuration: res, position });
                  modalRef.current?.close();
                })
                .catch((error) => {
                  message.error('创建失败');
                });
            }}>
            确认
          </EasyvButton>
        }
      />
    </>
  );
}

const mapDispatchToProps = {
  updateVersion
};
export default connect(null, mapDispatchToProps)(memo(GalleryGroupItem));
