import React, { Component } from 'react';
import {
  inject,
  observer
} from 'mobx-react';
import {toJS} from "mobx";
import {WeaRightMenu, WeaTop, WeaTab, WeaLocaleProvider, WeaHelpfulTip, WeaFormItem, WeaSearchGroup} from "ecCom";
import {Button, Spin} from "antd";
import {WeaTableNew, WeaSwitch} from "comsMobx";
import {getSearchBtns, getAdvancedItem} from '../../util/IntegrationUtil';
import MainTable from "../login/MainTable";
import isEmpty from 'lodash/isEmpty';
import CronExp from '../../public/CronExp';
import '../../style/email.less';

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

@inject('intelogin')
@observer
export default class Header extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tabDatas: [
        {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: getLabel('505949','集成列表'),
          viewcondition: 0
        }
        , {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: getLabel(20960, "集成登录"),
          viewcondition: 1
        }
        , {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: getLabel(125928, "同步日志"),
          viewcondition: 2
        }
        , {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: getLabel('516042','日志清理'),
          viewcondition: 3
        }
      ],
      baseRightMenus: [{
        key: "BTN_NEW",
        icon: <i className="icon-coms-New-Flow"/>,
        content: getLabel('365','新建'),
        type: "primary"
      }, {
        key: "BTN_DELETE",
        icon: <i className="icon-coms-delete"/>,
        content: getLabel('32136','批量删除'),
        type: "primary"
      }],
      logRightMenus: [{
        key: "BTN_INTERVAL_SAVE",
        icon: <i className="icon-coms-Preservation"/>,
        content: getLabel(30986, "保存"),
        type: "primary"
      }],
      showSearchAd: false,
      selectedKey: "0"
    }
  }

  getBtns = () => {
    const {selectedKey, baseRightMenus, logRightMenus} = this.state;
    const {
      intelogin,
      initLoading,
    } = this.props, {
      menus
    } = intelogin, {
      outTopButtons=[]
    } = menus;
    let datas = [];
    if(selectedKey == 1) {
      return outTopButtons.map(item => 
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@x4rvrh@integrationIntemailButton${item.key || ""}`} 
          disabled={item.disabled}
          key={item.key}
          type={item.type || "primary"}
          onClick={() => item.onClick({type: "mail"})}
        >{item.content}</Button>  
      )
    }else {
      if(selectedKey == 0) {
        datas = [...baseRightMenus];
      }else if(selectedKey == 2) {
        datas = [...this.props.rightMenus];
      }else if(selectedKey == 3) {
        datas = [...logRightMenus];
      }
      return datas.map(item => 
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9p8xuw@integrationIntemailButton${item.key || ""}`} 
          disabled={this.props.buttonLoading || initLoading || (item.key==="BTN_DELETE" && toJS(this.props.tableStore.selectedRowKeys).length == 0)} 
          key={item.key} 
          type={item.type} 
          onClick={() => this.onMenuClick(item.key)}
        >{item.content}</Button>);
    }
  };

  getRightMenus = () => {
    const {selectedKey, baseRightMenus, logRightMenus} = this.state;
    const {
      intelogin,
      initLoading,
    } = this.props, {
      menus
    } = intelogin, {
      dropMenuDatas=[]
    } = menus;
    
    if(selectedKey == 1) {
      return dropMenuDatas.map(item => {
        if(item.key === "BTN_NEW") {
          return {
            ...item,
            disabled: item.disabled
          }
        }else {
          return {
            ...item,
            onClick: () => item.onClick({typename: this.props.typename})
          };
        }
      })
    }else {
      let buttons = [], columnSet = {
        key: "BTN_COLUMN",
        icon: <i className="icon-coms-Custom"/>,
        content: getLabel(32535, "显示列定制"),
        onClick: () => this.onMenuClick("BTN_COLUMN")
      }, logSet = {
        key: "BTN_LOG",
        icon: <i className="icon-coms-Custom"/>,
        content: getLabel('83','日志'),
        onClick: () => this.onMenuClick("BTN_LOG")
      };
      if(selectedKey == 0) {
        buttons = [...baseRightMenus];
        buttons.push(logSet);
        buttons.push(columnSet);
      }else if(selectedKey == 2) {
        buttons = [...this.props.rightMenus];
        buttons.push(columnSet);
      }else if(selectedKey == 3) {
        buttons = [...logRightMenus];
      }
      return buttons.map(item => {
        return {
          ...item,
          disabled: this.props.buttonLoading || initLoading || (item.key === "BTN_DELETE" && toJS(this.props.tableStore.selectedRowKeys).length === 0),
          onClick: () => this.onMenuClick(item.key)
        }
      })
    }
  }

  onMenuClick = (type, record=null) => {
    const {selectedKey} = this.state;
    this.props.onMenuClick(selectedKey, type, record);
  }

  getButtonAd = () => {
    const {
      intelogin,
    } = this.props, {
      mainTab,
    } = intelogin, {
      form,
    } = mainTab;
    let resetFun = () => this.state.selectedKey == 0 ? this.props.searchForm1.reset() : this.state.selectedKey == 1 ? form.reset() : this.props.searchForm.reset();
    let closeFun = () => this.setState({showSearchAd: false});
    return getSearchBtns(this.getSearchFun, resetFun, closeFun, this && this.props && this.props.ecId || '', "integrationIntemail");
  }

  getSearchFun = () => {
    if(this.state.selectedKey == 1) {
      const {
        intelogin,
      } = this.props;
      intelogin.search({type: "mail"});
    } else {
      this.props.onSearch(this.state.selectedKey);
    }
    this.setState({showSearchAd: false});
  }

  onOperatesClick = (record, index, operate) => {
    this.onMenuClick(operate.index, record);
  };  

  getColumnsInfo = (data) => {
    const {selectedKey} = this.state;
    if(selectedKey == 0) {
      if(!isEmpty(data)) {
        for(let index = 0; index < data.length; index++) {
          if(data[index].dbField == "syscode") {
            data[index].render = (text, record, index) => {
              return (<a onClick={() => this.onMenuClick("BTN_EDIT", record)}>{text}</a>);
            }
          } else if(data[index].dataIndex === "mailicon") {
            data[index].render = (text, record, index) => {
              return record.mailtype == '1' 
                ? <div style={{
                    background: "red",
                    color: "white",
                    width: 30,
                    height: 30,
                    borderRadius: "50%",
                    textAlign: "center",
                    lineHeight: "30px",
                    fontSize: 18,
                  }}><i className="icon-coms02-ali-mail" /></div>  
                : record.mailtype == '2'  
                  ? <div style={{
                      background: "red",
                      color: "white",
                      width: 30,
                      height: 30,
                      borderRadius: "50%",
                      textAlign: "center",
                      lineHeight: "30px",
                      fontSize: 18,
                    }}><i className="icon-coms02-wangyi" /></div>
                  : null;
            }
          } else if(data[index].dataIndex === "isuse") {
            data[index].render = (text, record, index) => {
              return record.isuse == 0 ? getLabel('21888','未开启') : <span style={{color: "green"}}>{getLabel('21889','已开启')}</span>;
            }
          } else if(data[index].dataIndex === "issync") {
            data[index].render = (text, record, index) => {
              return record.issync == 0 ? getLabel('21888','未开启') : <span style={{color: "green"}}>{getLabel('21889','已开启')}</span>;
            }
          }
        }
      }
    }
  }

  // 日志清理
  getForm = (form, datas=[]) => {
    const {isFormInit} = form;
    let group = [];
    const formParams = form.getFormParams();
    isFormInit && datas && datas.forEach((c, index) => {
      let items = [];
      c && c.items && c.items.forEach(fields => {
        let dom = null, key = fields.domkey[0];
        if(key === "cleanCronExpr") {
          dom = <CronExp ecId={`${this && this.props && this.props.ecId || ''}_CronExp@rzes9u@integrationIntemailLogForm${key || ""}`} 
            key={key} 
            value={form.getFormParams().cleanCronExpr}
            field={fields}
            onChange={v => form.updateFields({cleanCronExpr: v.trim()})}
          />;
        } else{
          dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@tuaydj@integrationIntemailLogForm${key || ""}`} fieldConfig={fields} form={form} formParams={formParams} />;
        }
        items.push({
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@cb1o9j@integrationIntemailLogForm${key || ""}`}
              label={`${fields.label}`}
              labelCol={{span: `${fields.labelcol}`}}
              wrapperCol={{span: `${fields.fieldcol}`}}
              error={form.getError(fields)}
              tipPosition="bottom"
            >
              <nobr>
                {dom}
                {
                  key === "cleanType"
                    ? <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@p7159s@integrationIntemailLogForm${key || ""}`} title={getLabel('516454','自动清理日志数据将清理该时间之前的数据')} style={{marginLeft: 15, lineHeight: "30px", position: "absolute"}} />
                    : null
                }
              </nobr>
            </WeaFormItem>),
          colSpan: 1,
          hide: form.isHide(fields, (keys, allParams) => {
            let bool = false;
            fields.domkey[0] != "cleanStatus" && allParams.cleanStatus != 1 && (bool=true);
            fields && fields.showWhere && fields.showWhere.length > 0 && fields.showWhere.map(w => {
              if(!bool){
                let show = false;
                for(let val of w.value){
                  if(allParams[w.domkey] == val){
                      show = true;
                      break;
                  }
                }
                bool = !show;
              }
            })
            return bool;
          })
        });
      })
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@mgthpv@integrationIntemailLogForm${index || ""}`} col={1} center={true} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
    });
    return group;
  }

  render() {
    const {
      tabDatas, 
      showSearchAd, 
      selectedKey,
    } = this.state, {
      intelogin,
      initLoading,
    } = this.props, {
      searchsAd,
      mainTab,
    } = intelogin, {
      condition,
    } = mainTab;
    let advanceHeight = 72,
      datas = selectedKey == 0 ? this.props.searchCondition1 : selectedKey == 1 ? condition : this.props.searchCondition,
      form = selectedKey == 0 ? this.props.searchForm1 : selectedKey == 1 ? mainTab.form :  this.props.searchForm,
      searchKey = selectedKey == 1 ? 'name' : this.props.searchKey;
      try{
        advanceHeight = Math.ceil(datas[0].items.length/2) * 72;
      }catch(err){}
      let hasAdSearch = selectedKey != 3;
    return (
      <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@ve3z4i`}
        datas={this.getRightMenus()}
        collectParams={this.props.collectParams}
      >
        <div className="inte-email">
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@86n2hp`}
            title={this.props.title} 
            icon={<i className="icon-coms-integration"/>}
            iconBgcolor="#1a57a0"
            buttons={this.getBtns()}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenus()}
            dropMenuProps={{
              collectParams: this.props.collectParams
            }}
          />
          <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@2t9f5y`}
            datas={tabDatas}
            keyParam="viewcondition" 
            countParam="groupid"
            selectedKey={selectedKey}
            searchType={hasAdSearch ? ['base', 'advanced'] : []}
            advanceHeight={advanceHeight}
            searchsAd={selectedKey == 1 ? searchsAd : getAdvancedItem(form, datas, this.getSearchFun, false, this && this.props && this.props.ecId || '', "integrationIntemail")}
            buttonsAd={this.getButtonAd()}
            searchsBaseValue={hasAdSearch ? form.getFormParams()[searchKey] : ""}
            onSearchChange={value => form.updateFields({[searchKey]: value})}
            onSearch={this.getSearchFun}
            showSearchAd={showSearchAd}
            setShowSearchAd={showSearchAd => this.setState({showSearchAd})}
            hideSearchAd={() => this.setState({showSearchAd: false})}
            onChange={v => {
              this.setState({selectedKey: v});
              if(v == 1) {
                mainTab.form.reset();
              } 
              if(this.props.onChange && typeof(this.props.onChange) === "function") {
                this.props.onChange(v);
              }
            }}
          />
          {
            selectedKey == 3
              ? <div className="email-log-setting">
                  {this.getForm(this.props.form, this.props.condition)}
                </div> 
              : selectedKey == 1
                ? this.props.buttonLoading 
                  ? null
                  : <MainTable ecId={`${this && this.props && this.props.ecId || ''}_MainTable@yqs00l`} type={"mail"} />
                : <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@mkzk0o`} size="large" spinning={initLoading && selectedKey == 0 && (!this.props.showDialog)}>
                    <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@mfrmcb`}
                      key={selectedKey}
                      comsWeaTableStore={this.props.tableStore}
                      hasOrder={true}
                      needScroll={true}
                      onOperatesClick={this.onOperatesClick}
                      getColumns={this.getColumnsInfo}
                    />
                  </Spin> 
          }
        </div>
      </WeaRightMenu>
    )
  }
}
