import {inject, observer} from "mobx-react";
import {toJS} from "mobx";
import {
  Button,
  message
} from "antd";
import {
  WeaTop,
  WeaTab,
  WeaFormItem, 
  WeaRightMenu, 
  WeaNewScroll,
  WeaHelpfulTip,
  WeaSearchGroup,
  WeaLocaleProvider, 
} from "ecCom";
import {
  WeaSwitch,
  WeaTableNew
} from "comsMobx";
import NoRight from "../../public/NoRight";
import NonStand from "../../public/NonStand";
import {
  onCheck,
  getSearchBtns,
  getAdvancedItem,
} from "../../util/IntegrationUtil";
import copy from 'copy-to-clipboard';
import CronExp from '../../public/CronExp';
import SyncDataRange from './SyncDataRange';

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

@inject("ExchangeStore")
@observer
class Exchange extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKey: 0,
      visiable: false,
      showSearchAd: false
    };
  }

  componentDidMount() {
    const { ExchangeStore } = this.props;
    ExchangeStore.doInit();
    this.setState({
      showSearchAd: false
    });
  }

  componentWillReceiveProps(nextProps) {
    const { ExchangeStore } = this.props;
    if (this.props.location && nextProps.location && this.props.location.key !== nextProps.location.key) {
      ExchangeStore.doInit();
      this.setState({
        showSearchAd: false
      });
    }
  }

  // tab高级搜索
  getSearchBtns = () => {
    const {
      ExchangeStore
    } = this.props, {
      searchForm
    } = ExchangeStore;
    return getSearchBtns(
      this.onSearch,
      () => searchForm.reset(),
      () => this.setState({showSearchAd: false}),
      this && this.props && this.props.ecId || '',
      "integrationExchange",
    );
  }

  getAdvancedItem = () => {
    const {
      ExchangeStore
    } = this.props, {
      searchForm,
      status
    } = ExchangeStore, {
      searchCondition
    } = toJS(status);

    return getAdvancedItem(
      searchForm,
      searchCondition,
      this.onSearch,
      false,
      this && this.props && this.props.ecId || '',
      "integrationExchange",
    )
  }

  onSearch = () => {
    const {
      ExchangeStore
    } = this.props, {
      searchForm,
      getExchangeLogList
    } = ExchangeStore;  

    getExchangeLogList({...searchForm.getFormParams()});
    this.setState({showSearchAd: false});
  }

  /**
   * 按钮的显示和事件
   */
  onMenuClick = (type) => {
    const { 
      ExchangeStore 
    } = this.props, { 
      form,
      tableStore,
      getBaseInfoFormOperation, 
    } = ExchangeStore;
    if(type && ["SAVE", "TEST"].includes(type.toLocaleUpperCase())) {
      let params = form.getFormParams(), hideFormFields = [];
      if(params.syndirection && !params.syndirection.includes('1')) {
        hideFormFields.push("cronexpr");
      }
      if(params.logintype == 2) {
        let hideFields = ["username", "password"];
        hideFormFields = hideFormFields.concat(hideFields);
      }
      window.e9HideFormFieldKeys = hideFormFields;
      onCheck(form, () => {
        if(type === "TEST") {
          params = Object.assign({}, params, {operate: "test"});
          getBaseInfoFormOperation(params);
        }else {
          getBaseInfoFormOperation(Object.assign({}, params, {operate: "checkCron"}), () => {
            params = Object.assign({}, params, {operate: "save"});
            getBaseInfoFormOperation(params);
          });
        }
      });
    }else if(type === "BTN_COLUMN") {
      tableStore.setColSetVisible(true);
      tableStore.tableColSet(true);
    }
  };

  getBtns = (datas=[], disabled, selectedKey="0") => {
    if(selectedKey == 0) {
      return datas && datas.map(data => <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@re07ja@integrationExchangeButton${data.key}`} disabled={disabled} type={data.type} key={data.key} onClick={() => this.onMenuClick(data.key)}>{data.content}</Button>);
    }else {
      return [];
    }
  };

  getRightMenu(datas=[], disabled, selectedKey="0") {
    if(selectedKey == 0) {
      return datas && datas.map(data => {
        return {
          ...data,
          disabled,
          icon: <i className={data.icon} />,
          onClick: () => this.onMenuClick(data.key)
        }
      })
    } else {
      return [{
        key: "BTN_COLUMN",
        icon: <i className="icon-coms-Custom" />,
        content: `${getLabel(32535, "显示列定制")}`,
        onClick: () => this.onMenuClick("BTN_COLUMN")
      }];
    }
  }

  // 点击复制路径
  copyURL = (url) => {
    if (copy(url)) {
      message.success(getLabel('126081', '地址已经复制成功，您可以使用Ctrl+v粘贴'));
    }
  }

  // 设置数据同步的范围
  setSynDataRange = () => {
    const {
      ExchangeStore
    } = this.props, {
      doOperationlimit,
      getExchangelimitsList
    } = ExchangeStore;

    ExchangeStore.setState({
      showSyncDataRange: true
    });
    doOperationlimit({operate: "getButtons"});
    getExchangelimitsList();
  }

  getForm = (form, datas=[]) => {
    const {
      isFormInit
    } = form;
    const formParams = form.getFormParams();
    let group = [];
    isFormInit && datas && datas.forEach((c, index) => {
      let items = [];
      c && c.items && c.items.forEach(fields => {
        let key = fields.domkey[0];
        items.push({
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@hkc226@integrationExchangeForm${key}`}
              label={"day" === key ? <span>{fields.label}<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@bzj1vh@integrationExchangeForm${key}`} style={{marginLeft: "5px"}} title={getLabel('530048','同步定时时间当天之前7天到当天之后X天的范围')} /></span> : fields.label}
              labelCol={{span: fields.labelcol}} 
              wrapperCol={{span: fields.fieldcol}}
              error={form.getError(fields)}
              tipPosition="bottom"
            >
              {
                key === "syndatarange"
                  ? <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ma2xdg@integrationExchangeForm${key}`}
                      onClick={this.setSynDataRange} 
                    >
                      {getLabel('30747','设置')}
                    </Button>
                  : key === "cronexpr"
                    ? <CronExp ecId={`${this && this.props && this.props.ecId || ''}_CronExp@e2tdld@integrationExchangeForm${key}`} 
                        field={fields}
                        value={form.getFormParams()[key] || '0 0 * * * ?'}
                        onChange={(v="") => form.updateFields({[key]: v.trim() || '0 0 * * * ?'})}
                      />
                    : <nobr>
                        <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@tjhqxf@integrationExchangeForm${key}`} fieldConfig={fields} form={form} formParams={formParams} onChange={v => {
                          if(["syndirection", "datatpye"].includes(key)) {
                            if(!form.getFormParams()[key]) {
                              form.updateFields({[key]: formParams[key] == "1" ? "2" : "1"});
                            }
                          }
                        }} />
                          {
                            key === "userloginurl"
                              ? <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3app8r@integrationExchangeForm${key}`} 
                                  style={{marginLeft: "10px"}} 
                                  onClick={() => this.copyURL(formParams.userloginurl)}
                                >{getLabel('383573','点击复制')}</Button>
                              : key === "day"
                                ? <span
                                    style={{
                                      marginLeft: "10px",
                                      lineHeight: "30px"
                                    }}
                                  >{getLabel('1925','天')}</span>
                                : null
                          }
                        </nobr>
              }
              
            </WeaFormItem>),
          colSpan: 1,
          hide: form.isHide(fields, (keys, allParams) => {
            let bool = false, key = fields.domkey[0];
            ["userloginurl"].includes(key) && allParams.logintype != '2' && (bool = true);
            ["username", "password"].includes(key) && allParams.logintype != '1' && (bool = true);
            ["cronexpr"].includes(key) && (!allParams.syndirection.includes('1')) && (bool = true);
            fields && fields.showWhere && fields.showWhere.length > 0 && fields.showWhere.forEach(w => {
              if(!bool){
                let show = false;
                for(let val of w.value){
                if(allParams[w.domkey] == val){
                    show = true;
                    break;
                }
                }
                bool = !show;
              }
            })
            return bool;
          })
        });
        if(["userloginurl"].includes(key) && formParams.logintype == '2') {
          items.push({
            com: <div 
              style={{
                textAlign: "left",
                color: "red"
              }}
            >{getLabel('517422','请管理员将【用户登录地址】作为菜单地址新增菜单，以供普通用户进行登录绑定Exchange')}。</div>
          })
        }
      })
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@6fomub@integrationExchangeForm${index}`} col={1} center={true} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
    });
    return group;
  }

  // 切换tab页
  handleTabChange = (selectedKey) => {
    const {
      ExchangeStore
    } = this.props, {
      status,
      getBaseInfo,
      getExchangeLogInfo,
    } = ExchangeStore;

    if(selectedKey == 0) {
      getBaseInfo();
    }else if(selectedKey == 1) {
      getExchangeLogInfo();
    }
    ExchangeStore.setState({
      selectedKey
    });
  }

  render() {
    const { 
      ExchangeStore 
    } = this.props, {
      form,
      status,
      hasRight, 
      tableStore,
    } = ExchangeStore, {
      menus,
      loading,
      tabDatas,
      condition,
      selectedKey,
      buttonStatus,
      collectParams,
      advancedHeight,
      hasNonStandard, 
      nonStandLoading,
    } = toJS(status), {
      showSearchAd
    } = this.state;
    return (nonStandLoading
      ? null
      : hasNonStandard
        ? loading 
          ? null
          : hasRight
            ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@gb37di`}
                datas={this.getRightMenu(menus, buttonStatus, selectedKey)}
                collectParams={collectParams}
              >
                <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@jub2gt`}
                  title={getLabel('517412','Exchange集成')}
                  icon={<i className="icon-coms-integration" />}
                  iconBgcolor="#1a57a0"
                  buttons={this.getBtns(menus, buttonStatus, selectedKey)}
                  showDropIcon={true}
                  dropMenuDatas={this.getRightMenu(menus, buttonStatus, selectedKey)}
                  dropMenuProps={{collectParams}}
                />
                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@7nxjpl`} 
                  keyParam={"viewcondition"}
                  selectedKey={selectedKey}
                  datas={tabDatas}
                  searchType={selectedKey == 1 ? ["advanced"] : []}
                  buttonsAd={this.getSearchBtns()}
                  searchsAd={this.getAdvancedItem()}
                  advanceHeight={advancedHeight}
                  showSearchAd={showSearchAd}
                  setShowSearchAd={() => this.setState({showSearchAd: !showSearchAd})}
                  hideSearchAd={() => this.setState({showSearchAd: false})}
                  onChange={this.handleTabChange}
                />
                <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@klm68w`} height={"calc(100% - 100px)"}> 
                  {
                    selectedKey == 0
                      ? this.getForm(form, condition)
                      : selectedKey == 1
                        ? <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@uwt9tr`} 
                            comsWeaTableStore={tableStore}
                            hasOrder={true}
                            needScroll={true}
                          />
                        : null
                  }
                </WeaNewScroll>
                <SyncDataRange ecId={`${this && this.props && this.props.ecId || ''}_SyncDataRange@u1l3h9`}/>
              </WeaRightMenu>
            : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@77jvpt`}/>
        : <NonStand ecId={`${this && this.props && this.props.ecId || ''}_NonStand@k37czh`} />
    );
  }
}

export default Exchange;
