'use strict';

import React, { Component } from 'react';
import {
  categoryMap,
  getReactMaterials,
  getVueMaterials,
} from '../../service/database';
import { Button, Grid, Feedback, Tag } from '@icedesign/base';
import IceLoading from '@ali/ice-loading';
import { Link } from 'react-router';
import cx from 'classnames';
import kebabCase from 'kebab-case';
import { join } from 'path';
import moment from 'moment';
import uppercamelcase from 'uppercamelcase';
import './BlockDetail.scss';

const { Row, Col } = Grid;
const Toast = Feedback.toast;

export default class BlockDetail extends Component {
  static displayName = 'BlockDetail';

  state = {
    loading: true,
    blockData: {},
  };

  async componentWillMount() {
    await this.loadBlockDetail(this.props);
  }

  loadBlockDetail = async (props = this.props) => {
    const { router } = props;
    const { type = 'react' } = props.location.query;
    this.type = type;
    this.isLayout = /\/layout/.test(router.location.pathname);

    const { blocks, layouts } = await (type === 'react'
      ? getReactMaterials
      : getVueMaterials)();

    const targets = this.isLayout ? layouts : blocks;

    let blockData;

    for (let i = 0, l = targets.length; i < l; i++) {
      if (targets[i].name === router.params.blockName) {
        blockData = Object.assign({}, targets[i]);
      }
    }

    if (blockData) {
      this.setState({
        loading: false,
        blockData,
      });
    } else {
      Toast.error('未找到您查找的信息 5s 后返回.');
      setTimeout(() => {
        this.props.router.goBack();
      }, 5000);
    }
  };

  async componentWillReceiveProps(nextProps) {
    if (nextProps.params.blockName !== this.props.params.blockName) {
      await this.loadBlockDetail(nextProps);
    }
  }

  renderCategoryTag = (category, idx) => {
    return (
      <Link
        key={idx}
        to={join(window.routePrefix, `/block?category=${category}`)}
      >
        <Tag shape="readonly" animation={false} style={styles.categoryTag}>
          {categoryMap[category] || category}
        </Tag>
      </Link>
    );
  };

  renderUseComponents = (componentList) => {
    /**
     * componentList: [{
     *   basePackage: '@icedesign/base',
     *   document: '/component/button',
     *   className: 'Button',
     * }]
     */
    if (Array.isArray(componentList) && componentList.length > 0) {
      return (
        <Row className="list-item">
          <Col span={6}>使用的组件</Col>
          <Col style={styles.listItemDescription}>
            {componentList.map((component, idx) => {
              let documentURL = '';
              if (component.basePackage === '@icedesign/base') {
                documentURL = join(
                  window.routePrefix,
                  'component',
                  kebabCase(component.className).replace(/^-/, '')
                );
                return (
                  <Link className="list-item-link" key={idx} to={documentURL}>
                    {component.className}
                  </Link>
                );
              } else {
                const lowName = component.className.toLowerCase();
                documentURL = join(
                  window.routePrefix,
                  `/component/${/^ice/.test(lowName) ? lowName : lowName}`
                );
                return (
                  <Link className="list-item-link" key={idx} to={documentURL}>
                    {component.className}
                  </Link>
                );
              }
            })}
          </Col>
        </Row>
      );
    } else {
      return null;
    }
  };

