import React, { useReducer } from 'react';
import { connect } from 'react-redux';
import EditableText from 'components/EditableText';
import { Checkbox, Export } from '../../components';
import classNames from 'classnames';
import { Space, Button } from '@easyv/antd';
import EasyvButton from 'components/EasyvButton';
import DragSourceContainer from 'containers/screen-list/components/DragSourceContainer';
import { TYPES } from '../../constant';
import defaultScreenItemBgSrc from '../../../../../images/default_screen_bg.png';
import dragImg from 'images/icon_moveguide.png';
import sourceVideo from 'images/sourceVideo.png';
import sourceImg from 'images/sourceImg.png';
import styles from './index.less';
import EasyvModal, { useConfirmRef } from 'components/EasyvModal';
import { useProductionInfo } from 'components/easyUse';
import ExportMultiMaterisl from '../../components/Export/ExportMultiMaterisl';
import ExportResource from '../../components/Export/ExportResource';
import ExportModal from 'containers/resource/components/Export/ExportModal';
import EasyvTooltip from 'components/EasyvTooltip';
import { getAssetsUrl } from 'utils/utils';

const productTypes = (key, isRenew) => {
  const obj = isRenew
    ? {
        [TYPES.ENJOY]: '开发版',
        [TYPES.ADVANCE]: '企业版',
      }
    : {
        [TYPES.ENJOY]: '尊享版',
        [TYPES.ADVANCE]: '高级版',
      };
  return obj[key];
};

