import React from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { Button, Spin} from "antd";
import {
  WeaLocaleProvider,
  WeaTop,
  WeaTab,
  WeaRightMenu,
  WeaFormItem,
  WeaSearchGroup,
  WeaHelpfulTip
} from "ecCom";
import { WeaTableNew, WeaSwitch } from "comsMobx";
import * as IntegrationUtil from "../../util/IntegrationUtil";
import Login from "../login/index"
import AddOrEdit from './AddOrEdit';
import InitializedData from "./initializedData";
import NonStand from "../../public/NonStand";

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

@inject("coremailStore")
@inject('intelogin')
@observer
export default class DataShow extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { initPage } = this.props.coremailStore;
    initPage();
  }

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

  getDropMenuDatas = () => {
    const { coremailStore } = this.props;
    const { status,tableStore } = coremailStore;
    const { tabSelected, coremailRightMenu=[] } = toJS(status);
    const btnArr = [];
    // inteLogin
    const { intelogin } = this.props;
    const { menus } = intelogin;
    const { dropMenuDatas } = menus;
    const {selectedRowKeys} = toJS(tableStore);

    switch (tabSelected) {
      case 0:
        coremailRightMenu && coremailRightMenu.map(item => {
          btnArr.push({
            key: item.type,
            icon: <i className={item.menuIcon} />,
            content: item.menuName,
            onClick: () => this.onRightMenuClick(item.type),
            disabled: (item.type != "rb_1" && selectedRowKeys.length === 0)||
              (item.type=="rb_4"&&selectedRowKeys.length == 0)
              ||(item.type=="rb_3"&&selectedRowKeys.length == 0)
              ||(item.type=="rb_2"&&selectedRowKeys.length == 0),
          })
        })
        btnArr.push({
          key: "BTN_COLUMN",
          icon: <i className="icon-coms-Custom" />,
          content: `${getLabel(32535, "显示列定制")}`,
          onClick: () => this.onRightMenuClick("BTN_COLUMN")
        });
        break;
      case 1:
        dropMenuDatas && dropMenuDatas.map(item => {
          btnArr.push(item);
        })
        break;
      case 2:
        //显示列定制
        btnArr.push({
          key: "BTN_COLUMN",
          icon: <i className="icon-coms-Custom" />,
          content: `${getLabel(32535, "显示列定制")}`,
          onClick: () => this.onRightMenuClick("BTN_COLUMN")
        });
        break;

    }
    return btnArr;
  }

  getWeaTopBtns = () => {
    const { coremailStore } = this.props;
    const {status, tableStore} = coremailStore;
    const {tabSelected, coremailRightMenu=[]} = toJS(status);
    const {selectedRowKeys} = toJS(tableStore);
    // inteLogin
    const { intelogin } = this.props;
    const { menus } = intelogin;
    const btns = menus.buttons;
    const btnArr = [];

    switch (tabSelected) {
      case 0:
        coremailRightMenu && coremailRightMenu.forEach(item => {
          btnArr.push(
            <Button 
              ecId={`${this && this.props && this.props.ecId || ''}_Button@xz70fb@integrationCoremailButton${item.type}`} 
              disabled={
                (item.type != "rb_1" && selectedRowKeys.length === 0)||
                (item.type=="rb_4"&&selectedRowKeys.length == 0)
                ||(item.type=="rb_3"&&selectedRowKeys.length == 0)
                ||(item.type=="rb_2"&&selectedRowKeys.length == 0)
              } 
              onClick={() => this.onRightMenuClick(item.type)} 
              type='primary'
            >{item.menuName}</Button>
          )
        })
        break;
      case 1:
        btns && btns.forEach(item => {
          btnArr.push(item);
        })
        break;
      case 2:
        break;
    }
    return btnArr;
  }

  getTab = () => {
    return [
      {
        title: getLabel('505949','集成列表'),
        viewcondition: 0
      },{
        title: getLabel('20960','集成登录'),
        viewcondition: 1
      },{
        title: getLabel('125928','同步日志'),
        viewcondition: 2
      }
    ];
  }

  onRightMenuClick = (type, selectedIndex) => {
    const { coremailStore } = this.props;
    const { save, init, test, pageForm, logFormTable, tableStore, getCoreMailDelete ,getInitalDialog, testCoreMail, status: {tabSelected}} = coremailStore;
    const {selectedRowKeys} = toJS(tableStore);
    const params = pageForm.getFormParams();
    selectedIndex = selectedIndex != undefined ? selectedIndex : selectedRowKeys;

    switch (type) {
      case "BTN_SAVE":
        IntegrationUtil.onCheck(pageForm, () => {
          save(params)
        })
        break;
      case "BTN_INIT":
        init(params);
        break;
      case "BTN_TEST":
        IntegrationUtil.onCheck(pageForm, () => {
          test(params)
        })
        break;
      case "BTN_COLUMN":
        if(tabSelected == 0) {
          tableStore.setColSetVisible(true);
          tableStore.tableColSet(true);
        }else if(tabSelected == 2){
          logFormTable.setColSetVisible(true);
          logFormTable.tableColSet(true);
        }
        break;
      case "BTN_NEW":
        this.onRightMenuClick2("BTN_NEW");
        break;
      case "BTN_DEL":
        this.onRightMenuClick2("BTN_DEL");
        break;
      case "BTN_LOG":
        this.onRightMenuClick2("BTN_LOG");
        break;
      case "rb_1":
        coremailStore.setStatus('coremailDialogVisible', true);
        coremailStore.setStatus('operateIndex', '');
        coremailStore.getCoremailMailAddForm();
        break;
      case "BTN_EDIT": 
        coremailStore.setStatus('coremailDialogVisible', true);
        coremailStore.setStatus('operateIndex', selectedIndex);
        coremailStore.getCoremailMailAddForm();
        break;
      case "rb_2":
        IntegrationUtil.doConfirm(getLabel(385625, '确定要删除选择的记录吗？'), getCoreMailDelete, {coremailid: selectedIndex})
        break;
      case "rb_3":
        getInitalDialog(selectedIndex);
        break;
      case "rb_4":
        testCoreMail({coremailid: selectedIndex,operate:'test'});
        break;
    }
  }

  resetSearchCondition=v=>{
    const { coremailStore } = this.props;
    const {listSearchForm,logSearchForm,getCoreMailList,getDatas} = coremailStore;
    switch (v) {
      case 0:
        listSearchForm.reset();
        getCoreMailList(listSearchForm.getFormParams());

        break;
      case 1:
        const {
          intelogin
        } = this.props, {
          search,
          mainTab,
        } = intelogin, {
          form
        } = mainTab;
        form.reset();
        search();
        break;
      case 2:;
        logSearchForm.reset();
        getDatas(null, true);
        break;
    }
  }

  getSearchAD = () => {
    const { coremailStore } = this.props;
    const { logSearchForm, logSearchFormConditions=[], status, listSearchForm } = coremailStore;
    const { tabSelected, listSearchCondition=[] } = toJS(status);
    let searchForm = null, datas = [];
    switch (Number(tabSelected)) {
      case 0: 
        searchForm = listSearchForm;
        datas = [...listSearchCondition];
        break;
      case 2:
        searchForm = logSearchForm;
        datas = [...toJS(logSearchFormConditions)];
        break;
      case 1:
        const { intelogin } = this.props;
        const { mainTab } = intelogin;
        const {
          form,
          condition=[],
        } = mainTab;
        searchForm = form;
        datas = [...condition];
        break;
    }
    try {
      return IntegrationUtil.getAdvancedItem(searchForm, datas, this.onSearch, false, this && this.props && this.props.ecId || '', "integrationCoremail"); 
    }catch(err){
      return null;
    }
  };

  onSearch = () => {
    const { coremailStore } = this.props;
    const { status, getDatas, setStatus, getCoreMailList, listSearchForm } = coremailStore;
    const { tabSelected } = toJS(status);

    switch (tabSelected) {
      case 0:
        getCoreMailList(listSearchForm.getFormParams());
        setStatus("searchShow", false);
        break;
      case 2:
        getDatas(null, true); 
        setStatus("searchShow", false);
        break;
      case 1:
        const {
          intelogin
        } = this.props, {
            search,
        } = intelogin;
        search(); 
        setStatus("searchShow", false); 
        break;
    }
  }

  getSearchButtonsAd = () => {
    const { coremailStore } = this.props;
    const { status, setStatus, listSearchForm, logSearchForm } = coremailStore;
    const { tabSelected } = toJS(status);
    let resetFun = null;
    switch (Number(tabSelected)) {
      case 0:
        resetFun = () => listSearchForm.reset();
        break;
      case 2:
        resetFun = () => logSearchForm.reset();
        break;
      case 1:
        const {
          intelogin
        } = this.props, {
            mainTab,
        } = intelogin, {
           form
        } = mainTab;
        resetFun = () => form.reset();
        break;
    }
    return IntegrationUtil.getSearchBtns(
      this.onSearch,
      resetFun,
      () => setStatus("searchShow", false),
      this && this.props && this.props.ecId || '', 
      "integrationCoremail",
    );
  };

  handleSearch = () => {
    const { intelogin } = this.props;
    const { search } = intelogin;
    let params = {}
    params.typename = '8';//筛选

    isPanelShow && changeSearchPanelStatus(false);
    getTableInfo(params);
	}

  doOnSearchChange = v => {
    const { coremailStore } = this.props;
    const { status, setStatus, listSearchForm } = coremailStore;
    const { tabSelected } = toJS(status);
    switch (tabSelected) {
      case 0:
        listSearchForm.updateFields({systemaddress: v});
        break;
      case 1:
        const {
          intelogin
        } = this.props, {
            mainTab,
        } = intelogin, {
            form,
        } = mainTab;
        form.updateFields({name: v});
        break;
      case 2:
        setStatus("searchValue", v);
        break;
    }
  }

  doOnSearch = () => {
    const { coremailStore } = this.props;  
    const { status, getDatas, getCoreMailList, listSearchForm } = coremailStore;
    const { tabSelected, searchValue } = toJS(status);
    // intelogin
    const { intelogin } = this.props;
    const { search } = intelogin;
    switch (tabSelected) {
      case 0: 
        getCoreMailList({systemaddress: listSearchForm.getFormParams().systemaddress});
        break;
      case 1:
        search();
        break;
      case 2:
        getDatas({ operatedata: searchValue });
        break;
    }
  }

  getSearchBaseValue = () => {
    const { coremailStore } = this.props;  
    const { status, listSearchForm } = coremailStore;
    const { tabSelected } = toJS(status);
    // intelogin
    const {
      intelogin
    } = this.props, {
        mainTab,
    } = intelogin, {
       form
    } = mainTab;
    return tabSelected == 0 ? listSearchForm.getFormParams().systemaddress : form.getFormParams().name;
  }

  getFormSearchs = (pageForm, pageFormConditions=[]) => {
    const { isFormInit } = pageForm;
    let group = [];
    const formParams = pageForm.getFormParams();
    isFormInit && pageFormConditions && pageFormConditions.map((c, index) => {
      let items = [];
      c && c.items && c.items.map(field => {
        let key = field.domkey[0];
          items.push({
            com: (
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@1i8yla@integrationCoremailSearchForm${key}`}
                label={`${field.label}`}
                labelCol={{ span: `${field.labelcol}` }}
                wrapperCol={{ span: `${field.fieldcol}` }}
                error={pageForm.getError(field)}
                tipPosition="bottom"
              >
                <nobr><WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@1xi2lz@integrationCoremailSearchForm${key}`} fieldConfig={field} form={pageForm} formParams={formParams} />
                {key === 'domain' ? <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@21eu44@integrationCoremailSearchForm${key}`} style={{marginLeft:10}} width={310} 
                  title={`${getLabel(33010,'填写')}@${getLabel(387448, '后面部分')},${getLabel(18541, '例如')}test@163.com,${getLabel(33010, '填写')}163.com${getLabel(387449, '即可')}`} />
                  : ''
                }
                </nobr>
              </WeaFormItem>
            )
          })
      })
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@iea56b@integrationCoremailSearchForm${index}`} center={true} col={1} needTigger={true} title={c.title} showGroup={c.defaultshow || true} items={items} />)
    })
    return group;
  }

  // 列表的三个点
  onOperatesClick = (record, index, operate) => {
    let selectIndex = record.randomFieldId;
    let type = '';

    switch (Number(operate.index)) {
      case 0:
        type = 'BTN_EDIT';//编辑
        break;
      case 1:
        type = 'rb_2';//删除
        break;
      case 2:
        type = 'rb_4';//测试
        break;
      case 3:
        type= 'rb_3';//初始化
        break;
    }
    this.onRightMenuClick(type, selectIndex);
  }

  // 列表重定义列
  getColumns = (columns) => {
    let newColumns = '';
  
    newColumns = columns && columns.map(column => {
      let newColumn = column;
      newColumn.render = (text, record, index) => { //前端元素转义
        let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
        return (
          newColumn && (newColumn.dataIndex === 'systemaddress'||newColumn.dataIndex === 'coremailsys')
            ? <a onClick={() => this.onRightMenuClick('BTN_EDIT', record.randomFieldId)} dangerouslySetInnerHTML={{__html: valueSpan}}/>
            : <div dangerouslySetInnerHTML={{__html: valueSpan}}/>
        )
      };
        return newColumn;
    });
    return newColumns;
  }

  render() {
    const { coremailStore } = this.props;
    const { status, setStatus, logFormTable, tableStore, initialList, showInitDia} = coremailStore;
    const { loading, tabSelected, searchShow, rightLoading, hasNonStandard, nonStandLoading } = toJS(status);

    return (nonStandLoading
      ? null
      : hasNonStandard
        ? <div>
            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@7rsd0z`} 
              datas={this.getDropMenuDatas()}
              collectParams= {{
                favname: `${getLabel("129787", "CoreMail集成")}`,
                favouritetype: 1,
                objid: 0,
                link: "wui/engine.html#/integration/coremail",
                importantlevel: 1
              }}
            >
            <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@bpz96x`} spinning={rightLoading}>
              <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@nlajwu`}
                loading={loading}
                buttons={this.getWeaTopBtns()}
                title={getLabel("129787", "CoreMail集成")}
                icon={<i className={IntegrationUtil.GeneralTitleColor.icon} />}
                iconBgcolor={IntegrationUtil.GeneralTitleColor.iconBgcolor}
                showDropIcon={true}
                dropMenuDatas={this.getDropMenuDatas()}
                dropMenuProps={{
                  collectParams: {
                    favname: `${getLabel("129787", "CoreMail集成")}`,
                    favouritetype: 1,
                    objid: 0,
                    link: "wui/engine.html#/integration/coremail",
                    importantlevel: 1
                  }
                }}
              >
                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@hob4jk`}
                  advanceHeight={130}
                  buttonsAd={this.getSearchButtonsAd()}
                  searchsAd={this.getSearchAD()}
                  searchType={tabSelected == "2" ? ["advanced"] : ["base, advanced"]}
                  datas={this.getTab()}
                  keyParam="viewcondition" //主键
                  countParam="groupid" //数量
                  selectedKey={tabSelected}
                  showSearchAd={searchShow}
                  setShowSearchAd={e => setStatus("searchShow", e)}
                  hideSearchAd={() => setStatus("searchShow", false)}
                  onChange={v =>{this.resetSearchCondition(Number(v)); setStatus("tabSelected", Number(v))}}
                  onSearchChange={v => { this.doOnSearchChange(v); }}
                  onSearch={v => this.doOnSearch()}
                  searchsBaseValue={this.getSearchBaseValue()}
                />

                {tabSelected === 0 && 
                  <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@ehw850`} 
                    hasOrder={true}
                    onOperatesClick={this.onOperatesClick}
                    comsWeaTableStore={tableStore}
                    needScroll={true}
                    getColumns={this.getColumns}
                  />
                }
                {tabSelected === 1 && (
                  <div>
                    <Login ecId={`${this && this.props && this.props.ecId || ''}_Login@ycmft6`} source="coremail" />
                  </div>)}
                {tabSelected === 2 && (
                  <div>
                    <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@3wjlbl`}
                      hasOrder={true}
                      //onOperatesClick={this.onOperatesClick}
                      comsWeaTableStore={logFormTable}
                      needScroll={true}
                      //getColumns={this.redoColumnsByName}
                    />
                  </div>)}
              </WeaTop>
              <AddOrEdit ecId={`${this && this.props && this.props.ecId || ''}_AddOrEdit@ezuot4`} />
              <InitializedData ecId={`${this && this.props && this.props.ecId || ''}_InitializedData@zs9n6l`} showInit={showInitDia} initialList={initialList}/>
            </Spin>
            </WeaRightMenu>
          </div>
        : <NonStand ecId={`${this && this.props && this.props.ecId || ''}_NonStand@26lmlf`} />
    )
  }
}