  render() {
    const { loading, blockData } = this.state;
    const { router } = this.props;
    if (loading) {
      return (
        <IceLoading
          type="ball-spin-fade-loader"
          color="#1B73FF"
          style={{
            margin: '0 auto',
          }}
        />
      );
    } else {
      const isLayout = /\-layout$/.test(blockData.npm);
      let subTitle = blockData.name.split('-').join(' ');
      subTitle = subTitle[0].toUpperCase() + subTitle.slice(1);
      return (
        <Row
          wrap
          className={cx({
            'block-detail-container': true,
            'layout-detail-container': isLayout,
          })}
        >
          <Col
            xxs={24}
            s={16}
            style={{ paddingBottom: '15px', marginBottom: '25px' }}
          >
            <div className="block-detail-content">
              <div className="block-snapshoot">
                <img
                  style={{ borderRadius: '4px' }}
                  src={blockData.screenshot || blockData.snapshot}
                />
              </div>
            </div>
          </Col>
          <Col xxs={24} s={8} className="block-info">
            <div className="block-basic">
              <h2 className="block-name">{blockData.title}</h2>
              <p className="block-sub-name">{subTitle}</p>
              <div className="block-links">
                {!this.isLayout && (
                  <Button
                    type="primary"
                    style={{
                      marginRight: '10px',
                      height: '30px',
                      wordBreak: 'keep-all',
                      display: this.type === 'vue' ? 'none' : null,
                    }}
                    data-spm={`${blockData.title}-preview-link`}
                    onClick={() => {
                      this.props.router.push(
                        join(
                          window.routePrefix,
                          `/${this.isLayout ? 'layout' : 'block'}/${
                            blockData.name
                          }/preview`
                        )
                      );
                    }}
                  >
                    <span style={styles.linkStyle}>
                      <img
                        src="https://gw.alicdn.com/tfs/TB12j_pawmTBuNjy1XbXXaMrVXa-42-30.png"
                        style={styles.icon}
                      />{' '}
                      预览
                    </span>
                  </Button>
                )}
                <Button
                  type="primary"
                  style={{ marginRight: '10px', height: '30px' }}
                >
                  <a
                    style={styles.linkStyle}
                    target="_blank"
                    data-spm={`${blockData.title}-source-link`}
                    href={getSource(blockData, this.type, this.isLayout)}
                  >
                    <img
                      src="https://gw.alicdn.com/tfs/TB12K2CaqmWBuNjy1XaXXXCbXXa-30-38.png"
                      style={{ ...styles.icon, height: '14px', width: '10px' }}
                    />{' '}
                    查看代码
                  </a>
                </Button>
              </div>
            </div>
            <div className="block-meta">
              <h2 style={styles.groupTitle}>模块说明</h2>
              <div style={styles.para}>
                {blockData.description || (
                  <span>
                    暂无描述，您可以通过提交
                    <a
                      target="_blank"
                      href={`https://github.com/alibaba/ice/tree/master/react-materials/${
                        this.isLayout ? 'layouts' : 'blocks'
                      }/${blockData.className}/package.json`}
                    >
                      {' '}
                      PR{' '}
                    </a>，补充描述(description)来帮助我们完善。
                  </span>
                )}
              </div>

              <h2 style={styles.groupTitle}>基本信息</h2>

              <Row className="list-item">
                <Col span={6}>最新版本</Col>
                <Col>
                  <span
                    className="list-item-link"
                    style={{
                      ...styles.listItemDescription,
                      color: null,
                    }}
                    target="_blank"
                  >
                    {blockData.source.version}
                  </span>
                </Col>
              </Row>

              <Row className="list-item">
                <Col span={6}>所属分类</Col>
                <Col style={styles.listItemDescription}>
                  {(blockData.categories || []).map(this.renderCategoryTag)}
                </Col>
              </Row>

              <Row className="list-item">
                <Col span={6}>创建时间</Col>
                <Col style={styles.listItemDescription}>
                  {moment(blockData.publishTime).format('YYYY-MM-DD HH:mm')}
                </Col>
              </Row>

              <Row className="list-item">
                <Col span={6}>更新时间</Col>
                <Col style={styles.listItemDescription}>
                  {moment(blockData.updateTime).format('YYYY-MM-DD HH:mm')}
                </Col>
              </Row>
              {this.renderUseComponents(blockData.useComponents)}
            </div>
          </Col>
        </Row>
      );
    }
  }
}

const styles = {
  linkStyle: {
    padding: 0,
    color: '#fff',
    lineHeight: '30px',
    backgroundColor: 'transparent',
    display: 'inline-flex',
    marginRight: 0,
    marginTop: '-1px',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  subTitle: {
    color: '#000',
  },
  para: {
    color: '#666',
    fontWeight: 'light',
    lineHeight: 10 / 7,
  },
  icon: {
    width: '16px',
    height: '11px',
    marginRight: '6px',
  },
  groupTitle: {
    fontSize: '20px',
    color: '#333',
    fontWeight: '500',
    margin: '30px 0 10px',
  },
  listItemDescription: {
    fontSize: '14px',
    color: '#333',
    wordBreak: 'break-word',
  },
  categoryTag: {
    height: '24px',
    lineHeight: '22px',
    margin: '0 10px 8px 0',
    color: '#1B73FF',
    fontSize: '12px',
    fontWeight: 'normal',
    cursor: 'pointer',
  },
};

function getSource(blockData, type = 'react', isLayout) {
  if (blockData.repository === 'https://github.com/alibaba/ice') {
    return `https://github.com/alibaba/ice/tree/master/${type}-materials/${
      isLayout ? 'layouts' : 'blocks'
    }/${uppercamelcase(blockData.name)}`;
  } else {
    return blockData.repository;
  }
}