function TemplateItem({
  prefixCls,
  edit = false,
  item,
  selected,
  onSelect,
  onDelete,
  onPreview,
  onCreate,
  onDragStart,
  onDragEnd,
  type,
  userInfo,
  onRename,
}) {
  const deletRef = useConfirmRef();
  const [deleteParams, setDeleteParams] = useReducer((a, b) => ({ ...a, ...b }), {});
  const productionInfo = useProductionInfo();
  const { isRenew } = productionInfo;
  const disabled = item.isDisable;
  const productType = disabled ? '失效' : productTypes(item.measureType, isRenew);

  const dragStart = () => {
    onDragStart(item.id, type, item.userCategoryId);
  };

  const dragEnd = () => {
    onDragEnd(item.id);
  };

  const updateName = (val) => {
    onRename(item.id, val);
  };

  const CENTER_TYPE = {
    TEMPLATE: 0,
    MATERIAL: 1,
    RESOURCE: 2,
    MODAL: 3,
  };

  // 导出
  const EXPORT = {
    [CENTER_TYPE.TEMPLATE]: (
      <Export list={[item]}>
        <EasyvTooltip title="导出">
          <i className="icon iconfont icon-daochu" />
        </EasyvTooltip>
      </Export>
    ),
    [CENTER_TYPE.MATERIAL]: (
      <ExportMultiMaterisl data={[{ id: item.id, name: item.name }]}>
        <EasyvTooltip title="导出">
          <i className="icon iconfont icon-daochu" />
        </EasyvTooltip>
      </ExportMultiMaterisl>
    ),
    [CENTER_TYPE.RESOURCE]: (
      <ExportResource data={[{ id: item.id, name: item.name }]}>
        <EasyvTooltip title="导出">
          <i className="icon iconfont icon-daochu" />
        </EasyvTooltip>
      </ExportResource>
    ),
    [CENTER_TYPE.MODAL]: (
      <ExportModal data={[{ id: item.id, name: item.name }]}>
        <EasyvTooltip title="导出">
          <i className="icon iconfont icon-daochu" />
        </EasyvTooltip>
      </ExportModal>
    ),
  };

  return (
    <div
      className={classNames(prefixCls, { disabled })}
      onClick={() => {
        !disabled && edit && onSelect(!selected);
      }}>
      <div className={`${prefixCls}-back`} />
      <div className={`${prefixCls}-img-wrapper`}>
        <div className={`${prefixCls}-img`}>
          <div className="img">
            {productType && (
              <span
                className={classNames(`${prefixCls}-img-tag`, {
                  enjoy: item.measureType === TYPES.ENJOY,
                  advance: item.measureType === TYPES.ADVANCE,
                  disabled,
                })}>
                {productType}
              </span>
            )}
            {item.type === 2 && <img src={sourceVideo} alt="" style={{ objectFit: 'fill' }} />}
            {item.type !== 2 && type === 0 && (
              <img
                src={item.thumb}
                onError={(e: any) => {
                  e.target.onerror = null;
                  e.target.src = defaultScreenItemBgSrc;
                }}
                alt=""
              />
            )}
            {item.type !== 2 && type !== 0 && (
              <img
                src={item.thumb ? getAssetsUrl(`${item.thumb}`) : sourceImg}
                onError={(e: any) => {
                  e.target.onerror = null;
                  e.target.src = defaultScreenItemBgSrc;
                }}
                alt=""
              />
            )}
          </div>
          {!edit && (
            <div className={`${prefixCls}-img-operate`}>
              {disabled ? (
                <EasyvButton
                  onClick={() => {
                    deletRef.current?.show();
                    setDeleteParams({ id: item.id, title: item.name });
                  }}
                  theme="primary">
                  删除
                </EasyvButton>
              ) : (
                <>
                  <div>
                    <Space size={16}>
                      <DragSourceContainer
                        id={item.id}
                        className="drag"
                        dragPreviewImg={dragImg}
                        onDragStart={dragStart}
                        onDragEnd={dragEnd}>
                        <EasyvTooltip title="移动">
                          <i className="icon iconfont icon-btn_move" />
                        </EasyvTooltip>
                      </DragSourceContainer>
                      {(window.appConfig.LOCAL ||
                        (type === 0 && userInfo?.edition?.id === 'saas_vip') ||
                        isRenew) &&
                        EXPORT[type]}
                      {/* {EXPORT[type]} */}
                      <EasyvTooltip title="删除">
                        <i
                          className="icon iconfont icon-btn_delete"
                          onClick={() => {
                            deletRef.current?.show();
                            setDeleteParams({ id: item.id, title: item.name });
                          }}
                        />
                      </EasyvTooltip>
                    </Space>
                    <div>
                      <Space size={12}>
                        <EasyvButton theme="default" onClick={() => onPreview(item)}>
                          预览
                        </EasyvButton>
                        {type === 0 && (
                          <Button type="primary" onClick={() => onCreate(item)}>
                            创建
                          </Button>
                        )}
                      </Space>
                    </div>
                  </div>
                </>
              )}
            </div>
          )}
        </div>
      </div>
      <div className={`${prefixCls}-content`}>
        <div className={`${prefixCls}-content-title`}>
          {!disabled && edit && (
            <Checkbox className={`${prefixCls}-content-title-checkbox`} checked={selected} />
          )}
          {type !== 0 && item.edition === 0 && !edit ? (
            <EditableText
              text={item.name}
              className={styles.screenName}
              onCommit={updateName}
              suffix={
                <div className={styles.box}>
                  <i
                    className={classNames('icon iconfont icon-bianji screenItem-content-editIcon')}
                  />
                </div>
              }
            />
          ) : (
            <div className={`${prefixCls}-content-title-row`}>
              <span>{item.name}</span>
              {item.purchased && (
                <span className={`${prefixCls}-content-title-row-purchased`}>已购</span>
              )}
            </div>
          )}
        </div>
        <p className={`${prefixCls}-content-desc`}>
          <span>{item.category}</span>
          <span>{item.info}</span>
        </p>
      </div>
      <EasyvModal.Confirm
        content={
          <p style={{ whiteSpace: 'pre-wrap' }}>
            删除收藏的&nbsp;
            <span style={{ color: '#fff' }}>{deleteParams.title}</span>
            &nbsp;{type === 0 ? '模板' : '素材'}
            后无法恢复，确认删除？
          </p>
        }
        closable={false}
        title={`删除${type === 0 ? '模板' : '素材'}`}
        ref={deletRef}
        onOk={() => {
          onDelete(deleteParams.id);
          deletRef.current?.close();
        }}
      />
    </div>
  );
}

TemplateItem.defaultProps = {
  prefixCls: 'source-template-item',
};

const mapStateToProps = ({ user: { userInfo } }) => ({
  userInfo,
});

export default connect(mapStateToProps)(TemplateItem);
