import React from "react";
import {inject, observer} from "mobx-react";
import {toJS} from "mobx";
import {Button, message, Spin, Modal} from "antd";
import {
  WeaLocaleProvider,
  WeaTop,
  WeaTab,
  WeaRightMenu,
  WeaFormItem,
  WeaSearchGroup,
  WeaTools,
  WeaInput
} from "ecCom";
import {WeaTableNew, WeaSwitch} from "comsMobx";
import isEmpty from 'lodash/isEmpty';
import * as IntegrationUtil from "../../util/IntegrationUtil";
import NoRight from "../../public/NoRight";
import NonStand from "../../public/NonStand";
import Login from "../login/index"

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

@inject('intelogin')
@inject("tencentMailStore")
@observer
class TencentMail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKey: 0,
      marginLeftDis: -390,
      bottomDis: 7,
      styleSheet: 'labeldeyangshi',

    };
    //来自其他入口
    const {workflowFlowStore} = this.props;
    let queryString = toJS(this.props.location.query);
    if (queryString && queryString.from) {
      this.state = {
        from: queryString.from
      }
    } else {
      this.from = '';
    }
  }

  componentDidMount() {
    const {tencentMailStore} = this.props;
    tencentMailStore.doInit();
    this.setState({selectedKey: 0});
  }

  componentWillReceiveProps(nextProps) {
    const {tencentMailStore} = this.props;
    if (this.props.location.key !== nextProps.location.key) {
      tencentMailStore.doInit();
      this.setState({selectedKey: 0});
    }
  }

  /**
   * 获取右键菜单
   * @returns {Array}
   */
  getRightMenu() {
    const {tencentMailStore, intelogin} = this.props;
    const {selectedKey, rightMenusLog, rowSelectIdsLog} = toJS(tencentMailStore.status);
    const { menus, mainTable } = intelogin;
    const { tableStore } = mainTable;
    const { dropMenuDatas } = menus;
    const formParams = tencentMailStore.baseSetForm.getFormParams();
    const datas = dropMenuDatas.splice(0);
    let tencentmailTableStore = toJS(tableStore).datas;
    let btnArr = [];

    if (selectedKey == 1) {
      datas && datas.map(item => {
        btnArr.push({
          ...item,
          disabled: ((item.key==='BTN_NEW' && (formParams.isuse==0 || tencentmailTableStore.length > 0)) || (mainTable.tableStore.selectedRowKeys.length===0 && item.key==='BTN_DEL'))
        });
      })
    } else if (selectedKey == 0) {
      btnArr.push({
        key: "BTN_INTERVAL_SAVE",
        icon: <i className="icon-coms-Preservation"/>,
        content: `${getLabel(30986, "保存")}`,
        onClick: () => this.onRightMenuClick("BTN_INTERVAL_SAVE")
      });
      btnArr.push({
        key: "BTN_BASE_TEST",
        icon: <i className="icon-coms-currency-Task"/>,
        content: `${getLabel(	25496, "测试")}`,
        onClick: () => this.onRightMenuClick("BTN_BASE_TEST")
      });
      btnArr.push({
        key: "BTN_BASE_INIT",
        icon: <i className="icon-coms-operation"/>,
        content: `${getLabel(	20873, "初始化")}`,
        onClick: () => this.onRightMenuClick("BTN_BASE_INIT")
      });
    } else {
      rightMenusLog && rightMenusLog.map(m => {
        var btn = {
          key: m.type,
          icon: <i className={m.menuIcon}/>,
          content: m.menuName,
          onClick: () => this.onRightMenuClick(m.type),
          disabled: (m.menuIcon === 'icon-coms-delete' && rowSelectIdsLog.length === 0)
        };
        btnArr.push(btn);
      });
    }
    if (selectedKey == 2) {
      //显示列定制
      btnArr.push({
        key: "BTN_COLUMN",
        icon: <i className="icon-coms-Custom"/>,
        content: `${getLabel(32535, "显示列定制")}`,
        onClick: () => this.onRightMenuClick("BTN_COLUMN")
      });
    }
    return btnArr;
  }

  /**
   * 右键菜单点击事件
   * @param type
   */
  onRightMenuClick = (type, recordId) => {
    const {tencentMailStore} = this.props;
    const {baseSetForm} = tencentMailStore;
    const {selectedKey, rowSelectIdsLog} = toJS(tencentMailStore.status);
    const {intelogin} = this.props, {BTN_NEW, BTN_DEL} = intelogin;
    if (type == "BTN_NEW" || type == "rb_1") {
      BTN_NEW({'typename':'6'});
    }
    if (type == "rb_2" || type == "BTN_DEL") {
      BTN_DEL({'typename':'6'});
      //删除
    } else if (type == "rb_delLog") {
      //删除
      if (rowSelectIdsLog.length > 0) {
        tencentMailStore.confirmModal(`${getLabel('385625', "确定要删除选择的记录吗？")}`, tencentMailStore.getTencentMailOperation, {
          operate: 'deleteLog',
          deteteviewid: rowSelectIdsLog
        });
      }
    }

    if (type == "BTN_INTERVAL_SAVE") {
      //触发周期设置保存
      IntegrationUtil.onCheck(baseSetForm,()=>{
        let params = Object.assign(baseSetForm.getFormParams(), {"operate":"INTERVAL_SAVE"});
        tencentMailStore.getTencentMailOperation(params);
      });
    }else if (type == "BTN_BASE_TEST") {
      //测试
      IntegrationUtil.onCheck(baseSetForm,()=>{
        let params = Object.assign(baseSetForm.getFormParams(), {"operate":"test"});
        tencentMailStore.getTencentMailOperation(params);
      });
    }else if (type == "BTN_BASE_INIT") {
      //初始化
      Modal.confirm({
        title: `${getLabel(81592, "是否开始同步")}`,
        onOk: ()=> {
          IntegrationUtil.onCheck(baseSetForm,()=>{
            let params = Object.assign(baseSetForm.getFormParams(), {"operate":"init"});
            tencentMailStore.getTencentMailOperation(params);
          });
        }
      })

    }else if (type == "BTN_BASE_DELETE") {
      tencentMailStore.confirmModal(`${getLabel(15097, '确定要删除吗？')}`, tencentMailStore.getTencentMailOperation, {
        ...baseSetForm.getFormParams(),
        operate: 'removeAll'
      });
    }

    if (type == "BTN_COLUMN") {
      //显示列定制
      if (selectedKey == 2) {
        tencentMailStore.tableStoreLog.setColSetVisible(true);
        tencentMailStore.tableStoreLog.tableColSet(true);
      }
    }
  };

  /**
   * 获取顶部按钮
   * @returns {Array}
   */
  getBtns = () => {
    const {tencentMailStore, intelogin} = this.props;
    const {selectedKey, rightMenusLog, rowSelectIdsLog} = toJS(tencentMailStore.status);
    const { mainTable } = intelogin;
    const { tableStore } = mainTable;
    let btnArr = [];
    let formParams = tencentMailStore.baseSetForm.getFormParams();

    if (selectedKey == 1) {
      let tencentmailTableStore = toJS(tableStore).datas;
      btnArr = [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gjwxv2@integrationTencentButtonBTNNEW`} type="primary" disabled={!formParams.isuse || tencentmailTableStore.length > 0} onClick={() => {this.onRightMenuClick('BTN_NEW')}}>{getLabel(365, '新建')}</Button>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@cwpwgf@integrationTencentButtonBTNDEL`} type="primary" disabled={tableStore.selectedRowKeys.length === 0} onClick={() => {this.onRightMenuClick('BTN_DEL')}}>{getLabel(32136, '批量删除')}</Button>
      ];
    } else if (selectedKey == 0) {
      var btn = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@s2gjzt`} type="primary" onClick={() => {{this.onRightMenuClick('BTN_INTERVAL_SAVE');}}}>{`${getLabel(30986, "保存")}`}</Button>;
      btnArr.push(btn);
      btnArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vleauw@integrationTencentButtonBTNTEST`} type="primary" onClick={() => {{this.onRightMenuClick('BTN_BASE_TEST');}}}>{`${getLabel(	25496, "测试")}`}</Button>);
      btnArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qvm7wr@integrationTencentButtonBTNINIT`} type="primary" onClick={() => {{this.onRightMenuClick('BTN_BASE_INIT');}}}>{`${getLabel(	20873, "初始化")}`}</Button>);
    } else if (selectedKey == 2) {
      rightMenusLog && rightMenusLog.map(m => {
        btnArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@r43geu@integrationTencentButton${m.type}`} 
          type="primary" 
          disabled={m.menuIcon === 'icon-coms-delete' && rowSelectIdsLog.length === 0}
          onClick={() => this.onRightMenuClick(m.type)}
        >{m.menuName}</Button>);
      });
    }
    return btnArr;
  };

  /**
   * 获取高级查询
   * @returns {Array}
   */
  getAdvancedSearch = () => {
    const {tencentMailStore} = this.props;
    const {
      searchFormLog,
      status
    } = tencentMailStore;
    const {
      selectedKey,
      TencentMailConditionInfoLog,
    } = toJS(status);
    let btns = [];
    if (selectedKey == 1) {
      return this.getSearchAd();
    } else if(selectedKey == 2) {
      return IntegrationUtil.getAdvancedItem(
        searchFormLog,
        TencentMailConditionInfoLog,
        this.handleSearchFun,
        false,
        this && this.props && this.props.ecId || '', 
        "integrationTencent"
      );
    }
    return btns;
  };

  getTabButtonsAd() {
    const {tencentMailStore} = this.props;
    const {selectedKey} = toJS(tencentMailStore.status);
    let resetFun = null;
    if(selectedKey==2) {
      resetFun = () => tencentMailStore.searchFormLog.reset();
    }else if(selectedKey==1) {
      const {intelogin} = this.props, {mainTab} = intelogin, {form} = mainTab;
      resetFun = () => form.reset();
    }

    return IntegrationUtil.getSearchBtns(
      this.handleSearchFun,
      resetFun,
      () => tencentMailStore.setState({showSearchAd: false}),
      this && this.props && this.props.ecId || '', 
      "integrationTencent"
    );
  }

  handleSearchFun = () => {
    const {tencentMailStore} = this.props;
    const {selectedKey, searchAdName, searchAdTarget} = toJS(tencentMailStore.status);
    if(selectedKey==2) {
      tencentMailStore.getTencentMailLogList();
      tencentMailStore.setState({showSearchAd: false});
    }else if(selectedKey==1) {
      const {intelogin} = this.props, {search} = intelogin;
      search({sysid: searchAdTarget, name: searchAdName}); 
      tencentMailStore.setState({showSearchAd: false});
    }
  }

  // 集成登录的高级搜索
  getSearchAd = () => {
    const {tencentMailStore} = this.props;
    const {searchAdName, searchAdTarget} = toJS(tencentMailStore.status);

    let group = [];
    let items = [];

    items.push({
      com: <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ajv77d@integrationTencentLoginFormsearchAdTarget`}
        label={getLabel('84','标识')}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@kzak19@integrationTencentLoginFormsearchAdTarget`} value={searchAdTarget} onChange={v => tencentMailStore.setState({searchAdTarget: v.trim()})} />
      </WeaFormItem>
    })
    items.push({
      com: <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@us8eg3@integrationTencentLoginFormsearchAdName`}
        label={getLabel('33439','名称')}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@s5ctr4@integrationTencentLoginFormsearchAdName`} value={searchAdName} onChange={v => tencentMailStore.setState({searchAdName: v.trim()})} />
      </WeaFormItem>
    })

    group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@uhxyq4@integrationTencentLoginForm1`} items={items} showGroup={true} />)

    return group;
  }

  /**
   * 数据列表行数据的操作项
   * @param record
   * @param index
   * @param operate
   * @param flag
   */
  onOperatesClick = (record, index, operate, flag) => {
    const {tencentMailStore} = this.props;
    const {selectedKey} = toJS(tencentMailStore.status);
    if (selectedKey == 1) {
      if (operate.index == "0") {
        //测试
        let params = {operate: 'test', viewid: record.randomFieldId}
        tencentMailStore.getTencentMailOperation(params, (result) => {
          if (result.errmsgTip) {
            message.success(result.errmsgTip);
          }
        });
      }
      if (operate.index == "1") {
        //编辑
        this.doEditDetailById(record);

      }
      if (operate.index == "2") {
        //删除
        tencentMailStore.confirmModal(`${getLabel(15097, '确定要删除吗？')}`, tencentMailStore.getTencentMailOperation, {
          operate: 'delete',
          deteteviewid: record.randomFieldId
        });
      }
      if (operate.index == "3") {
        //预览  todo
      }
    } else if (selectedKey == 2) {
      if (operate.index == "0") {
        //删除
        tencentMailStore.confirmModal(`${getLabel('83877', "确定要删除吗？")}`, tencentMailStore.getTencentMailOperation, {
          operate: 'deleteLog',
          deteteviewid: record.randomFieldId
        });
      }
    }

  };

  getColumnsInfo = (data) => {
    const that = this;
    if (!isEmpty(data)) {
      for (let index = 0; index < data.length; index++) {
        if (data[index].dbField == 'setname') {
          data[index].render = (text, record, index) => {
            return (<a onClick={that.doEditDetailById.bind(that, record)}>{record.setname}</a>);

          }
        }
      }
    }
  }

  getTab2Form = () => {
    const {tencentMailStore} = this.props;
    const {baseSetForm, status,changeShowOrHiden,showSyncParam} = tencentMailStore;
    const {BaseSetFormFields} = toJS(status);
    const {isFormInit} = baseSetForm;
    let group = [];
    const formParams = baseSetForm.getFormParams();
    isFormInit && BaseSetFormFields && BaseSetFormFields.map((c, index) => {
      let items = [];
      c.items.map(fields => {
        let keyName = getKey(fields);
        items.push({
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@9dbybj@integrationTencentTab2Form${keyName}`}
              label={`${fields.label}`}
              labelCol={{span: `${fields.labelcol}`}}
              wrapperCol={{span: `${fields.fieldcol}`}}
              error={baseSetForm.getError(fields)}
              tipPosition="bottom"
              style ={{display:keyName=='otherparam'?showSyncParam:''}}
            >

              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@uqrs7i@integrationTencentTab2Form${keyName}`} fieldConfig={fields} form={baseSetForm} formParams={formParams} onChange={v => {
                if(getKey(fields) == 'issync') {
                  let switchStatusValue = baseSetForm.getFormParams().issync;
                  changeShowOrHiden(switchStatusValue);
                }
              }}/>
            </WeaFormItem>),
          colSpan: 1,
          hide: baseSetForm.isHide(fields, (keys, allParams) => {
            let bool = false;
            return bool;
          })
        });
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@idmwwy@integrationTencentTab2Form${index}`} center col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>);
    });
    return group;
  }

  getRowSelection = () => {
    return {
      onChange: selectedRowKeys =>
        this.props.tencentMailStore.setState({
          rowSelectIdsLog: selectedRowKeys
        })
    }
  }

  render() {
    const {tencentMailStore} = this.props;
    const {intelogin} = this.props;
    const { mainTab } = intelogin;
    const {form} = mainTab;
    const {
      searchFormLog,
      tableStoreLog,
      status,
      hasRight,
      rightLoading,
      getBaseSetForm,
    } = tencentMailStore;
    const {
      showSearchAd,
      selectedKey,
      loading,
      tip,
      advanceHeight,
      searchAdTarget,
      hasNonStandard,
      nonStandLoading
    } = toJS(status);

    let topTab = [
      {
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(1361, "基本信息")}`,
        viewcondition: 0
      }
      , {
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(20960, "集成登录")}`,
        viewcondition: 1
      }
      , {
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(125928, "同步日志")}`,
        viewcondition: 2
      }
    ];
    let topTitle = getLabel(500840, "腾讯企业邮箱集成");
    return (nonStandLoading
      ? null
      : hasNonStandard
        ? rightLoading
          ? null
          : hasRight
            ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@5hx70d`}
                datas={this.getRightMenu()}
                collectParams={{
                  favname: `${getLabel(500840, "腾讯企业邮箱集成")}`,
                  favouritetype: 1,
                  objid: 0,
                  link: "wui/engine.html#/integration/tencentmail",
                  importantlevel: 1
                }}
              >
                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@irpdvd`} spinning={this.state.selectedKey == 0 && loading} tip={tip}>
                  <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@d26f9p`}
                    title={topTitle}
                    icon={<i className="icon-coms-integration"/>}
                    iconBgcolor="#1a57a0"
                    buttons={this.getBtns()}
                    showDropIcon={true}
                    dropMenuDatas={this.getRightMenu()}
                    dropMenuProps={{
                      collectParams: {
                        favname: topTitle,
                        favouritetype: 1,
                        objid: 0,
                        link: "wui/engine.html#/integration/tencentmail",
                        importantlevel: 1
                      }
                    }}
                  >
                    <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@qxb6u4`}
                      datas={topTab}
                      keyParam="viewcondition" //主键
                      selectedKey={this.state.selectedKey}
                      searchType={selectedKey == 2 ? ['advanced'] : []}
                      searchsBaseValue={selectedKey == 1 ? searchAdTarget : selectedKey == 2 ? searchFormLog.getFormParams().setname : ""}
                      advanceHeight={advanceHeight}
                      searchsAd={this.getAdvancedSearch()}
                      showSearchAd={showSearchAd}
                      buttonsAd={this.getTabButtonsAd()}
                      setShowSearchAd={() => tencentMailStore.setState({showSearchAd: !showSearchAd})}
                      hideSearchAd={() => tencentMailStore.setState({showSearchAd: false})}
                      onChange={v => {
                        getBaseSetForm();
                        this.setState({selectedKey: v});
                        form.reset();
                        searchFormLog.reset();
                        tencentMailStore.setState({selectedKey: v});
                      }}
                      onSearch={this.handleSearchFun}
                      onSearchChange={value => {
                        selectedKey == 1 ?
                          tencentMailStore.setState({searchAdTarget: value}) :
                          selectedKey == 2 ? searchFormLog.updateFields({workflowname: value}) : ""
                      }}
                    />
                    {
                      selectedKey == 1 
                        ? <Login ecId={`${this && this.props && this.props.ecId || ''}_Login@vvvy76`} source="tencentmail" />
                        : selectedKey == 2 
                          ? <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@3jt0tj`}
                              comsWeaTableStore={tableStoreLog}
                              hasOrder={true}
                              needScroll={true}
                              onOperatesClick={this.onOperatesClick}
                              rowSelection={this.getRowSelection()}
                            />
                          : this.getTab2Form()
                    }
                  </WeaTop>
                </Spin>
              </WeaRightMenu>
            : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@qtoxon`}/>
        : <NonStand ecId={`${this && this.props && this.props.ecId || ''}_NonStand@fnnfn9`} />
    );
  }
}

export default TencentMail;
