'use strict';

import React, { Component } from 'react';
import { Table, moment, Grid, Input, Button } from '@icedesign/base';
import '@icedesign/base/lib/table/style';
import IceLoading from '@ali/ice-loading';
import { normalizeGitUrl } from '../utils';
import './CollectDetail.less';

const { Row, Col } = Grid;

export default class CollectDetailView extends Component {
  getBasicCompDatasource(moduleFileMap) {
    const { data } = this.props;
    const basicComponents = data ? data.statistics.basicComponents : [];
    const basicComponentsTimes = data
      ? data.statistics.basicComponentsTimes
      : {};
    return basicComponents.map((compName, id) => ({
      id: id + 1, // 序号
      comp: compName, // 组件名称
      times: basicComponentsTimes[compName], // 引用次数
      files: moduleFileMap[compName],
    }));
  }

  getBusinessCompDatasource(moduleFileMap) {
    const { data } = this.props;
    const businessComponents = data ? data.statistics.businessComponents : [];
    const businessComponentsTimes = data
      ? data.statistics.businessComponentsTimes
      : {};
    return businessComponents.map((compName, id) => ({
      id: id + 1, // 序号
      comp: compName, // 组件名称
      times: businessComponentsTimes[compName], // 引用次数
      files: moduleFileMap[compName],
    }));
  }

  getThirdDatasource(moduleFileMap) {
    const { data } = this.props;
    const thirdModules = data ? data.statistics.thirdModules : [];
    const thirdModulesTimes = data ? data.statistics.thirdModulesTimes : {};
    return thirdModules.map((compName, id) => ({
      id: id + 1, // 序号
      comp: compName, // 模块名称
      times: thirdModulesTimes[compName], // 引用次数
      files: moduleFileMap[compName],
    }));
  }

