import React from 'react';
import { inject, observer } from 'mobx-react';
import { Icon } from 'antd';
import {
    WeaTools,
    WeaLocaleProvider,
    WeaErrorPage
} from 'ecCom';
import './style/autograph.less';

const getLabel = WeaLocaleProvider.getLabel;
@inject('weaworkflow_autograph_store')
@observer
export default class Autograph extends React.Component {
  static defaultProps = {
    prefixCls: 'wf-autograph',
  }
  constructor(props) {
    super(props);
    this.state = {
      formSignatureWidth: 1034,
      editType: 0, //EditType:默认签章类型，0:签名 1:文字  默认值:0 
      isIE: true,
    }
  }
  
  componentDidMount() {
    const { weaworkflow_autograph_store: {
      getAutographInfo, setMobxState,
    }, params, isMustInput, recordId } = this.props;
    const ua = navigator.userAgent.toLowerCase();
    const isIE = /rv:([\d.]+)\) like gecko/.test(ua);
    this.setState({ isIE });
    this.handleResize();
    setMobxState({ isMustInput, recordId });
    jQuery(Consult2).parent().append('<object width="1645" height="200" id="Consult" classid="clsid:2294689C-9EDF-40BC-86AE-0438112CA439" codebase="/workflow/request/iWebRevision.cab#version=6,7,0,403"></object>')
    isIE && getAutographInfo(params).then(() => {
      this.initAutograph();
    });
    window.addEventListener('resize', this.handleResize);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize);
  }

  handleResize = () => {
    const { formSignatureWidth } = this.state;
    const dom = document.getElementById('consultdiv');
    const width = dom.clientWidth || dom.scrollWidth;
    if (width !== formSignatureWidth) {
      this.setState({ formSignatureWidth: width });
    }
  }

  initAutograph() {
    const { formSignatureWidth } = this.state;
    const {weaworkflow_autograph_store} = this.props;
    const { initInfo, setMobxState } = weaworkflow_autograph_store;
    Consult.WebUrl = '/workflow/request/RevisionServer.jsp'; //WebUrl:系统服务器路径，与服务器交互操作，如打开签章信息
    // Consult.WebUrl = initInfo.WebUrl; //WebUrl:系统服务器路径，与服务器交互操作，如打开签章信息
    Consult.RecordID = initInfo.RecordID || '-1'; //RecordID:本文档记录编号
    Consult.FieldName ="Consult"; //FieldName:签章窗体可以根据实际情况再增加，只需要修改控件属性 FieldName 的值就可以
    Consult.UserName = initInfo.UserName; //UserName:签名用户名称
    Consult.WebSetMsgByName("USERID", initInfo.UserId);          //USERID:签名用户id
    Consult.Enabled = initInfo.Consult_Enabled; //Enabled:是否允许修改，0:不允许 1:允许  默认值:1 
    Consult.PenColor = initInfo.PenColor; //PenColor:笔的颜色，采用网页色彩值  默认值:#000000 
    Consult.BorderStyle = "0"; //BorderStyle:边框，0:无边框 1:有边框  默认值:1 
    Consult.EditType = initInfo.EditType; //EditType:默认签章类型，0:签名 1:文字  默认值:0 
    Consult.ShowPage = initInfo.ShowPage; //ShowPage:设置默认显示页面，0:电子印章,1:网页签批,2:文字批注  默认值:0 
    Consult.InputText = ""; //InputText:设置署名信息，  为空字符串则默认信息[用户名+时间]内容 
    Consult.PenWidth = initInfo.PenWidth; //PenWidth:笔的宽度，值:1 2 3 4 5   默认值:2 
    Consult.FontSize = initInfo.FontSize; //FontSize:文字大小，默认值:11
    Consult.ShowMenu = "0";
    Consult.SignatureType = initInfo.SignatureType; //SignatureType:签章来源类型，0表示从服务器数据库中读取签章，1表示从硬件密钥盘中读取签章，2表示从本地读取签章，并与ImageName(本地签章路径)属性相结合使用  默认值:0}
    Consult.InputList = initInfo.InputList; //InputList:设置文字批注信息列表 
    Consult.ShowUserListMenu = "true";			//签批用户列表是否显示，"true"为显示
    Consult.FontName=initInfo.FontName; // 设置字体名称
    Consult.CASignType = initInfo.CASignType; //默认为不启用数字签名
    Consult.SetFieldByName("DocEmptyJuggle", initInfo.DocEmptyJuggle);
    Consult.LoadSignature(); //调用签章数据信息
    Consult.ImgWidth=formSignatureWidth;
    Consult.ImgHeight = initInfo.formSignatureHeight;
    // this.setState({ isAutoResizeSignImage: initInfo.isAutoResizeSignImage });
    setMobxState({ isAutoResizeSignImage: initInfo.isAutoResizeSignImage });
  }   

  // saveAutograph = (src) => {
  //   const { isMustInput } = this.props;
  //   if (isMustInput === '1' || (isMustInput === '2' && "reject" === src)) {
  //     if(Consult.DocEmpty && Consult.OpinionText == "") {
  //       isDocEmpty = 1;
  //       return false;
  //     }
  //   }
  //   //TODO save
  //   let record = '';
  //    let timestamp = Date.parse(new Date());
  //   timestamp = timestamp / 1000;
  //   if (Consult.Modify) {
  //     let saveFlag = this.state.isAutoResizeSignImage ? Consult.SaveAsGifEx(timestamp+".gif","All","Remote") : Consult.SaveSignature();
  //     if (!saveFlag) {
  //       return false;
  //     } 
  //     record = Consult.WebGetMsgByName("RECORDID");
  //     if (parseInt(record) > 0 && isAutoResizeSignImage) {
  //       Consult.WebSetMsgByName("TEMPCALL","1");
  //       Consult.WebSetMsgByName("TEMPID",record);
  //       saveFlag = Consult.SaveSignature();
  //     }
  //   } else {
  //     return this.props.recordId;
  //   }
  //   return record;
  // } 

  getHash = (prefixCls) => prefixCls + Math.random().toString(36).substr(2, 6);

  openSignature = () => this.state.isIE && Consult.OpenSignature();

  changeEditType = () => this.state.isIE && this.setState({ editType: Consult.EditType === 0 ? 1 : 0, }, () => { Consult.EditType = this.state.editType; });

  showSignature = () => this.state.isIE && Consult.ShowSignature();

  clear = () => this.state.isIE && Consult.Clear();

  clearAll = () => this.state.isIE && Consult.ClearAll();
  
  chgReadSignatureType = () => {
    if (this.state.isIE) {
      const res = Consult.SignatureType === 1 ? 0 : 1;
      if (this.state.isIE) {
        Consult.SignatureType = res;
        if (res === 0) alert('签章从数据库中读取');
        else alert('签章从智能钥匙盘中读取');
      }  
    }
  }

  showZoomInHandWrite = () => this.state.isIE && Consult.ShowZoomInHandWrite();

  getToolTabs = () => {
    const { editType } = this.state;
    const { prefixCls, weaworkflow_autograph_store: { visible, isMustInput, setMobxState } } = this.props;
    return visible ? (
      <tr className={`${prefixCls}-tooltab-tr`}>
        <td className={`${prefixCls}-tooltab-td ${prefixCls}-tooltab-tdSign`}>
          <span className={`${prefixCls}-tooltab-img icon-coms-Need-feedback`} />
          <a className={`${prefixCls}-tooltab-label`}>签字意见</a>
          { isMustInput && (<span className={`${prefixCls}-tooltab-label-required`}>（必填）</span>)}
        </td>              
        <td className={`${prefixCls}-tooltab-td`}>
          <span className={`icon-coms02-form-Sign ${prefixCls}-tooltab-img`} onClick={this.openSignature}>
            <span className="path1" />
            <span className="path2" />
          </span>
          <a className={`${prefixCls}-tooltab-label`} onClick={this.openSignature}>
            {getLabel('21431', '打开签章 ')}
          </a>
        </td>
        <td className={`${prefixCls}-tooltab-td`}>
          <span className={`${editType === 0 ? 'icon-coms02-form-to-write' : 'icon-coms02-from-Text'} ${prefixCls}-tooltab-img`} onClick={this.changeEditType}>
            <span className="path1" />
            <span className="path2" />
          </span>
          <a className={`${prefixCls}-tooltab-label`} onClick={this.changeEditType}>
            { editType === 0 ? getLabel('25349', '手写签批 ') : getLabel('21441', '文字签批 ') }
          </a>
        </td>
        <td className={`${prefixCls}-tooltab-td`}>
          <span className={`icon-coms02-from-SignList ${prefixCls}-tooltab-img`} onClick={this.showSignature} >
            <span className="path1" />
            <span className="path2" />
            <span className="path3" />
            <span className="path4" />
            <span className="path5" />
            <span className="path6" />
          </span>
          <a className={`${prefixCls}-tooltab-label`} onClick={this.showSignature}>
            {getLabel('21432', '签章列表 ')}
          </a>
        </td>
        <td className={`${prefixCls}-tooltab-td`}>
          <span className={`icon-coms02-from-cancel ${prefixCls}-tooltab-img`} onClick={this.clear}>
            <span className="path1" />
            <span className="path2" />
          </span>
          <a className={`${prefixCls}-tooltab-label`} onClick={this.clear}>
            {getLabel('21433', '取消修改 ')}
          </a>
        </td>
        <td className={`${prefixCls}-tooltab-td`}>
          <span className={`icon-coms02-from-Empty ${prefixCls}-tooltab-img`} onClick={this.clearAll}>
            <span className="path1" />
            <span className="path2" />
          </span>
          <a className={`${prefixCls}-tooltab-label`} onClick={this.clearAll}>
            {getLabel('21434', '清空全部 ')}
          </a>
        </td>
        <td className={`${prefixCls}-tooltab-td`}>
          <span className={`icon-coms02-from-Switching ${prefixCls}-tooltab-img`} onClick={this.chgReadSignatureType} >
            <span className="path1" />
            <span className="path2" />
            <span className="path3" />
            <span className="path4" />
            <span className="path5" />
            <span className="path6" />
          </span>
          <a className={`${prefixCls}-tooltab-label`} onClick={this.chgReadSignatureType}>
            {getLabel('21435', '切换签章来源 ')}
          </a>
        </td>
        <td className={`${prefixCls}-tooltab-td`}>
          <span className={`icon-coms02-from-Switching ${prefixCls}-tooltab-img`} onClick={this.showZoomInHandWrite} >
            <span className="path1" />
            <span className="path2" />
            <span className="path3" />
            <span className="path4" />
            <span className="path5" />
            <span className="path6" />
          </span>
          <a className={`${prefixCls}-tooltab-label`} onClick={this.showZoomInHandWrite}>
            {getLabel('131881', ' 全屏手写')}
          </a>
        </td>
      </tr>
    ): (
        <tr className={`${prefixCls}-tooltab-tr`} onClick={() => setMobxState({ visible: true })}>
        <td className={`${prefixCls}-tooltab-td ${prefixCls}-tooltab-tdSign`}>
          <span className={`${prefixCls}-tooltab-img icon-coms-Need-feedback`} />
          <a className={`${prefixCls}-tooltab-label`}>签字意见</a>
          {isMustInput && (<span className={`${prefixCls}-tooltab-label-required`}>（必填）</span>)}
        </td>
      </tr>
    )
  }

  render() {
    const { formSignatureWidth, isIE } = this.state;
    const { weaworkflow_autograph_store, prefixCls, bottomBarConfig } = this.props;
    const { initInfo: { formSignatureHeight = 200, revisionClassId, revisionClientUrl }, visible } = weaworkflow_autograph_store;
    return (
      <div id="consultdiv" className={prefixCls}>
        <table className={`${prefixCls}-tooltab`} cellspacing="0" cellpadding="0" align="center">
          <tbody>{this.getToolTabs()}</tbody>
        </table>
        {
          visible ? isIE ? (
            <div className={`${prefixCls}-consulttab`} style={{ height: formSignatureHeight }}>
              <table id="consulttab" width={formSignatureWidth + 'px'} height={formSignatureHeight + 'px'} cellspacing="0" cellpadding="0" align="left">
                <tbody >
                  <tr>
                    <td id="formSignatureTd" className={`${prefixCls}-consulttab-formSignatureTd`}>
                      <object
                        id="Consult2"
                        width={formSignatureWidth}
                        height={formSignatureHeight}
                        classid={revisionClassId}
                        codebase={revisionClientUrl}
                        // classid='clsid:2294689C-9EDF-40BC-86AE-0438112CA439'
                        // codebase='/iWebRevision.cab#version=6.7.0.403'
                        ></object>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            ) : (
              <div className={`${prefixCls}-noData`}>
                <div className={`${prefixCls}-noData-icon`}>!</div>
                <div className={`${prefixCls}-noData-desc`}>
                  <div>您当前使用的浏览器不支持【表单签章】，</div>
                  <div>如需使用该功能，请使用IE浏览器！</div>
                </div>
              </div>
            ) : null
        }
        {
          visible && bottomBarConfig && (
            <div className={`${prefixCls}-bottomBarConfig`}>
              { bottomBarConfig.map(config => (<div key={this.getHash('wfConsult')} className={`${prefixCls}-bottomBarConfig-single`}>{config}</div>)) }
            </div>            
          )
        }
      </div>
    );
  }
}