import React from "react";
import {CopyToClipboard} from 'react-copy-to-clipboard';
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { Button, message } from "antd";
import { WeaTableNew, WeaSwitch } from "comsMobx";
import * as IntegrationUtil from "../../util/IntegrationUtil";
import NoRight from "../../public/NoRight";
import IMInitDialog from './IMInitDialog';
import {
  WeaLocaleProvider,
  WeaTop,
  WeaTab,
  WeaRightMenu,
  WeaFormItem,
  WeaTools,
  WeaSearchGroup,
  WeaNewScroll
} from "ecCom";

const { WeaTable } = WeaTableNew;
const { getKey } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;

@inject("imrtx")
@observer
export default class IMrtx extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      topTab: [
        {
          title: `${getLabel(81711, "基本信息")}`,
          viewcondition: 0
        },
        {
          title: `${getLabel(125928, "同步日志")}`,
          viewcondition: 1
        }
      ],
      collectParams: {
        favname: `${getLabel('386889', "IM集成设置")}`,
        favouritetype: 1,
        objid: 0,
        link: "wui/engine.html#/integration/imrtx",
        importantlevel: 1
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    const { imrtx } = this.props;
    if (this.props.location.key !== nextProps.location.key) {
      imrtx.doInit();
    }
  }

  componentDidMount() {
    const { imrtx } = this.props;
    imrtx.doInit();
  }

  getRightMenu() {
    const { imrtx } = this.props;
    const { selectedKey} = toJS(imrtx.status);
    let data = [];
    if (selectedKey == 1) {
      data = [{
        key: "BTN_COLUMN",
        icon: "icon-coms-Custom",
        content: getLabel(32535, "显示列定制")
      }]
    }else {
      data = [{
        key: "save",
        icon: "icon-coms-Preservation",
        content: getLabel(86, "保存")
      }, {
        key: "test",
        icon: "icon-coms-currency-Task",
        content: getLabel(25496, "测试")
      }, {
        key: "initialize",
        icon: "icon-coms-operation",
        content: getLabel(20873, "初始化")
      }]
    }

    return data && data.map(v => {
      return {
        key: v.key,
        icon: <i className={v.icon} />,
        content: v.content,
        onClick: () => this.onRightMenuClick(v.key)
      }
    })
  }

  getAdvancedSearch = () => {
    const { imrtx } = this.props;
    const { status, searchForm } = imrtx;
    const { searchFormFields } = toJS(status);

    return IntegrationUtil.getAdvancedItem(
      searchForm,
      searchFormFields,
      this.handleSearchFun,
      false,
      this && this.props && this.props.ecId || '',
      "integrationImRtx",
    );
  };

  handleSearchFun = () => {
    const { imrtx } = this.props;
    imrtx.getTable();
    imrtx.setState({ showSearchAd: false });
  }

  getTabButtonsAd() {
    const { imrtx } = this.props;
    return IntegrationUtil.getSearchBtns(
      this.handleSearchFun, 
      () => imrtx.searchForm.reset(), 
      () => imrtx.setState({ showSearchAd: false }),
      this && this.props && this.props.ecId || '',
      "integrationImRtx",
    );
  }

  getBtns = () => {
    let data = [{
      key: "save",
      content: getLabel(86, "保存")
    }, {
      key: "test",
      content: getLabel(25496, "测试")
    }, {
      key: "initialize",
      content: getLabel(20873, "初始化")
    }];
    return data.map(v => <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3qfvpl@integrationIMButton${v.key}`} type="primary" onClick={() => this.onRightMenuClick(v.key)}>{v.content}</Button>);
  };


  onRightMenuClick = type => {
    const { imrtx } = this.props;
    const { save, newBaseForm, initialize, status} = imrtx;
    const params = newBaseForm.getFormParams();
    const { initializeResult } = toJS(status);
    switch (type) {
      case "save":
        save(params);
        break;
      case "BTN_COLUMN":
        imrtx.tableBaseInfo.setColSetVisible(true);
        imrtx.tableBaseInfo.tableColSet(true);
        break;
      case "initialize":
        if (initializeResult && initializeResult.flag && initializeResult.flag == 'syning') {
          imrtx.initialize();
        } else {
          IntegrationUtil.doConfirm(getLabel(81592, "是否开始同步"), imrtx.initialize);
        }
        break;
      case "test":
        params.method = "test";
        save(params);
        break;
    }
  };

  getFormSearchs = (form, datas) => {
    const { imrtx } = this.props;
    const { inputfaceOptions, inputface, getPassWord, status: {showOCSPassWord} } = imrtx;
    const { isFormInit } = form;
    const formParams = form.getFormParams();
    let group = [];

    isFormInit && datas && datas.map((c, index) => {
      let items = [];
      c.items && c.items.map(fields => {
        items.push({
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@iehzyb@integrationIMForm${fields.domkey[0]}`}
              label={(getKey(fields) === "rtxConnServer" && form.getFormParams().rtxOrElinkType == '1') ? getLabel('18782','端口号') : `${fields.label}`}
              labelCol={{ span: fields.labelcol }}
              wrapperCol={{ span: fields.fieldcol }}
              error={form.getError(fields)}
              tipPosition="bottom"
            >
              {
                getKey(fields) === "download" 
                  ? <a className="common" href="javascript:void(0)" style={{display: 'inline-table', lineHeight: "30px"}} onClick={()=> {
                      window.location.href = `${location.origin}${fields.helpfulTip}`;
                    }}>{getLabel(31156, "下载")}</a>
                  : <nobr>
                      <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@v8dc7j@integrationIMForm${fields.domkey[0]}`} formParams={formParams} fieldConfig={fields} form={form} onChange={v=> {
                        if(getKey(fields) === 'rtxOrElinkType') {
                          if(form.getFormParams().rtxOrElinkType=="1"){
                            form.updateFields({inputface:inputfaceOptions.ocsInputface});
                            getPassWord();
                          }else{
                            form.updateFields({inputface:inputfaceOptions.rtxInputface});
                          }
                        }
                      }}/>
                      {
                        getKey(fields) === "inputface" 
                          ? <CopyToClipboard ecId={`${this && this.props && this.props.ecId || ''}_CopyToClipboard@ritmmv@integrationIMForm${fields.domkey[0]}`} 
                              text={form.getFormParams().inputface} 
                              onCopy={() => message.success(getLabel('126081', '地址已经复制成功，您可以使用Ctrl+v粘贴'))}
                            >
                              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1g06or@integrationIMForm${fields.domkey[0]}`} style={{position: 'absolute', right:'-55px', top: '4px'}} size="small" type={'ghost'}>{getLabel("77", "复制")}</Button>
                            </CopyToClipboard>
                          : ""
                      }
                    </nobr>
              }
            </WeaFormItem>
          ),
          colSpan: 1,
          hide: form.isHide(fields, (keys, allParams)=> {
            let hide = true;
            let key = keys[0];  
            if (allParams.rtxOrElinkType == '0' && ['rtxserverurl','rtxserverouturl','rtxserverport','rtxConnServer','rtxVersion','rtxDenyHrm',
              'rtxOnload','impwd','rtxAlert','userattr',
              'isDownload','download','userattr'].indexOf(key) > -1) {
              hide = false;
            } else if (allParams.rtxOrElinkType == '1' &&  ['domainName','rtxserverurl','rtxDenyHrm','rtxOnload','impwd', 'rtxConnServer',
              'rtxAlert','userattr','rtxLoginToOA','isDownload'].indexOf(key) > -1) {
              hide = false;
            } else if (allParams.rtxOrElinkType == '2' &&  ['rtxserverurl','rtxDenyHrm',
            'rtxOnload','rtxAlert','isDownload'].indexOf(key) > -1) {
              hide = false;
            }
            if (key =='inputface' && allParams.rtxLoginToOA === '0') {
              hide = true;
            } else if (key =='inputface' && allParams.rtxLoginToOA === '1' && allParams.rtxOrElinkType == '1') {
              hide = false;
            }
            if (key == 'isusedtx' || key == 'rtxOrElinkType') {
              hide = false;
            }
            allParams.rtxOrElinkType == "1" && key === 'impwd' && showOCSPassWord == 0 && (hide = true);
            return hide;
          })
        });
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@tea10p@$integrationIMForm${index}`} center col={1} needTigger={false} showGroup={c.defaultshow} items={items}/>);
    });
    return group;
  };

  render() {
    const { imrtx } = this.props;
    const { status, tableBaseInfo, newBaseForm,hasRight, rightLoading } = imrtx;
    const { selectedKey, showSearchAd, baseFormFields, advanceHeight } = toJS(status);
    const { topTab, collectParams } = this.state;
    
    return (
      !rightLoading && <div style={{height: "100%"}}>
        { 
          hasRight
            ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@8x0c4w`}
                datas={this.getRightMenu()}
                collectParams={collectParams}
              >
                <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@jc6smj`}
                  key={selectedKey}
                  title={getLabel('386889',"IM集成设置")}
                  icon={<i className={IntegrationUtil.GeneralTitleColor.icon} />}
                  iconBgcolor={IntegrationUtil.GeneralTitleColor.iconBgcolor}
                  buttons={selectedKey == 0 ? this.getBtns() : []}
                  showDropIcon={true}
                  dropMenuDatas={this.getRightMenu()}
                  dropMenuProps={{
                    collectParams
                  }}
                />
                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@bufz5n`}
                  datas={topTab}
                  keyParam="viewcondition" 
                  selectedKey={selectedKey}
                  searchType={selectedKey == 1 ? ["advanced"] : []}
                  advanceHeight={advanceHeight}
                  searchsAd={selectedKey == 1 ? this.getAdvancedSearch() : []}
                  showSearchAd={showSearchAd}
                  buttonsAd={this.getTabButtonsAd()}
                  setShowSearchAd={() => imrtx.setState({ showSearchAd: !showSearchAd })}
                  hideSearchAd={() => imrtx.setState({ showSearchAd: false })}
                  onChange={(v)=> {
                    imrtx.setState({ selectedKey: v })
                    if (v == 1) {
                      imrtx.getCondition();
                      imrtx.searchForm.reset();
                      imrtx.getTable();
                    } else {
                      imrtx.getForm();
                    }
                  }}
                />
                {
                  selectedKey == 0
                    ? <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@kjt5ki`} height={"calc(100% - 100px)"}>
                        {this.getFormSearchs(newBaseForm, baseFormFields)}
                      </WeaNewScroll>
                    : <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@977r56`}
                        comsWeaTableStore={tableBaseInfo}
                        hasOrder={true}
                        needScroll
                      />
                }
                <IMInitDialog ecId={`${this && this.props && this.props.ecId || ''}_IMInitDialog@uamdnv`} />
              </WeaRightMenu>
            : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@gmq1ul`}/>
        }
      </div>
    );
  }
}
