import { Button, Modal,message,Row,Col, Spin} from 'antd';
import { WeaErrorPage, WeaPopoverHrm, WeaTools,WeaSearchBrowserBox,WeaTableEdit, WeaDialog,WeaSearchGroup, WeaRightMenu,WeaFormItem , WeaQrcode} from 'ecCom'
import isEmpty from 'lodash/isEmpty'
import debounce from 'lodash/debounce'
import isArray from 'lodash/isArray'
import '../../style/cardInfo.less';
import { InfoGroup4Formal1,InfoGroup4Formal2} from '../../coms/infoGroup4Formal';
import * as PublicFunc from '../../util/pulic-func';
import  {createQRCode} from '../../util';
import UploadAvatar from '../../../../pc4public/hrm/uploadAvatar'
import TopButton from '../../coms/topButton';
import {WeaSwitch} from 'comsMobx';
import * as mobx from 'mobx';
import { inject, observer} from 'mobx-react';
import {i18n} from '../../public/i18n';
import {addContentPath} from '../../util/index.js'
const getKey = WeaTools.getKey;
const toJS = mobx.toJS;

@inject('hrmCardInfo4Formal')
@inject('hrmCard')
@observer
class Main extends React.Component {
  constructor(props) {
    super(props);
    const funcs = ['onRightMenuClick', 'showSQR','editCard','backCard','saveEditCard'];
    funcs.forEach(f=> this[f] = this[f].bind(this));
  }
  componentWillReceiveProps(nextProps) {
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    if(keyOld !== keyNew) {
      const {hrmCardInfo4Formal} = this.props;
      hrmCardInfo4Formal.updateIsEditor();
    }
  }
  componentDidMount(){
    const {hrmCardInfo4Formal} = this.props;
    const hrmId = this.props.params.hrmId ||'';
    hrmCardInfo4Formal.updateIsEditor();
    hrmCardInfo4Formal.getData(hrmId);
    hrmCardInfo4Formal.getRightMenu(hrmId);
  }
  showSQR(bool,e){
    const {hrmCardInfo4Formal} = this.props;
    e.stopPropagation && e.stopPropagation();
    e.preventDefault && e.preventDefault();
    e.nativeEvent && e.nativeEvent.preventDefault();
    hrmCardInfo4Formal.updateShowSQR(bool);
  }
  getIcon(str) {
    switch(str){
      case 'sendEmessage':
          return 'icon-coms-Send-message';
      case 'openmessage':
          return 'icon-coms-message-o';
      case 'openemail':
          return 'icon-coms-Send-emails';
      case 'doAddWorkPlan':
          return 'icon-coms-New-schedule-o';
    }
  }
  getRightMenu() {
    const {
      hrmCardInfo4Formal, hrmCard
    } = this.props;
    let {
      isEditor,
      buttons,
      rightMenus
    } = hrmCardInfo4Formal;
    buttons = toJS(buttons);
    rightMenus = toJS(rightMenus);
    let arr = [];
    if (isEditor) {
      arr = [{
        icon: <i className='icon-coms-common'/>,
        content: i18n.button.save(),
        key: 'save',
        onClick: key =>{
          this.saveEditCard();
        }
      }, {
        icon: <i className='icon-coms-go-back'/>,
        content: i18n.button.back(),
        key: 'back',
        onClick: key =>{
          this.backCard();
        }
      }]
    } else {
      !isEmpty(rightMenus) && rightMenus.forEach((c) => {
        let item = {
          icon: <i className={`${c.menuIcon}`}/>,
          content: c.menuName,
          key: c.menuFun,
          onClick: key =>{
            const menuFun = c.menuFun;
            if(menuFun === 'showPortraitSetting')
              hrmCard[menuFun] && hrmCard[menuFun]();
            this[menuFun] && this[menuFun](c.params);
          }
        }
        arr.push(item);
      })
    }
    return arr;
  }
  
  onRightMenuClick(key){
    const {hrmCardInfo4Formal} = this.props;
    let {isEditor, rightMenus} = hrmCardInfo4Formal;
    rightMenus = toJS(rightMenus);
    if (isEditor) {
      switch(key){
        case '0':
            this.saveEditCard();
            break;
        case '1':
            this.backCard();
            break;
      }
    } else {
      const menuFun = rightMenus[key].menuFun;
      this[menuFun] && this[menuFun]();
    }
  }
  
  showLog(params){
    window.setLogViewProps(params);
  }

  sendEmessage = () =>{
     const {params} = this.props;
    let id = params.hrmId;
    if (id) PublicFunc.sendEmessage(id);
  }
  
