import React from "react";
import { 
  inject, 
  observer, 
} from "mobx-react";
import { 
  Button, 
} from "antd";
import {
  WeaLocaleProvider,
  WeaLeftRightLayout,
  WeaTop,
  WeaTab,
  WeaRightMenu,
} from "ecCom";
import { 
  WeaTableNew, 
  WeaLogView,
} from "comsMobx";
import {
  doConfirm, 
  getAdvancedItem,
  getSearchBtns,
} from "../../util/IntegrationUtil";
import NewForm from "./NewForm";
import NewE7Form from "./NewE7Form";
import NoRight from "../../public/NoRight";
import PreviewDialog from "./PreviewDialog";
import IndexTestDialog from "./IndexTestDialog";
import SqlTestDialog from "./SqlTestDialog";
import OrganizationTree from '../../public/OrganizationTree';
import CacheDataManage from "./CacheDataManage";

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

@inject("dataShowStore")
@observer
export default class DataShow extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      targetId: "",
      showSearchAd: false,
      searchType: ['base','advanced'],
      tabDatas: [{
        key: "0",
        title: getLabel("526043", "数据展现集成列表")
      }, {
        key: "1",
        title: getLabel("526044", "缓存管理")
      }],
    };
  }

  // 从NC等产品集成入口进来的数据
  componentWillMount() {
    const {dataShowStore} = this.props;
    let paramsIndex = location.href.trim() && location.href.trim().indexOf('?');
    if((paramsIndex != -1) && (location.href.trim().indexOf('typename') > paramsIndex) && (location.href.trim().indexOf('from=productEntrance') > paramsIndex)) {
      let url = location.href.split('?')[1];
      if(url) {
        let params = url.split('&');
        let query = {};
        for(let i = 0; i < params.length; i++) {
          query[params[i].split('=')[0]] = params[i].split('=')[1];
        }
        dataShowStore.source = (query.typename ? query.typename : "");
      }else {
        dataShowStore.source = "";
      }
    }else {
      dataShowStore.source = "";
    }
  }

  // 组件渲染后调用
  componentDidMount() {
    const { dataShowStore } = this.props;
    dataShowStore.doInit();
  }

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

  // 分权刷新
  refreshData = (id, type) => {
    const {
      dataShowStore
    } = this.props, {
      status,
    } = dataShowStore, {
      selectedKey,
    } = status;

    if("1" === type) {
      // 如果点击的是分部
      dataShowStore.setState({
        subcompanyid: id,  
      })
    } else{
      dataShowStore.setState({
        subcompanyid: "",  
      })
    }

    if(selectedKey == "1") {
      dataShowStore.getCacheManageCondition({}, dataShowStore.getCacheManageListInfo);
    } else {
      dataShowStore.getDataShowCondition({}, dataShowStore.getDataShowInfo);
    }
  }

  getBtns = () => {
    const { 
      dataShowStore, 
    } = this.props, {
      status,
      tableStore,
    } = dataShowStore, { 
      rightMenus,
      selectedKey,
      tabButtonDisabled,
    } = status, {
      selectedRowKeys
    } = tableStore;

    return rightMenus && rightMenus.map(m => <Button 
      ecId={`${this && this.props && this.props.ecId || ''}_Button@gb279a@integrationDatashowButton${m.type}`} 
      type="primary" 
      disabled={tabButtonDisabled || (selectedKey == "0" ? (m.menuIcon==='icon-coms-delete' && selectedRowKeys.length === 0) : this.getButtonSelectProps(m.type))} 
      onClick={() => this.onRightMenuClick(m.type)}
    >{m.menuName}</Button>);
  };

  getRightMenu = () => {
    const { 
      dataShowStore, 
    } = this.props, {
      status,
      tableStore,
    } = dataShowStore, { 
      rightMenus,
      selectedKey,
      tabButtonDisabled,
    } = status;

    let btnArr = rightMenus && rightMenus.map(m => {
      return {
        key: m.type,
        icon: <i className={m.menuIcon} />,
        content: m.menuName,
        onClick: () => this.onRightMenuClick(m.type),
        disabled: tabButtonDisabled || (selectedKey == "0" ? (m.menuIcon==='icon-coms-delete' && tableStore.selectedRowKeys.length === 0) : this.getButtonSelectProps(m.type)),
      };
    });
    //显示列定制
    btnArr.push({
      key: "BTN_COLUMN",
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(32535, "显示列定制"),
      onClick: () => this.onRightMenuClick("BTN_COLUMN")
    });
    return btnArr;
  }

  getButtonSelectProps = (type) => {
    const {
      dataShowStore,
    } = this.props, {
      tableStore,
    } = dataShowStore, {
      selectedRowKeys,
      datas,
    } = tableStore;
    let disabled = selectedRowKeys.length === 0, 
      list = [];

    if(!disabled) {
      selectedRowKeys && selectedRowKeys.forEach(key => {
        let data = datas && datas.find(data => data.randomFieldId === key);
        if(data) {
          if(list.indexOf(data.isopencache) == -1) {
            list.push(data.isopencache);
          }
        }
      })
      if(list.length > 1) {
        disabled = true;
      } else {
        return (type === "BTN_NEW" && list[0] == "1") || (type === "BTN_DEL" && list[0] == "0");
      }
    }

    return disabled;
  }

  onRightMenuClick = (type, record=null) => {
    const { 
      dataShowStore, 
    } = this.props, {
      tableStore,
      status,
      getDataShowCacheOperation,
      getCacheDataManageCondition,
      getCacheDataManageInfo,
    } = dataShowStore, {
      selectedKey,
    } = status;
    const operateKey = record ? record.id : tableStore.selectedRowKeys;

    if("0" == selectedKey) {
      if (type == "BTN_NEW") {
        dataShowStore.setState({showNewFormDialog: true});
        dataShowStore.getDataShowEditForm({id: ''});
      }else if (type == "BTN_DEL" || type == "2") {
        let ids = "", title = "";
        if(type == "2") {
          title = getLabel(15097, '确定要删除吗？');
          ids = record.id;
        } else {
          title = getLabel(385625, '确定要删除选择的记录吗？'); 
          ids = tableStore.selectedRowKeys;
        }
        doConfirm(
          title, 
          dataShowStore.getDataShowOperation, 
          {operator: 'delete', id: ids}
        );
      }else if (type == "0") {
        dataShowStore.setState({type: 'INDEX_TEST'});
        dataShowStore.getIndexTest(record.id);
      }else if (type == "1") {
        if(record.browserfrom == '0') {
          dataShowStore.getDataShowEditForm4E7({id: record.id, browserid:record.showname});
          dataShowStore.setState({showNewE7FormDialog: true});
        }else {
          dataShowStore.getDataShowEditForm({id: record.id});
          dataShowStore.setState({showNewFormDialog: true});
        }
      }
    } else if ("1" == selectedKey) {
      if("0" == type || "BTN_NEW" == type) {
        // 开启缓存
        let title = '';
        if('0' == type) {
          title = `${getLabel('529052','确定开启缓存吗')}？`;
        } else {
          title = `${getLabel('529054','确定要开启选择的记录的缓存吗')}？`; 
        }
        doConfirm(
          title, 
          getDataShowCacheOperation, 
          {operate: "openCache", id: operateKey}
        );
      } else if("1" == type || "BTN_DEL" == type) {
        // 关闭缓存
        let title = '';
        if('1' == type) {
          title = `${getLabel('529051','确定关闭缓存吗')}？` ;
        } else {
          title = `${getLabel('529053','确定要关闭选择的记录的缓存吗')}？`; 
        }
        doConfirm(
          title, 
          getDataShowCacheOperation, 
          {operate: "closeCache", id: operateKey}
        );
      } else if("2" == type) {
        // 缓存数据管理
        dataShowStore.setState({
          cacheDataManageVisible: true,
          cacheDataOperateInfo: record,
        })
        getCacheDataManageCondition({}, getCacheDataManageInfo);
      } else if("3" == type) {
        // 系统日志
        this.setState({
          visible: true,
          targetId: record ? record.id : "",
        })
      }
    }

    if (type == "BTN_COLUMN") {
      tableStore.setColSetVisible(true);
      tableStore.tableColSet(true);
    }
  };

  getAdvancedSearch = () => {
    const { 
      dataShowStore,
    } = this.props, {
      searchForm,
      status,
    } = dataShowStore, {
      dataShowConditionInfo
    } = status;
    return getAdvancedItem(searchForm, dataShowConditionInfo, this.handleSearchFun, false, this && this.props && this.props.ecId || '', "integrationDatashow");
  };

  handleSearchFun = () => {
    const {
      dataShowStore,
    } = this.props, {
      status,
      searchForm,
    } = dataShowStore, {
      selectedKey,
    }= status;

    dataShowStore.setState({
      subcompanyid: searchForm.getFormParams().subcompanyid1,
    });

    if(selectedKey == "1") {
      dataShowStore.getCacheManageListInfo();
    } else {
      dataShowStore.getDataShowInfo();
    }

    this.setState({ showSearchAd: false });
  }

  getTabButtonsAd = () => {
    return getSearchBtns(
      this.handleSearchFun,
      () => this.props.dataShowStore.searchForm.reset(),
      () => this.setState({ showSearchAd: false }),
      this && this.props && this.props.ecId || '', 
      "integrationDatashow"
    );
  }

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

  getColumnsInfo = (datas=[]) => {
    const {selectedKey} = this.props.dataShowStore.status;

    return datas && datas.map(item => {
      if("0" == selectedKey) {
        if("id" === item.dataIndex) {
          item.render = (text, record) => <a onClick={() => this.onRightMenuClick("1", record)}>{record.showname}</a>;
        } else if(["unconditionalQuery", "physicalPaging", "isPhyPage"].includes(item.dataIndex)) {
          item.render = (text, record) => <span style={{color: record[item.dataIndex] == "1" ? "green" : "black"}}>{record[`${item.dataIndex}span`] || record[item.dataIndex]}</span>;
        }
      }

      if("subcompanyid" === item.dataIndex) {
        item.render = (text, record) => <a href={`${window.ecologyContentPath || ""}/spa/hrm/engine.html#/hrmengine/organization?showTree=false&isView=1&type=subcompany&id=${record.subcompanyid}`} target="_blank">{record.subcompanyidspan}</a>;
      }

      return item;
    })
  }

  setShowSearchAd = (bool) => this.setState({showSearchAd: bool});

  hideSearchAd = () => this.setState({showSearchAd: false});

  onSearchChange = value => {
    const {
      dataShowStore,
    } = this.props, {
      searchForm,
      status,
    } = dataShowStore, {
      selectedKey,
    } = status;

    searchForm.updateFields({[selectedKey == "0" ? "name" : "showname"]: value})
  };

  getSearchBaseValue = () => {
    const {
      dataShowStore,
    } = this.props, {
      searchForm,
      status,
    } = dataShowStore, {
      selectedKey,
    } = status;

    const formParams = searchForm.getFormParams();

    return selectedKey == "0" ? formParams.name : formParams.showname;
  }

  onChange = (selectedKey) => {
    const {
      dataShowStore,
    } = this.props;

    if(selectedKey == "1") {
      dataShowStore.getCacheManageCondition({}, dataShowStore.getCacheManageListInfo);
    } else {
      dataShowStore.getDataShowCondition({}, dataShowStore.getDataShowInfo);
    }

    dataShowStore.setState({selectedKey});
  }

  // 关闭日志弹窗
  closeLogDialog = () => {
    this.setState({
      visible: false,
      targetId: "",
    })
  }

  render() {
    const { 
      dataShowStore, 
    } = this.props, {
      tableStore,
      status,
      hasRight, 
      rightLoading,
      logStore,
    } = dataShowStore, {
      advanceHeight,
      showTestFormDialog,
      showsSqlTextFormDialog,
      showIndexTestDialog,
      collectParams,
      hasOrganization,
      subcompanyid,
      selectedKey,
    } = status, {
      showSearchAd,
      searchType,
      tabDatas=[],
      visible,
      targetId,
    } = this.state;

    return (rightLoading
      ? null 
      : hasRight
        ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@z97us9`}
            datas={this.getRightMenu()}
            collectParams={collectParams}
          >
            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@uccb1l`}
              title={getLabel(32303, "数据展现集成")}
              icon={<i className="icon-coms-integration" />}
              iconBgcolor="#1a57a0"
              buttons={this.getBtns()}
              showDropIcon={true}
              dropMenuDatas={this.getRightMenu()}
              dropMenuProps={{collectParams}}
            />
            <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@uitgs3`}
              showLeft={hasOrganization}
              showBtn={hasOrganization}
              leftCom={<OrganizationTree ecId={`${this && this.props && this.props.ecId || ''}_OrganizationTree@le35kt`} 
                ref="datashow"
                refreshData={this.refreshData}
                selectedKeys={[subcompanyid]}
                rightStr={"integration:datashowset"}
              />}
            >
              <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@0mlh6h`}
                datas={tabDatas}
                keyParam="key" 
                selectedKey={selectedKey}
                searchType={searchType}
                searchsBaseValue={this.getSearchBaseValue()}
                advanceHeight={advanceHeight}
                searchsAd={this.getAdvancedSearch()}
                showSearchAd={showSearchAd}
                buttonsAd={this.getTabButtonsAd()}
                setShowSearchAd={this.setShowSearchAd}
                hideSearchAd={this.hideSearchAd}
                onSearch={this.handleSearchFun}
                onSearchChange={this.onSearchChange}
                onChange={this.onChange}
              />
              <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@fqqf7f`}
                comsWeaTableStore={tableStore}
                hasOrder={true}
                needScroll={true}
                onOperatesClick={this.onOperatesClick}
                getColumns={this.getColumnsInfo}
              />
            </WeaLeftRightLayout>
            <NewForm ecId={`${this && this.props && this.props.ecId || ''}_NewForm@k3560j`} />
            <NewE7Form ecId={`${this && this.props && this.props.ecId || ''}_NewE7Form@bxxfhs`} />
            <SqlTestDialog ecId={`${this && this.props && this.props.ecId || ''}_SqlTestDialog@w6ugu7`} showSqlDialog={showsSqlTextFormDialog}/>
            <PreviewDialog ecId={`${this && this.props && this.props.ecId || ''}_PreviewDialog@un1blg`} showDialog={showTestFormDialog}/>
            <IndexTestDialog ecId={`${this && this.props && this.props.ecId || ''}_IndexTestDialog@q0vvwn`} showTestVersion={showIndexTestDialog}/>
            <CacheDataManage ecId={`${this && this.props && this.props.ecId || ''}_CacheDataManage@2rpraa`} />
            <WeaLogViewComp ecId={`${this && this.props && this.props.ecId || ''}_WeaLogViewComp@gbkt78`} 
              logStore={logStore} 
              logType="15" 
              logSmallType="94"
              targetId={targetId}
              visible={visible} 
              onCancel={this.closeLogDialog} 
            />
          </WeaRightMenu>
        : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@030ywc`}/>
    );
  }
}