import {inject, observer} from "mobx-react";
import {Button} from "antd";
import {WeaLocaleProvider, WeaRightMenu, WeaTab, WeaTop} from "ecCom";
import {WeaLogView, WeaTableNew} from "comsMobx";
import NoRight from "../../public/NoRight";
import {
  getAdvancedItem,
  getSearchBtns,
} from "../../util/IntegrationUtil";
import AppEditDetailDialog from "./AppEditDetailDialog";

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

@inject("authenticationCenterStore")
@observer
class AuthenticationCenter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visiable: false,
      targetId: "",
      showSearchAd: false,
      searchType: ['base','advanced'],
      collectParams: {
        favname: getLabel('131607','应用管理'),
        favouritetype: 1,
        objid: 0,
        link: "wui/engine.html#/integration/appcenter",
        importantlevel: 1
      }
    };
  }

  componentDidMount() {
    const { authenticationCenterStore } = this.props;
    authenticationCenterStore.doAppCenterInit();
  }

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

  /**
   * 获取右键菜单
   * @returns {Array}
   */
  getRightMenu = () => {
    const {
      authenticationCenterStore,
    } = this.props, {
      status, 
      newForm, 
      tableStore,
    } = authenticationCenterStore, {
      rightMenus=[],
    } = status, {
      selectedRowKeys
    } = tableStore, {
      isuse, 
      token_isuse,
      oauth2_isuse,
      dlgt_isuse,
    } = newForm.getFormParams();

    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.menuIcon==='icon-coms-delete' && selectedRowKeys.length === 0) || (m.menuIcon === "icon-coms-New-Flow" && isuse == 0 && token_isuse == 0&& oauth2_isuse == 0&& dlgt_isuse == 0),
      }
    });
    //显示列定制
    btnArr.push({
      key: "BTN_COLUMN",
      icon: <i className="icon-coms-Custom" />,
      content: `${getLabel(32535, "显示列定制")}`,
      onClick: () => this.onRightMenuClick("BTN_COLUMN")
    });
    return btnArr;
  }

  /**
   * 获取顶部按钮
   * @returns {Array}
   */
  getBtns = () => {
    const {
      authenticationCenterStore,
    } = this.props, {
      status, 
      newForm, 
      tableStore,
    } = authenticationCenterStore, {
      rightMenus=[],
    } = status, {
      selectedRowKeys
    } = tableStore, {
      isuse, 
      token_isuse,
      oauth2_isuse,
      dlgt_isuse,
    } = newForm.getFormParams();

    return rightMenus && rightMenus.map(m => (
      <Button 
        ecId={`${this && this.props && this.props.ecId || ''}_Button@authApp${m.type}`} 
        type="primary" 
        disabled={(m.menuIcon==='icon-coms-delete' && selectedRowKeys.length === 0) || (m.menuIcon === "icon-coms-New-Flow" && isuse == 0 && token_isuse == 0&& oauth2_isuse == 0&& dlgt_isuse == 0)}
        onClick={() => this.onRightMenuClick(m.type)}
      >{m.menuName}</Button>
    ));
  };

  /**
   * 打开编辑弹窗
   */
  doEditDetailById = (record={}) => {
    const { authenticationCenterStore } = this.props;
    let tabIndex = record.tabIndex ? record.tabIndex : 0;
    
    authenticationCenterStore.setState({
      appEditFormDetailDialogVisible: true,
      registerAppId: record.id || "",
      editDetailDialogSelectedKey: tabIndex,
    });

    if("3" == tabIndex) {
      authenticationCenterStore.getRegisterAppLoginLogList({id: record.id});
    } else if("2" == tabIndex) {
      authenticationCenterStore.getRegisterAppDataMappingCondition({}, () => {
        authenticationCenterStore.getRegisterAppDataMappingInfo({id: record.id});
      });
    } else {
      authenticationCenterStore.getRegisterAppEditForm({id: record.id});  
    }
  }

  /**
   * 右键菜单点击事件
   * @param type
   */
  onRightMenuClick = (type, record) => {
    const {
      authenticationCenterStore,
    } = this.props, {
      tableStore, 
      confirmModal, 
      getRegisterAppOperation,
    } = authenticationCenterStore;
    let id = record ? record.id || "" : tableStore.selectedRowKeys || "";

    if(type == "rb_1") {
      authenticationCenterStore.getRegisterAppEditForm({id});
      authenticationCenterStore.setState({
        appEditFormDetailDialogVisible: true,
        registerAppId: "",
        editDetailDialogSelectedKey: "0",
      });
    } else if(type == "rb_2" || type == "1") {
      let title = getLabel(385625, '确定要删除选择的记录吗？');

      if(type == "1") {
        title = getLabel( 15097, '确定要删除吗？');
      }

      confirmModal(title, getRegisterAppOperation, {operation:'delete', id});
    } else if(type == "BTN_COLUMN") {
      //显示列定制
      tableStore.setColSetVisible(true);
      tableStore.tableColSet(true);
    } else if("0" === type) {
      // 编辑
      this.doEditDetailById({id});
    } else if("2" === type) {
      //数据映射
      this.doEditDetailById({id, tabIndex: 2});
    } else if("3" === type) {
      this.setState({visiable: true, targetId: id});
    } else if("4" === type) {
      // 运行日志
      this.doEditDetailById({id, tabIndex: 3});
    }
  };

  /**
   * 数据列表行数据的操作项
   * @param record
   * @param index
   * @param operate
   * @param flag
  */
  onOperatesClick = (record, index, operate) => this.onRightMenuClick(operate.index, record);

  getColumnsInfo = (datas=[]) => {
    return datas && datas.map(data => {
      if(data.dataIndex === "appid") {
        data.render = (text, record, index) => <a onClick={() => this.onRightMenuClick("0", record)}>{text}</a>;
      }

      return data;
    })
  }

  getAdvancedSearch = (form, datas=[]) => {
    return getAdvancedItem(
      form, 
      datas, 
      this.handleSearchFun, 
      true, 
      this && this.props && this.props.ecId || '', 
      "authAppIndex"
    );
  };

  handleSearchFun = () => {
    const { authenticationCenterStore } = this.props;
    authenticationCenterStore.getRegisterAppList();
    this.setState({ showSearchAd: false });
  }

  getTabButtonsAd = () => {
    const { authenticationCenterStore } = this.props;
    return getSearchBtns(
      this.handleSearchFun,
      () => authenticationCenterStore.appCenterForm.reset(),
      () => this.setState({ showSearchAd: false }),
      this && this.props && this.props.ecId || '',
      "authAppIndex",
    );
  }

  onCloseLogDialog = () => {
    this.setState({
      visiable: false,
      targetId: "",
    })
  };

  render() {
    const {authenticationCenterStore} = this.props;
    const {tableStore, hasRight, logStore, rightLoading, appCenterForm, status} = authenticationCenterStore;
    const {appCenterCondition, advanceHeight} = status;
    const {collectParams, showSearchAd=false, visiable, targetId, searchType} = this.state;

    return (
      rightLoading
        ? null
        : hasRight 
          ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@nb4xqe`}
              datas={this.getRightMenu()}
              collectParams={collectParams}
            >
              <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@wrg4ed`}
                title={getLabel('131607','应用管理')}
                icon={<i className="icon-coms-integration" />}
                iconBgcolor="#1a57a0"
                buttons={this.getBtns()}
                showDropIcon={true}
                dropMenuDatas={this.getRightMenu()}
                dropMenuProps={{collectParams}}
              >
                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@dqi4g7`} 
                  searchType={searchType}
                  searchsBaseValue={appCenterForm.getFormParams().appid}
                  advanceHeight={advanceHeight}
                  searchsAd={this.getAdvancedSearch(appCenterForm, appCenterCondition)}
                  buttonsAd={this.getTabButtonsAd()}
                  onSearch={this.handleSearchFun}
                  onSearchChange={value => appCenterForm.updateFields({appid: value})}
                  showSearchAd={showSearchAd}
                  setShowSearchAd={() => this.setState({ showSearchAd: !showSearchAd })}
                  hideSearchAd={() => this.setState({ showSearchAd: false })}
                />
                <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@1vilfa`}
                  comsWeaTableStore={tableStore}
                  hasOrder={true}
                  needScroll={true}
                  onOperatesClick={this.onOperatesClick}
                  getColumns={this.getColumnsInfo}
                />
              </WeaTop>
              <AppEditDetailDialog ecId={`${this && this.props && this.props.ecId || ''}_AppEditDetailDialog@d5h4fk`}/>
              <WeaLogViewComp 
                ecId={`${this && this.props && this.props.ecId || ''}_WeaLogViewComp@l1npy1`} 
                onCancel={this.onCloseLogDialog} 
                visible={visiable} 
                logStore={logStore} 
                logSmallType="92" 
                targetId={targetId} 
              />
            </WeaRightMenu>
          : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@jmntgm`}/>
    );
  }
}

export default AuthenticationCenter;