  sendSmsMessage(){
    const {params} = this.props;
    let id = params.hrmId;
    if (id) PublicFunc.sendSmsMessage(id);
  }

  sendMail(){
    const {params} = this.props;
    let id = params.hrmId;
    if (id) PublicFunc.sendMail(id);
  }

  doAddWorkPlanByHrm(){
    const {params} = this.props;
    let id = params.hrmId;
    if (id) PublicFunc.doAddWorkPlanByHrm(id);
  }

  addCoWork(){
    const {params} = this.props;
    let id = params.hrmId;
    if (id) PublicFunc.addCoWork(id);
  }
  getTopButtons() {
    const {hrmCardInfo4Formal} = this.props;
    let {isEditor, buttons} = hrmCardInfo4Formal;
    buttons = toJS(buttons);
    const save = <Button type="primary" onClick={this.saveEditCard} >{i18n.button.save()}</Button>;
    const back = <Button type="primary" onClick={this.backCard} >{i18n.button.back()}</Button>;
    const edit = <Button type="primary" onClick={this.editCard} >{i18n.button.modify()}</Button>;
    const btns = [];
    if (isEditor) {
      if (buttons.hasSave) {
        btns.push(save);
        btns.push(back);
      }
    } else {
      if (buttons.hasEdit) {
        btns.push(edit);
      }
    }
    return btns;
  }
  editCard(){
    const hrmId = this.props.params.hrmId ||'';
    const {hrmCardInfo4Formal} = this.props;
    hrmCardInfo4Formal.edit(hrmId);
  }

  saveEditCard(){
    const hrmId = this.props.params.hrmId ||'';
    const {hrmCardInfo4Formal,hrmCard} = this.props;
    hrmCardInfo4Formal.saveEditCard(()=>{
      hrmCard.getTabBaseInfo({id:hrmId});
    });
  }