  render() {
    const { data, basic, isLoading, error } = this.props;

    if (error) {
      console.error(error.stack);
      return <div>{JSON.stringify(error)}</div>;
    } else if (isLoading) {
      return <IceLoading style={{ margin: '100px auto' }} />;
    }

    const { baseComponent } = basic;
    basic.developers = basic.developers || [];
    if (basic.developers.indexOf(basic.author) === -1) {
      basic.developers.push(basic.author);
    }

    const moduleFileMap = {};

    // 有少数麼有 data 的情况
    if (data) {
      const {
        pkg, // package.json
        analyzed, // 每个 js/jsx 文件的 import 或 require 情况
      } = data;

      Object.keys(analyzed).forEach((fileName) => {
        const filed = analyzed[fileName];
        filed.forEach((obj) => {
          if (obj && obj.fromModule === baseComponent) {
            if (obj.importedValue.forEach) {
              // array
              obj.importedValue.forEach((module) => {
                if (moduleFileMap[module]) {
                  moduleFileMap[module][fileName] = true;
                } else {
                  moduleFileMap[module] = { [fileName]: true };
                }
              });
            } else {
              // string
              if (moduleFileMap[obj.importedValue]) {
                moduleFileMap[obj.importedValue][fileName] = true;
              } else {
                moduleFileMap[obj.importedValue] = { [fileName]: true };
              }
            }
          } else {
            if (moduleFileMap[obj.fromModule]) {
              moduleFileMap[obj.fromModule][fileName] = true;
            } else {
              moduleFileMap[obj.fromModule] = { [fileName]: true };
            }
          }
        });
      });

      for (let key of Object.keys(moduleFileMap)) {
        moduleFileMap[key] = Object.keys(moduleFileMap[key]);
      }
      moduleFileMap.react = ['...'];
    }

    const git = normalizeGitUrl(basic.repo);
    const repo = git.repo;

    return (
      <div className="collect-detail-page">
        <h2>基本信息</h2>
        <Row>
          <Col span={10}>
            {!repo || repo == 'undefined/undefined' ? (
              <p>
                项目名称: <span>{basic.project || '暂无'}</span>
              </p>
            ) : (
              <p>
                仓库地址:{' '}
                <a href={git.url} target="_blank">
                  {repo || '暂无'}
                </a>
              </p>
            )}
          </Col>
          <Col>
            <p>
              业务介绍：<span>{basic.description || '暂无'}</span>
            </p>
          </Col>
        </Row>
        <Row>
          <Col span={10}>
            <p>
              业务页面：<span>{basic.projectUrl || '暂无'}</span>
            </p>
          </Col>
          <Col>
            <p>
              成员:{' '}
              {basic.developers.map((developer, idx) => (
                <a
                  key={idx}
                  style={{ marginRight: 3 }}
                  href={`https://work.alibaba-inc.com/work/search?keywords=${developer}&type=all`}
                >
                  {developer}
                </a>
              ))}
            </p>
          </Col>
        </Row>
        {basic.baseComponent &&
          basic.baseComponentVersion && (
            <Row>
              <Col span={10}>
                <p>
                  基础包:{' '}
                  <a
                    href={`http://web.npm.alibaba-inc.com/package/${
                      basic.baseComponent
                    }/${basic.baseComponentVersion}`}
                  >
                    {basic.baseComponent + '@' + basic.baseComponentVersion}
                  </a>
                </p>
              </Col>
              <Col>
                <p>
                  创建时间:{' '}
                  {moment(basic.createdAt)
                    .locale('zh-cn')
                    .format('YYYY-MM-DD HH:mm:ss')}
                </p>
              </Col>
            </Row>
          )}
        <Row>
          <Col>
            <p>
              更新时间:{' '}
              {moment(basic.updatedAt)
                .locale('zh-cn')
                .format('YYYY-MM-DD HH:mm:ss')}
            </p>
          </Col>
        </Row>
        <hr />
        <section>
          <h2>基础组件</h2>
          <Table dataSource={this.getBasicCompDatasource(moduleFileMap)}>
            <Table.Column title="组件名称" dataIndex="comp" width={200} />
            <Table.Column title="引用次数" dataIndex="times" width={100} />
            <Table.Column
              width="40%"
              title="文件列表"
              dataIndex="files"
              cell={(files) => (
                <ul>
                  {files &&
                    files.map((file, key) => (
                      <li key={key} title={file}>
                        {file}
                      </li>
                    ))}
                </ul>
              )}
            />
          </Table>
        </section>
        <section>
          <h2>业务组件</h2>
          <Table dataSource={this.getBusinessCompDatasource(moduleFileMap)}>
            <Table.Column
              title="组件名称"
              dataIndex="comp"
              cell={(comp) => (
                <a
                  target="_blank"
                  href={`http://web.npm.alibaba-inc.com/package/${comp}`}
                >
                  {comp}
                </a>
              )}
            />
            <Table.Column
              title="依赖类型"
              dataIndex="comp"
              cell={(comp) =>
                (comp in data.pkg.devDependencies && 'Dev 依赖') || '直接依赖'
              }
            />
            <Table.Column title="引用次数" dataIndex="times" />
            <Table.Column
              title="声明版本"
              dataIndex="comp"
              cell={(comp) => (
                <span>
                  {
                    data.modules.reduce(
                      (before, m) => (m.module == comp && m) || before
                    ).pkgVersion
                  }
                </span>
              )}
            />
            <Table.Column
              title="本地版本"
              dataIndex="comp"
              cell={(comp) => (
                <span>
                  {
                    data.modules.reduce(
                      (before, m) => (m.module == comp && m) || before
                    ).version
                  }
                </span>
              )}
            />
            <Table.Column
              width="40%"
              title="文件列表"
              dataIndex="files"
              cell={(files) => (
                <ul>
                  {files &&
                    files.map((file, key) => (
                      <li key={key} title={file}>
                        {file}
                      </li>
                    ))}
                </ul>
              )}
            />
          </Table>
        </section>
        <section>
          <h1>第三方模块</h1>
          <Table dataSource={this.getThirdDatasource(moduleFileMap)}>
            <Table.Column
              title="模块名称"
              dataIndex="comp"
              cell={(comp) => (
                <a
                  target="_blank"
                  href={`http://web.npm.alibaba-inc.com/package/${comp}`}
                >
                  {comp}
                </a>
              )}
            />
            <Table.Column
              title="依赖类型"
              dataIndex="comp"
              cell={(comp) =>
                (comp in data.pkg.devDependencies && 'Dev 依赖') || '直接依赖'
              }
            />
            <Table.Column title="引用次数" dataIndex="times" />
            <Table.Column
              title="声明版本"
              dataIndex="comp"
              cell={(comp) => (
                <span>
                  {
                    data.modules.reduce(
                      (before, m) => (m.module == comp && m) || before
                    ).pkgVersion
                  }
                </span>
              )}
            />
            <Table.Column
              title="本地版本"
              dataIndex="comp"
              cell={(comp) => (
                <span>
                  {
                    data.modules.reduce(
                      (before, m) => (m.module == comp && m) || before
                    ).version
                  }
                </span>
              )}
            />
            <Table.Column
              width="40%"
              title="文件列表"
              dataIndex="files"
              cell={(files) => (
                <ul>
                  {files &&
                    files.map((file, key) => (
                      <li key={key} title={file}>
                        {file}
                      </li>
                    ))}
                </ul>
              )}
            />
          </Table>
        </section>
      </div>
    );
  }
}
