import React from 'react';
import {toJS} from 'mobx';
import {inject, observer} from "mobx-react";
import {Button, Spin} from 'antd';
import {WeaTableNew} from "comsMobx";
import {WeaDialog, WeaRightMenu, WeaLocaleProvider, WeaButtonIcon, WeaTab, WeaBrowser} from 'ecCom';
import {GeneralTitleColor, menuIcon, getForm, getDescription, checkUnique, onCheck, doConfirm, getSearchBtns, getAdvancedItem} from "../../util/IntegrationUtil";
import WhiteList from '../../public/WhiteList';

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

@inject("whiteListStore")
@observer
export default class AddOrEdit extends React.Component { 
  constructor(props) {
    super(props);
    this.state = {
      showSearchAd: false
    }
  }

  componentWillUnmount() {
    this.props.whiteListStore.setState({
      addOrEditDialogVisible: false,
      operateIndex: "",
      detailList: false
    })
  }

  /**
   * 右键菜单
   */
  getRightMenu = () => {
    const {detailList, selectedKey, operateIndex, buttonLoading} = toJS(this.props.whiteListStore.status);
    if(detailList && selectedKey == 0) {
      return [];
    }else {
      let btnArr = [{
        key: 'BTN_SAVE',
        icon: menuIcon.save,
        content: getLabel(86,'保存'),
        disabled: buttonLoading,
        onClick: () => this.onRightMenuClick('BTN_SAVE')
      }];
      if(selectedKey == 0 && operateIndex == "") {
        btnArr.push({
          key: 'BTN_SAVE_DETAIL',
          icon: menuIcon.save,
          content: getLabel('513652','保存后配置白名单'),
          disabled: buttonLoading,
          onClick: () => this.onRightMenuClick('BTN_SAVE_DETAIL')
        });
      }
      return btnArr;
    }
  }

