/**
 * imui.Message
 * @author coverguo
 */
import React from 'react';
import Message from './lib/Message';
import Icon from '../icon/index';
// @require './style/index.scss'

// message常用的接口类型
const commonApiList = ['info', 'success', 'question', 'alert'];


// 全局默认样式
let defaultOpts = {
  duration: 2, // 默认每个tip展示2s,
  direction: 'top', // 默认消息展示的位置
  zIndex: 4000, // 默认消息的zindex的等级
};

let MessageList; // 目前是单例模式，故只有一个MessageList
let key = 1; // messageItem的key值

// 获取icon类型
const defaultIcons = {
  info: 'info',
  success: 'success',
  alert: 'alert',
  question: 'question',
  loading: 'loading'
};

// 获取MessageList
function getMessageList() {
  MessageList = MessageList || Message.init();
  return MessageList;
}

function message(opts, type) {
  // 判断是否有参数
  if (!opts) {
    throw Error('need params');
  }

  // 获取当前messageList
  let curMessageList = getMessageList();

  // 单只传了一个字符串参数时, 使用默认布局
  if (typeof opts.content === 'string') {
    opts.content = (
      <div className="im-message-item-default">
        {type === 'loading' ?
          <div className="icon-loading"></div> :
          <Icon type={defaultIcons[type]} />}
        <span>{opts.content}</span>
      </div>
    );
  }

  // 合并属性
  opts = Object.assign({
    key // 表示messageItem的key
  }, defaultOpts, opts);

  // 调用message的add方法
  curMessageList.add(opts);

  let target = key++;
  // 返回对象,
  // TODO 之后可以增加多点接口
  return {
    close: () => {
      curMessageList.remove(target);
    }
  };
}


// 最终对外提供的api
const MessageApi = {
  /**
   * 【全局方法】设置message全局配置
   */
  config(opts = {}) {
    defaultOpts = Object.assign(defaultOpts, opts);
    // console.log(defaultOpts);
  },

  /**
   * 【全局方法】销毁所有message
   */
  destroy() {
    if (MessageList) {
      MessageList.destroy();
      MessageList = null;
    }
  },

  /**
   * 【常用方法】loading，
   *  由于loading有点特殊故单独抽开
   */
  loading(opts) {
    if (typeof opts === 'string') {
      opts = {
        content: opts
      };
    }
    // loading的时延强制为0
    opts.duration = 0;
    return message(opts, 'loading');
  }
};

// 设置常用的方法 info|error|question|success
commonApiList.forEach((methodName) => {
  // 排除loading
  MessageApi[methodName] = (opts) => {
    if (typeof opts === 'string') {
      opts = {
        content: opts
      };
    }
    return message(opts, methodName);
  };
});


export default MessageApi;
