import React from 'react';
import { Modal, Spin } from 'antd';
import {
  WeaLocaleProvider,
  WeaBrowser,
  WeaTools,
} from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

const shareTypeMap = {
  152: 'workflow',
  37: 'doc',
  18: 'crm',
  workplan: 'workplan',
  28: 'meeting',
};
const addShareMap = {
  workplan: 2,
};

const browserIconMap = {
  28: 'icon-coms-meeting',
  workplan: 'icon-coms-schedule',
};

const onCloseHandle = () => {
  if (window.em) {
    em.closeWindow();
  } else {
    Modal.error({
      transitionName: 'none',
      title: getLabel(125960, '初始化失败'),
      content: getLabel(520050, 'em对象不存在'),
    });
  }
};

export default class Home extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      visible: false,
      errorMsg: '',
      loading: false,
    };
    window.setLayoutWindow = window;
    this.interval = '';
    this.defaultMD = null;
    this.initEm = this.initEm.bind(this);
  }

  getFrameParams() {
    let url = window.location.href;
    try {
      if (window.frameElement) {
        url = window.frameElement.src;
      }
    } catch (error) {

    }
    let urlParams = url.slice(url.indexOf('?') + 1).split('&');
    let params = [];
    urlParams.forEach((element) => {
      let datas = element.split('=');
      params[datas[0]] = datas[1];
    });
    let host = url.slice(0, url.indexOf('/spa/'));
    params.host = host;
    return params;
  }

  componentDidMount() {
    this.setState({ visible: true });

    // if (window.em) {
    this.initEm();
    // } else {
    //   setTimeout(() => {
    //     this.initEm()
    //   } ,500)
    // }
  }

  initEm() {
    if (window.em) {
      em.ready(() => {
        em.setPageReload({
          setvalue: 2, // 1表示每次都需要重新加载页面（默认） 2表示保持页面无需重新加载，
          success(res) {
          },
        });
        em.pageVisible((visible) => {
          if (visible) {
            this.defaultMD.reload();
          }
        });

        if (this.defaultMD && this.defaultMD.browser && this.defaultMD.openModal) {
          this.defaultMD.openModal();
        } else {
          let interval = setInterval(() => {
            if (this.defaultMD && this.defaultMD.browser && this.defaultMD.openModal) {
              this.defaultMD.openModal();
              clearInterval(interval);
            }
          }, 200);
        }
      });
    } else {
      setTimeout(() => {
        this.initEm();
      }, 500);
    }
  }

  componentWillUnmount() {
    this.interval && clearInterval(this.interval);
  }

  onChangeHandle(ids, names, datas) {
    const params = this.getFrameParams();
    if (!params.type) {
      const modal = Modal.error({
        transitionName: 'none',
        title: getLabel(129174, '分享失败'),
        content: getLabel(520051, '获取资源类型失败'),
        onOk() { onCloseHandle(); },
        onCancel() { onCloseHandle(); },
      });
      em.setPageReload({
        setvalue: 1, // 1表示每次都需要重新加载页面（默认） 2表示保持页面无需重新加载，
        success: (res) => {
          setTimeout(() => {
            modal.destroy();
            this.defaultMD && this.defaultMD.openModal();
          }, 3000);
        },
      });
      return false;
    }
    this.setState({ loading: true });
    if (window.em) {
      em.getUserFromConversation({
        targetId: '', // 消息会话ID
        success: (res) => {
          // 以数组形式返回
          // 如：{"userIdList":["123","456"]"},"errMsg":"getUserListFromConversation:ok"}
          if (!res.userIdList || res.userIdList.length === 0) {
            const modal = Modal.warning({
              transitionName: 'none',
              title: getLabel(24960, '提示信息'),
              content: getLabel(520052, '获取会话用户失败'),
              onOk() { onCloseHandle(); },
              onCancel() { onCloseHandle(); },
            });
            em.setPageReload({
              setvalue: 1, // 1表示每次都需要重新加载页面（默认） 2表示保持页面无需重新加载，
              success: (res) => {
                setTimeout(() => {
                  modal.destroy();
                  this.defaultMD && this.defaultMD.openModal();
                }, 3000);
              },
            });
            return;
          }
          let userIdList = res.userIdList.join(',');
          let shareList = [];
          let successCount = 0;
          let failedCount = 0;
          let errorMsg = '';
          const rs = () => {
            if (successCount + failedCount < datas.length) {
              return;
            }
            if (failedCount === 0) {
              onCloseHandle();
              this.defaultMD && this.defaultMD.openModal();
            } else {
              const modal = Modal.warning({
                transitionName: 'none',
                title: getLabel(24960, '提示信息'),
                content: getLabel(520053, '共${1}条，失败${2}条').replace('${1}', datas.length).replace('${2}', datas.length - successCount) + errorMsg,
                onOk() { onCloseHandle(); },
                onCancel() { onCloseHandle(); },
              });
              em.setPageReload({
                setvalue: 1, // 1表示每次都需要重新加载页面（默认） 2表示保持页面无需重新加载，
                success: (res) => {
                  setTimeout(() => {
                    modal.destroy();
                    this.defaultMD && this.defaultMD.openModal();
                  }, 3000);
                },
              });
            }
          };
          const rj = () => {
            const modal = Modal.warning({
              transitionName: 'none',
              title: getLabel(24960, '提示信息'),
              content: getLabel(520053, '共${1}条，失败${2}条').replace('${1}', datas.length).replace('${2}', datas.length - successCount) + errorMsg,
              onOk() { onCloseHandle(); },
              onCancel() { onCloseHandle(); },
            });
            em.setPageReload({
              setvalue: 1, // 1表示每次都需要重新加载页面（默认） 2表示保持页面无需重新加载，
              success: (res) => {
                setTimeout(() => {
                  modal.destroy();
                  this.defaultMD && this.defaultMD.openModal();
                }, 3000);
              },
            });
          };
          datas.forEach((element) => {
            // let promise = new Promise(function(rs, rj){
            let shareParams = {
              resourcetype: addShareMap[params.type] || params.type,
              resourceid: element.id,
              resourceids: userIdList,
            };
            try {
              WeaTools.callApi('/api/common/chatResource/addshare', 'POST', shareParams).then((res) => {
                if (Object.keys(res).length === 0) {
                  rj();
                  return;
                }
                if (res.success !== true) {
                  rj();
                  return;
                }
                em.sendMsg({
                  targetId: '', // 消息会话ID
                  msgType: 10, // 消息类型：1-文本 2-链接 10-E6分享消息
                  msgInfo: {
                    content: element.name, // 分享标题（必填）
                    sharetype: shareTypeMap[params.type], // 分享数据类型,值有"doc","workflow","task","pdoc","folder" ,"crm" 分别代表文档，流程，任务，云盘文档，云盘文件，客户名片
                    sharetypename: params.sharetypename ? decodeURI(params.sharetypename) : '',
                    shareid: element.id, // 分享的数据ID（必填）
                    opentype_pc: 2, // PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
                    linkurl: res.linkUrl, // 消息链接地址（必填）
                    callbackurl: res.callbackurl,
                    canforward: res.canforward,
                  },
                  success: (res) => {
                    successCount++;
                    rs();
                  },
                  fail: (res) => {
                    failedCount++;
                    errorMsg = `${errorMsg + res.errMsg} `;
                    rs();
                  },
                });
              }, (res) => {
                const modal = Modal.error({
                  transitionName: 'none',
                  title: getLabel(129174, '分享失败'),
                  content: getLabel(502350, '数据异常 ') + res,
                  onOk() { onCloseHandle(); },
                  onCancel() { onCloseHandle(); },
                });
                em.setPageReload({
                  setvalue: 1, // 1表示每次都需要重新加载页面（默认） 2表示保持页面无需重新加载，
                  success: (res) => {
                    setTimeout(() => {
                      modal.destroy();
                      this.defaultMD && this.defaultMD.openModal();
                    }, 3000);
                  },
                });
              });
            } catch (error) {
              const modal = Modal.error({
                transitionName: 'none',
                title: getLabel(129174, '分享失败'),
                content: getLabel(520054, '分享接口请求失败 ') + error,
              });
              em.setPageReload({
                setvalue: 1, // 1表示每次都需要重新加载页面（默认） 2表示保持页面无需重新加载，
                success: (res) => {
                  setTimeout(() => {
                    modal.destroy();
                    this.defaultMD && this.defaultMD.openModal();
                  }, 3000);
                },
              });
            }
            // })
            // shareList.push(promise);
          });
          // Promise.all(shareList).then(() => {
          // }).catch(() => {
          // })
        },
        fail: (res) => {
          const modal = Modal.error({
            transitionName: 'none',
            title: getLabel(129174, '分享失败'),
            content: getLabel(520052, '获取会话用户失败') + res.errMsg,
            onOk() { onCloseHandle(); },
            onCancel() { onCloseHandle(); },
          });
          em.setPageReload({
            setvalue: 1, // 1表示每次都需要重新加载页面（默认） 2表示保持页面无需重新加载，
            success: (res) => {
              setTimeout(() => {
                modal.destroy();
                this.defaultMD && this.defaultMD.openModal();
              }, 3000);
            },
          });
        },
      });
    }
  }


  render() {
    const params = this.getFrameParams();
    if (params.type && params.type != 'url') {
      window.setDialogFullWindow = true;
    }
    let isSingle = false;
    if (params.isSingle && params.isSingle == 'true') {
      isSingle = true;
    }
    const browserTitleMap = {
      152: getLabel(30045, '流程'),
      37: getLabel(22243, '文档'),
      18: getLabel(136, '客户'),
      28: getLabel(2103, '会议'),
      workplan: getLabel(83466, '日程'),
    };
    return (
      <WeaLocaleProvider>
        <div className="wea-emobile-entrance">
          <Spin spinning={this.state.loading} tip={getLabel(520055, '分享中……')}>
            <div style={{ minHeight: '500px' }} />
          </Spin>
          {params.type && <WeaBrowser
            customized
            type={params.type}
            title={browserTitleMap[params.type] || getLabel(695, '浏览按钮')}
            icon={browserIconMap[params.type] || 'icon-toolbar-Organization-list'}
            iconBgcolor="#b32e37"
            inputStyle={{ width: 200 }}
            onChange={(ids, names, datas) => this.onChangeHandle(ids, names, datas)}
            onCancel={() => { onCloseHandle(); this.defaultMD.openModal(); }}
            isSingle={isSingle}
            // ref='defaultMD'
            ref={el => (this.defaultMD = el)}
            hasAdvanceSerach
            dataParams={{ isFormEMShare: 1 }}
            conditionDataParams={{ isFormEMShare: 1 }}
            browserModalProps={
              {
                transitionName: 'none',
                draggable: false,
                visibleOnClose: true,
                hideClear: true,
              }
            }
          />}
        </div>
      </WeaLocaleProvider>
    );
  }
}