  getBtns = () => {
    const {detailList, selectedKey, operateIndex, buttonLoading} = toJS(this.props.whiteListStore.status);
    if(detailList && selectedKey == 0) {
      return [];
    }else {
      let btnArr = [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@zxdpwx@integrationWhitelistAddOrEditButtonSave`} type="primary" disabled={buttonLoading} onClick={()=> this.onRightMenuClick('BTN_SAVE')}>{getLabel(86,'保存')}</Button>
      ];
      if(selectedKey == 0 && operateIndex == "") {
        btnArr.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vps1po@integrationWhitelistAddOrEditButtonDetail`} type="primary" disabled={buttonLoading} onClick={()=> this.onRightMenuClick('BTN_SAVE_DETAIL')}>{getLabel('513652','保存后配置白名单')}</Button>
        );
      }
      return btnArr;
    }
  }

  /**
   * 保存的操作
   */
  saveOperate = (param) => {
    const {whiteListStore} = this.props;
    const {status: {hiddenFields, selectedKey}, newForm} = whiteListStore;
    let params = Object.assign({}, newForm.getFormParams(), toJS(hiddenFields));
    if(selectedKey == 0) {
      let saveCallBack = null;
      if(param && param.type === "BTN_SAVE_DETAIL") {
        saveCallBack = whiteListStore.getFilterFormInfo;
      }
      whiteListStore.getRegisterFilterisValid({filter_clazz: newForm.getFormParams().clazz.trim()}, () => whiteListStore.getRegisterFilterFormOperation({...params, ...param}, saveCallBack));
    }else if(selectedKey == 1) {
      whiteListStore.getBaseInfoFormOperation(params);
    }
  }

  /**
   * menuClick事件
   */
  onRightMenuClick = (type) => {
    const {whiteListStore} = this.props;
    const {status: {selectedKey, operateIndex}, newForm} = whiteListStore;
    const formParams = newForm.getFormParams();

    if(["BTN_SAVE", "BTN_SAVE_DETAIL"].includes(type)) {
      let checkParams = {}, key = "", name = ""; 
      if(selectedKey == 0) {
        key = "clazz";
        name = '3';
        checkParams = {
          tableName: 'Int_RegisterFilter',
          fieldName: `${key}_`,
          fieldValue: formParams[key].replace(/^(\s*)|(\s*)$/g, ''),
          idName: 'id',
          idValue: operateIndex
        };
      }else if(selectedKey == 1) {
        key = "exclude";
        name = '4';
        checkParams = {
          tableName: 'Int_WhiteList',
          fieldName: `${key}_`,
          fieldValue: formParams[key].replace(/^(\s*)|(\s*)$/g, ''),
          idName: 'id',
          idValue: operateIndex
        };
      }
      onCheck(newForm, () => checkUnique(checkParams, newForm, key, name, operateIndex, this.saveOperate, {type}));
    }else if(type === "BTN_EXIT") {
      whiteListStore.setState({
        addOrEditDialogVisible: false,
        operateIndex: "",
        detailList: false
      })
    }
  }
  
  /**
   * dialog弹窗的标题
   */
  getDialogTitle = () => {
    const {whiteListStore} = this.props;
    const {status: {selectedKey, operateIndex, detailList}} = whiteListStore;
    let title = '';
    if(selectedKey == 0) {
      if(detailList) {
        title = getLabel('513418','引用白名单地址');
      }else {
        if(operateIndex) {
          title = getLabel('513390','编辑过滤器');
        }else {
          title = getLabel('513389','注册过滤器');
        }
      } 
    }else if(selectedKey == 1) {
      if(operateIndex) {
        title = getLabel('513567','编辑白名单');
      }else {
        title = getLabel('513566','新增白名单');
      }
    }
    return title;
  }

  /**
   * form中onChnage事件
   */
  handleChange = (field, item) => {
    const {whiteListStore} = this.props;
    const {status, newForm} = whiteListStore;
    const {selectedKey, operateIndex} = toJS(status);
    const formParams = newForm.getFormParams();
    let key = field.domkey[0], checkParams = {};
    if(key === "clazz" && selectedKey == 0) {
      checkParams = {
        tableName: 'Int_RegisterFilter',
        fieldName: `${key}_`,
        fieldValue: formParams[key].replace(/^(\s*)|(\s*)$/g, ''),
        idName: 'id',
        idValue: operateIndex
      };
      checkUnique(checkParams, newForm, key, '3', operateIndex);
    }else if(key === "exclude" && selectedKey == 1) {
      checkParams = {
        tableName: 'Int_WhiteList',
        fieldName: `${key}_`,
        fieldValue: formParams[key].replace(/^(\s*)|(\s*)$/g, ''),
        idName: 'id',
        idValue: operateIndex
      };
      checkUnique(checkParams, newForm, key, '4', operateIndex);
    }
  }

  /**
   * 对白名单的操作
   */
  operateWhiteList = (type, value) => {
    const {whiteListStore} = this.props;
    const {tableStore2, status: {operateIndex}} = whiteListStore;
    const {selectedRowKeys} = toJS(tableStore2);
    if(type === "add") {
      whiteListStore.getWhiteListMappingOperation({operation: "add", id: value[0], filter_id: operateIndex});
    }else if(type === "delete") {
      doConfirm(getLabel(385625, '确定要删除选择的记录吗？'), whiteListStore.getWhiteListMappingOperation, {operation: "delete", id: selectedRowKeys, filter_id: operateIndex});
    }
  }

  /**
   * 获取weasearchGroup上方的自定义按钮
   */
  getCustomComponent = () => {
    const {status, tableStore2} = this.props.whiteListStore;
    const {selectedRowKeys} = toJS(tableStore2);
    const {selectids} = toJS(status);
    let btn = [
      <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@ujsqm2@integrationWhitelistAddOrEditButtonwhitelist`}
        type="whitelist"
        customized
        title={getLabel('513388','选择白名单地址')}
        icon={GeneralTitleColor.icon}
        iconBgcolor={GeneralTitleColor.iconBgcolor}
        isSingle={false}
        memorise={true}
        replaceDatas={selectids}
        onChange={(...v) => this.operateWhiteList('add', v)}
      >
        <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@iyh7ie@integrationWhitelistAddOrEditButtonwhitelistaddBtn`} className="addBtn" buttonType='add' type="primary" />
      </WeaBrowser>,
      <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@7jz5gk@integrationWhitelistAddOrEditButtonwhitelistdeleteBtn`} onClick={() => this.operateWhiteList('delete')} buttonType='del' type="primary" disabled={selectedRowKeys.length === 0} />
    ];
    return <div className="inte-whitelist-register-dialog-custom-button">{btn}</div>
  }

   /**
   * 获取高级查询
   * @returns {Array}
   */
  getAdvancedSearch = () => {
    const {whiteListStore} = this.props;
    const {detailSearchForm, status} = whiteListStore;
    const {detailSearchFormCondition} = toJS(status);
    return getAdvancedItem(detailSearchForm, detailSearchFormCondition, this.onSearch, false, this && this.props && this.props.ecId || '', "integrationWhiteListAddOrEdit");
  };

  onSearch = () => {
    const {whiteListStore} = this.props;
    const {operateIndex} = toJS(whiteListStore.status);
    whiteListStore.getWhiteList({filter_id: operateIndex, isview: '1'});
    this.setState({showSearchAd: false});
  }

  getTabButtonsAd = () => {
    let resetFun = () => this.props.whiteListStore.detailSearchForm.reset();
    let cancelFun = () => this.setState({showSearchAd: false});
    return getSearchBtns(this.onSearch, resetFun, cancelFun, this && this.props && this.props.ecId || '', "integrationWhiteListAddOrEdit");
  }

  /**
   * 渲染的form内容
   */
  getContent = () => {
    const {whiteListStore} = this.props;
    const {status, newForm, tableStore2, detailSearchForm} = whiteListStore;
    const {selectedKey, newFormCondition, detailList, operateIndex, detailSearchFormCondition=[]} = toJS(status);
    const {showSearchAd} = this.state;
    const formParams = detailSearchForm.getFormParams();
    let advanceHeight = 0;
    if(detailSearchFormCondition) {
      try{
        advanceHeight = Math.ceil(detailSearchFormCondition[0].items.length/2)*72;
      }catch(err){}
    }
   
    return <div>
      {
        (selectedKey == 0 && detailList)
          ? null
          : newFormCondition.length > 1
            ? <div>
                {getForm(newForm, [newFormCondition[0]], true, this.handleChange, null, null, this && this.props && this.props.ecId || '', "integrationWhiteListForm")}
                {getDescription(newForm, [newFormCondition[1]], this && this.props && this.props.ecId || '', "integrationWhiteListForm")}
              </div> 
            : getForm(newForm, [newFormCondition[0]], selectedKey == 1 ? false : operateIndex ? true : false, this.handleChange, null, null, this && this.props && this.props.ecId || '', "integrationWhiteListForm")
      }
      {
        selectedKey == 1
          ? null
          : detailList
            ? <div>
                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@oxirxn`}
                  datas={[]}
                  selectedKey={'0'}
                  keyParam="viewcondition" 
                  searchType={['base', 'advanced']}
                  showSearchAd={showSearchAd}
                  setShowSearchAd={() => this.setState({showSearchAd: !showSearchAd})}
                  hideSearchAd={() => this.setState({showSearchAd: false})}
                  searchsAd={this.getAdvancedSearch()}
                  buttonsAd={this.getTabButtonsAd()}
                  advanceHeight={advanceHeight}
                  searchsBaseValue={formParams.exclude}
                  onSearch={this.onSearch}
                  onSearchChange={value => detailSearchForm.updateFields({exclude: value})} 
                />
                <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@jf0d2s`} 
                  comsWeaTableStore={tableStore2}
                  hasOrder={true}
                />
              </div>
            : operateIndex
              ? <div className="inte-whitelist-whitelist-custom"><WhiteList ecId={`${this && this.props && this.props.ecId || ''}_WhiteList@7iqzj4`} title={getLabel('513418','引用白名单地址')} /></div>
              : null
      }
    </div>
  }

  render () {
    const {whiteListStore} = this.props;
    const {status} = whiteListStore;
    const {addOrEditDialogVisible, dialogLoading, whiteListLoading} = toJS(status);

    return <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@gkycjh`}
      visible={addOrEditDialogVisible}
      title={this.getDialogTitle()}
      onCancel={()=> whiteListStore.setState({addOrEditDialogVisible: false})}
      style={{width: 800, height: 600}}
      hasScroll
      moduleName={GeneralTitleColor.moduleName}
      buttons={this.getBtns()}
      moreBtn={{
        datas: this.getRightMenu(),
        collectParams: []
      }}
    >
      {
        dialogLoading 
          ? <div style={{position: "relative", top: "50%"}}>
              <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@wmcrey`} spinning={dialogLoading}> </Spin>
            </div>
          : <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@2jsmee`}
              datas={this.getRightMenu()}
              collectParams={{}}
            >
              <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@kbd6bp`} spinning={whiteListLoading}>
                {this.getContent()}
              </Spin>
            </WeaRightMenu>
      }
    </WeaDialog>
  }
}