import React from 'react';
import {inject, observer} from "mobx-react";
import {toJS} from "mobx";
import {Button, Spin} from "antd";
import {WeaLocaleProvider, WeaRightMenu, WeaTab, WeaTop} from "ecCom";
import {WeaLogView, WeaTableNew, WeaForm} from "comsMobx";
import isEmpty from 'lodash/isEmpty';
import NoRight from "../../public/NoRight";
import {GeneralTitleColor, menuIcon, doConfirm, getAdvancedItem, getSearchBtns} from "../../util/IntegrationUtil";
import AddOrEdit from './AddOrEdit';

const {WeaTable} = WeaTableNew;
const {getLabel} = WeaLocaleProvider;
const WeaLogViewComp = WeaLogView.Component;

@inject("whiteListStore")
@observer
export default class WhiteList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visiable:false,
      showSearchAd: false,
      targetId: '',
      topTab: [{
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(513383, "过滤器白名单")}`,
        viewcondition: 0
      }, {
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(513384, "通用白名单")}`,
        viewcondition: 1
      }],
      collectParams:{
        favname: getLabel(513382, "统一白名单地址配置"),
        favouritetype: 1,
        objid: 0,
        link: "wui/engine.html#/integration/whitelist",
        importantlevel: 1
      }
    };
  }

  componentDidMount() {
    const {whiteListStore} = this.props;
    whiteListStore.doInit();
  }

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

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

  onSearch = () => {
    const {whiteListStore} = this.props;
    const {status} = whiteListStore;
    const {selectedKey} = toJS(status);

    if(selectedKey == 0) {
      whiteListStore.getRegisterFilterList();
    }else if(selectedKey == 1) {
      whiteListStore.getWhiteList();
    }
    this.setState({showSearchAd: false});
  }

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

  /**
   * 获取右键按钮
   */
  getRightMenus = () => {
    const {whiteListStore} = this.props;
    const {rightMenus} = toJS(whiteListStore.status);
    const {selectedRowKeys} = toJS(whiteListStore.tableStore);
    let btnArr = rightMenus && rightMenus.map(m => {
      return {
        key: m.type,
        icon: <i className={m.menuIcon} />,
        content: m.menuName,
        onClick: () => this.onRightMenuClick(m.type),
        disabled:(m.type === 'rb_2' && selectedRowKeys.length === 0)
      };
    });
    //显示列定制
    btnArr.push({
      key: "BTN_COLUMN",
      icon: menuIcon.column,
      content: `${getLabel(32535, "显示列定制")}`,
      onClick: () => this.onRightMenuClick("BTN_COLUMN")
    });
    return btnArr;
  }

  /**
   * 获取顶部按钮
   */
  getBtns = () => {
    const {whiteListStore} = this.props;
    const {rightMenus} = toJS(whiteListStore.status);
    const {selectedRowKeys} = toJS(whiteListStore.tableStore);
    let btnArr = rightMenus && rightMenus.map(m => {
      return <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@tkrswf@integrationWhiteListButtonrb_2`} type="primary" disabled={m.type === 'rb_2' && selectedRowKeys.length === 0} onClick={() => this.onRightMenuClick(m.type)}>{m.menuName}</Button>
    })
    return btnArr;
  };

  /**
   * 事件menuClick
   */
  onRightMenuClick = (type, record) => {
    const {whiteListStore} = this.props;
    const {tableStore} = whiteListStore;
    const {selectedKey} = toJS(whiteListStore.status);
    const {selectedRowKeys} = toJS(tableStore);
    let selectedIndex = record ? record.randomFieldId : selectedRowKeys;
    if(type === "rb_1") {
      // 新建
      whiteListStore.setState({
        addOrEditDialogVisible: true,
        operateIndex: "",
        detailList: false
      })
      if(selectedKey == 0) {
        whiteListStore.getRegisterFilterForm();
      }else if(selectedKey == 1) {
        whiteListStore.getBaseInfoForm();
      }
    }else if(type == "0") {
      // 编辑
      let id = record.id;
      whiteListStore.setState({
        addOrEditDialogVisible: true,
        operateIndex: id,
        detailList: false
      })
      if(selectedKey == 0) {
        whiteListStore.getFilterFormInfo({id}, {filter_id: id, isview: '2'});
      }else if(selectedKey == 1) {
        whiteListStore.getBaseInfoForm({id});
      }
    }else if(["1", "rb_2"].includes(type)) {
      // 删除
      let content = type == "1" 
        ? getLabel(15097, '确定要删除吗？')
        : type === "rb_2"
          ? getLabel(385625, '确定要删除选择的记录吗？')
          : "";
      let func = selectedKey == 0
        ? whiteListStore.getRegisterFilterFormOperation
        : selectedKey == 1
          ? whiteListStore.getBaseInfoFormOperation
          : null;
      doConfirm(content, func, {id: selectedIndex, operation: 'delete'});
    }else if(type == "2") {
      // 日志
      let id = record.id;
      let logSmallType = selectedKey == 0
        ? 96
        : selectedKey == 1
          ? 95
          : "";
      this.setState({
        targetId: id,
        visiable: true,
        logSmallType
      })
    }else if(type === "detail") {
      // 过滤器查看详情
      let id = record.id;
      whiteListStore.setState({
        addOrEditDialogVisible: true,
        operateIndex: id,
        detailList: true
      });
      whiteListStore.detailSearchForm = new WeaForm();
      whiteListStore.getBaseInfoCondition();
      whiteListStore.getWhiteList({filter_id: id, isview: '1'});
    }else if(type == "BTN_COLUMN") {
      //显示列定制
      tableStore.setColSetVisible(true);
      tableStore.tableColSet(true);
    }
  };

  /**
   * 重新渲染列
   */
  getColumnsInfo = (data) => {
    const {selectedKey} = toJS(this.props.whiteListStore.status);
    if(!isEmpty(data)) {
      for(let index = 0; index < data.length; index++) {
        if(selectedKey == 0) {
          if(data[index].dbField == "name_") {
            data[index].render = (text, record, index) => {
              return (<a onClick={() => this.onRightMenuClick("0", record)}>{text}</a>);
            }
          }else if(data[index].dbField == "link_") {
            data[index].render = (text, record, index) => {
              if(record.link_span) {
                return (<a onClick={() => this.onRightMenuClick("detail", record)}>{record.link_span}</a>);
              }else {
                return null;
              }
            }
          }
        }else if(selectedKey == 1) {
          if(data[index].dbField == "exclude_") {
            data[index].render = (text, record, index) => {
              return (<a onClick={() => this.onRightMenuClick("0", record)}>{text}</a>);
            }
          }
        }
      }
    }
  }

  /**
   * 数据列表行数据的操作项
   * @param record
   * @param index
   */
  onOperatesClick = (record, index, operate) => {
    this.onRightMenuClick(operate.index, record);
  };  
  
  closeLogDialog = () => this.setState({visiable: false, targetId: ""});

  render() {
    const {whiteListStore} = this.props;
    const {tableStore, status, logStore, searchForm} = whiteListStore;
    const {selectedKey, hasRight, loading, addOrEditDialogVisible, advanceHeight} = toJS(status);
    const {collectParams, topTab, visiable, targetId, logSmallType, showSearchAd} = this.state;
    const formParams = searchForm.getFormParams();

    return loading
      ? <div style={{position: "relative", top: "50%"}}>
          <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@j2lv3b`} spinning={loading} size="large"> </Spin>
        </div>
      : (!hasRight)
        ? <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@fdl4xv`} />
        : <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@a6uar3`}
            datas={this.getRightMenus()}
            collectParams={collectParams}
          >
            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@l6fqmm`} 
              title={getLabel(513382, "统一白名单地址配置")}
              icon={GeneralTitleColor.iconDom}
              iconBgcolor={GeneralTitleColor.iconBgcolor}
              buttons={this.getBtns()}
              showDropIcon={true}
              dropMenuDatas={this.getRightMenus()}
              dropMenuProps={{collectParams}}
            />
            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@ir25wc`}
              datas={topTab}
              keyParam="viewcondition" 
              selectedKey={selectedKey}
              searchType={['base', 'advanced']}
              showSearchAd={showSearchAd}
              setShowSearchAd={() => this.setState({showSearchAd: !showSearchAd})}
              hideSearchAd={() => this.setState({showSearchAd: false})}
              searchsAd={this.getAdvancedSearch()}
              buttonsAd={this.getTabButtonsAd()}
              advanceHeight={advanceHeight}
              searchsBaseValue={selectedKey == 0 ? formParams.name : selectedKey == 1  ? formParams.exclude : ""}
              onSearch={this.onSearch}
              onSearchChange={value => {
                let key = selectedKey == 0 
                  ? "name" 
                  : selectedKey == 1 
                    ? "exclude"
                    : "";
                searchForm.updateFields({[key]: value})
              }} 
              onChange={v => {
                whiteListStore.searchForm = new WeaForm();
                if(v == 0) {
                  whiteListStore.getRegisterFilterInfo();
                }else if(v == 1) {
                  whiteListStore.getWhiteListInfo();
                }
                whiteListStore.setState({selectedKey: v});
              }}
            />
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@k2q43u`} 
              key={selectedKey}
              comsWeaTableStore={tableStore}
              hasOrder={true}
              needScroll={true}
              onOperatesClick={this.onOperatesClick}
              getColumns={this.getColumnsInfo}
            />
            {addOrEditDialogVisible && <AddOrEdit ecId={`${this && this.props && this.props.ecId || ''}_AddOrEdit@rk0xto`} />}
            <WeaLogViewComp ecId={`${this && this.props && this.props.ecId || ''}_WeaLogViewComp@fa9027`} 
              onCancel={this.closeLogDialog} 
              visible={visiable} 
              logStore={logStore} 
              logSmallType={logSmallType} 
              targetId={targetId}
            />
          </WeaRightMenu>
  }
}