  backCard(){
    const hrmId = this.props.params.hrmId ||'';
    const {hrmCardInfo4Formal} = this.props;
    hrmCardInfo4Formal.updateIsEditor();
    hrmCardInfo4Formal.qrcode(hrmId);
    hrmCardInfo4Formal.updateShowSQR(false);
  }
  getSearchs(){
    const {hrmCardInfo4Formal} = this.props;
    let {conditioninfo,hideBelongto,isEditor,form} = hrmCardInfo4Formal;
    let group = [];
    const {isFormInit} = form;
    let idx = 0;
    window.e9HideFormFieldKeys = [];
    isFormInit && conditioninfo.forEach(c =>{
      let items = [];
      idx++;
      if(c.hasResourceImage){
        let resourceimg;
        let baseGroup = <div>
                    <WeaSearchGroup className={`${isEditor?'hrm-base-group-title':''}`} hide={c.hide} needTigger={true} title={c.title} showGroup={c.defaultshow}>
                      <Row>
                        <Col span={12}>
                          {
                            c.items.forEach( field => {
                              let dom = <WeaSwitch fieldConfig={field} form={form} onChange={(v)=> {
                                  if (v.accounttype) {
                                    hrmCardInfo4Formal.updateHideBelongto(v.accounttype.value == '0');
                                  }
                                }}/>
                              if (field.conditionType == 'RESOURCEIMG' || (field.domkey && field.domkey[0] == 'belongto' && hideBelongto)) {
                              } else {
                                if(c.hide || !isEmpty(field.otherParams) && field.otherParams.hide){
                                  window.e9HideFormFieldKeys.push(field.domkey[0]);
                                }else{
                                  items.push({
                                    com:(<div style={{paddingLeft: 30}}><WeaFormItem
                                      label={`${field.label}`}
                                      labelCol={{span: `${window.HrmLabelCol}`}}
                                      wrapperCol={{span: `${window.HrmWrapperCol}`}}>
                                        {dom}
                                      </WeaFormItem></div>),
                                    colSpan: 1
                                  });
                                }
                              }
                            })
                          }
                          <WeaSearchGroup className={`${isEditor?'hrm-base-group':''}`} needTigger={true} hide={c.hide} title={c.title} showGroup={c.defaultshow} items={items} col={1}/>
                        </Col>
                        <Col span={12}>
                          {
                            c.items.forEach( field => {
                              if (field.conditionType == 'RESOURCEIMG') {
                                const key = getKey(field);
                                const bindObj = form.$(key);
                                resourceimg = <WeaFormItem
                                label={`${field.label}`}
                                labelCol={{span: `${window.HrmLabelCol}`}}
                                wrapperCol={{span: `${window.HrmWrapperCol}`}}>
                                  <UploadAvatar {...bindObj.bind()}/>
                                </WeaFormItem>
                              } 
                            })
                          }
                          {resourceimg}
                        </Col>
                      </Row>
                    </WeaSearchGroup>
                  </div>
        group.push(baseGroup);
      }else{
        c.items.forEach( field => {
          if(c.hide || !isEmpty(field.otherParams) && field.otherParams.hide){
            window.e9HideFormFieldKeys.push(field.domkey[0]);
          }else{
            let dom = <WeaSwitch fieldConfig={field} form={form} onChange={(v)=> {
              if (v.accounttype) {
                hrmCardInfo4Formal.updateHideBelongto(v.accounttype.value == '0');
              }
            }}/>
            if (field.conditionType == 'RESOURCEIMG' || (field.domkey && field.domkey[0] == 'belongto' && hideBelongto)) {
            } else {
              items.push({
                com:(<WeaFormItem
                  label={`${field.label}`}
                  labelCol={{span: `${window.HrmLabelCol}`}}
                  wrapperCol={{span: `${window.HrmWrapperCol}`}}>
                    {dom}
                  </WeaFormItem>),
                colSpan: 1
              });
            }
          }
        });
        group.push(<WeaSearchGroup className={`${isEditor?'hrm-center':''} ${c.isHide?'wea-hide':''}`} needTigger={true} hide={c.hide} title={c.title} showGroup={c.defaultshow} items={items} col={window.HrmGroupCol}/>)
      }
    });
    return group
  }
  render() {
    const {hrmCardInfo4Formal} = this.props;
    let {isEditor, infoGroup,infoGroup2,imgSrc,modelItems,showSQR,
      showBigImg,sendButtons,accountInfo,showAccountInfo,hasQRCode,QRCodeOptions} = hrmCardInfo4Formal;
    sendButtons = toJS(sendButtons);
    infoGroup = toJS(infoGroup);
    infoGroup2 = toJS(infoGroup2);
    modelItems = toJS(modelItems);
    const getPortrait =()=>{
      const loadingImg = '/images/messageimages/temp/loading_wev8.gif';
      const hasNoImg = ['/images/messageimages/temp/man_wev8.png', '/images/messageimages/temp/women_wev8.png', ''].indexOf(imgSrc || '') > -1;
      return (
        <div className='hrm-my-card-basicInfo-left-imgwrap'>
          <div className={`hrm-my-card-basicInfo-left-img${hasNoImg ? '' : '-value'}`}
           onClick={debounce(this.showSQR.bind(null,true),150)}/>
          {!showBigImg &&
            <img className='hrm-my-card-basicInfo-left-img'
              src={addContentPath(imgSrc ? imgSrc : loadingImg)}
              onError={()=> {this.setState({imgSrc: addContentPath('/images/messageimages/temp/man_wev8.png')})}}
              onClick={()=>imgSrc && hrmCardInfo4Formal.updateShowBigImg(true)}
            />
          }
          {showBigImg &&
            <img className='hrm-my-card-basicInfo-left-img-big'
              onError={()=> {this.setState({imgSrc: addContentPath('/images/messageimages/temp/man_wev8.png')})}}
              onClick={()=>imgSrc && hrmCardInfo4Formal.updateShowBigImg(false)}
             src={`${window.ecologyContentPath || ''}${imgSrc ? imgSrc : loadingImg}`}
            />
          }
          <div className='hrm-my-card-basicInfo-left-img-sqrimg' style={{position:'absolute',top:4,right:5}}
             onClick={debounce(this.showSQR.bind(null,true),150)}>
            <i className='icon-coms-Scan' style={{color:'#fff'}}/>
          </div>
          <div className='hrm-my-card-basicInfo-sqr' style={{display: showSQR ? 'block' : 'none'}}
             onClick={this.showSQR.bind(null,false)}>
             {
                hasQRCode && !isEmpty(QRCodeOptions) &&<WeaQrcode
                  text={createQRCode(QRCodeOptions)}
                  size={120}
                  level={'L'}
                />
             }
          </div>
        </div>
      )
    }
    const getPortraitButtons=()=>{
      const colArr = [];
      isArray(sendButtons) && sendButtons.forEach((item) => {
        colArr.push(
          <Col span={6}>
            <div className='hrm-my-card-basicInfo-icon-circle'
              onClick={()=> {
                PublicFunc[item.funname](item.id);
              }}
              title={item.title}
            >
              <i className={`${this.getIcon(item.name)}`}></i>
            </div>
          </Col>
        )
      })
      return colArr;
    }
    const getAccountinfo=()=>{
      let colArr = [];
       accountInfo && accountInfo.forEach((a,i)=>{
        let showValue;
        if(a.isOpenHrm){
            showValue = a.showName!=''?<a href={`javaScript:openhrm(${a.value})`} onClick={event => window.pointerXY(event)}>{a.showName}</a> : <div>&nbsp;</div>;
        }else{
            showValue = a.value ? <div dangerouslySetInnerHTML={{__html:a.value}}/> : <div>&nbsp;</div>;
        }
        if(a.name=='weixin'){
          colArr.push(
            <Col className='hrm-my-card-basicInfo-left-accountinfo-label' span='24'>
              <a onClick={()=> {showWeaDialog()}}>{a.label}</a>
            </Col>
          );
        }else{
          colArr.push(
            <Col className='hrm-my-card-basicInfo-left-accountinfo-label' span='12'>
            {a.label}:
            </Col>
          );
          colArr.push(
            <Col className='hrm-my-card-basicInfo-left-accountinfo-value' span='12'>
            {showValue}
            </Col>
          );
        }

        i==3 && colArr.push(<Col className='hrm-my-card-basicInfo-left-accountinfo-middline' span='24'/>);

      });
      if(!showAccountInfo){
        colArr.splice(8,colArr.length);
      }
      colArr.push(
        <Col className='hrm-my-card-basicInfo-left-accountinfo-endicon' span='24'
          onClick={()=> hrmCardInfo4Formal.updateShowAccountInfo(!showAccountInfo)}>
          <i className={showAccountInfo ? 'icon-coms-up' : 'icon-coms-down'} title={showAccountInfo ? i18n.button.collapse() : i18n.button.expand()}/>
        </Col>
      );
      return colArr;
    }
    const viewCard = (
      <div className='hrm-my-card-basicInfo' style={{height:'100%'}}>
        <WeaDialog style={{width:500, height: 380}} title={i18n.button.companyWechat()} hideIcon>
          <div className='align-center'>
            <img src={addContentPath('/hrm/resource/image/qrcode.jpg')} style={{height: 374, width: 344}}/>
          </div>
        </WeaDialog>
        <div className='hrm-my-card-basicInfo-left' >
          {getPortrait()}
          <Row className="hrm-my-card-basicInfo-left-imgwrap-op"  type="flex" justify="center" gutter={16}>{getPortraitButtons()}</Row>
          <Row>{getAccountinfo()}</Row>
        </div>
        <div className='hrm-my-card-basicInfo-right'>
          <div className='hrm-my-card-basicInfo-right-counts'>
          {
            modelItems && modelItems.map(c => {
              const fontColor = c['font-color'];
              return (
                <div className='hrm-my-card-basicInfo-right-counts-cell' onClick={()=>{window.open(c.url)}}>
                  <img src={addContentPath(c.icon)} alt=""/>
                  <div className='hrm-my-card-basicInfo-right-counts-cell-info'>
                    <div>{c.label}</div>
                    <div title={c.num} className='text-overflow'><span style={{color:fontColor?fontColor:null,fontSize:18}}>{c.num}</span></div>
                  </div>
                </div>
              )
            })
          }
          </div>
          <Row gutter={24}>
            <Col span='12'>
              <Row className='hrm-my-card-basicInfo-right-info'>
                {
                  infoGroup && infoGroup.map(info => {
                    return (
                      <Col span='24'>
                        <InfoGroup4Formal1 items={info.items} title={info.title} showGroup={info.defaultshow}/>
                      </Col>
                    )
                  })
                }
              </Row>
            </Col>
            <Col span='12'>
              <Row className='hrm-my-card-basicInfo-right-info'>
               {
                  infoGroup2 && infoGroup2.map(info => {
                    return (
                      <Col span='24'>
                        <InfoGroup4Formal2 items={info.items} title={info.title} showGroup={info.defaultshow}/>
                      </Col>
                    )
                  })
                }
              </Row>
            </Col>
          </Row>
        </div>
      </div>
    )
    const editCard = (
      <div className='hrm-my-card-basicInfo hrm-my-cardInfo' style={{height:'100%'}}>
        {this.getSearchs()}
      </div>
    )
    return (<div style={{position: 'relative'}}>
      <TopButton
        buttons={this.getTopButtons()}
        buttonSpace={10}
        showDropIcon={true}
        dropMenuDatas={this.getRightMenu()}
        onDropMenuClick={this.onRightMenuClick}
      />
      <WeaRightMenu
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
      >
        {!isEditor ? viewCard : editCard}
      </WeaRightMenu>
    </div>)
  }

}
export default Main;