/**
 * @description 21.04.25 重构数据源功能
 * @author fyj
 */

import React from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { WeaTableNew, WeaLogView } from "comsMobx";
import { getSearchBtns, getAdvancedItem, GeneralTitleColor, findOriginFromRoute, showDeleteDataConfirmDialog } from "../../util/IntegrationUtil.js";
import {
  WeaLocaleProvider,
  WeaRightMenu,
  WeaTop,
  WeaTab,
  WeaLeftRightLayout,
} from "ecCom";
import { Button } from "antd";
import NoRight from "../../public/NoRight";
import CreateAndEdit from "./createAndEdit.js";
import OrganizationTree from '../../public/OrganizationTree';

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

@inject("dataSource")
@observer
export default class DataSource extends React.Component {

  state = {
    /** tabData, weatab 的 datas 属性值 */
    tabData: [
      {
        title: getLabel("32264", "数据源设置"),
        viewcondition: 0
      },
      {
        title: getLabel("129690", "数据库类型设置"),
        viewcondition: 1
      }
    ]
  }

  componentWillMount() {
    const {dataSource} = this.props;
    dataSource.source = findOriginFromRoute();
  }

  componentDidMount() {
    this.init();
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.location.key != this.props.location.key) {
      this.init();
    }
  }

  /**
   * 页面挂载后初始化数据，所有初始化的操作都在该方法中进行
   */
  init = () => {
    const { init } = this.props.dataSource;
    init();
  }

  // 分权刷新
  refreshData = (id, type) => {
    const {
      dataSource
    } = this.props, {
      datasourceAPI,
      tab,
    } = dataSource;

    // 如果点击的是分部
    dataSource.subcompanyid = ('1' === type ? id : '');
    if(tab.selectedKey == 0) {
      datasourceAPI().getListConditions(() => {
        dataSource.getList();
        datasourceAPI().getListRightMenus();
      });
    }
  }

  getTabButtonsAd = () => {
    const { dataSource } = this.props;
    const { searchAdvance } = dataSource;
    return getSearchBtns(
      this.handleSearchFun,
      () => searchAdvance.form.reset(),
      () => searchAdvance.show = false,
      this && this.props && this.props.ecId || '', 
      "integrationDatasource"
    );
  };

  getSearchAD = () => {
    const { dataSource } = this.props;
    const { form, conditions=[] } = dataSource.searchAdvance;
    return getAdvancedItem(
      form,
      toJS(conditions),
      this.handleSearchFun,
      false,
      this && this.props && this.props.ecId || '', 
      "integrationDatasource"
    );
  };

  /**
   * 获取删除按钮的 disabled 
   * @returns disabled 获取按钮的 disabled 状态
   */
  getBtnDisabledStatus = () => {
    const {
      dataSourceTable,
      dataSourceType,
      tab,
    } = this.props.dataSource;

    if (Number(tab.selectedKey) === 0) {
      return toJS(dataSourceTable.selectedRowKeys).length === 0;
    } else {
      return toJS(dataSourceType.table.selectedRowKeys).length === 0;
    }
  }

  getWeaTopBtns = () => {
    const { tab, dropMenuDatas } = this.props.dataSource;

    const disable = this.getBtnDisabledStatus();
    if (Number(tab.selectedKey) === 0) {
      return toJS(dropMenuDatas) && toJS(dropMenuDatas).map((item, i) => {
        if (i < 2) {
          if (item.type === "BTN_BatchDelete") {
            return (
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@q0kyli@integrationDataSourceButton${item.type}`} onClick={() => this.onRightMenuClick(item.type)} type="primary" disabled={disable}>
                {item.menuName}
              </Button>
            )
          } else {
            return (
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@k178fv@integrationDataSourceButton${item.type}`} onClick={() => this.onRightMenuClick(item.type)} type="primary">
                {item.menuName}
              </Button>
            )
          }
        }
      })
    }
    return [];
  }

  getDropMenuDatas = () => {
    const { dropMenuDatas, tab, source } = this.props.dataSource;
    const btnArr = [];
    
    toJS(dropMenuDatas) && toJS(dropMenuDatas).forEach((item, i) => {
      let disable = false;
      if (item.type === "BTN_BatchDelete") {
        disable = this.getBtnDisabledStatus();
      }
      if (Number(tab.selectedKey) === 1 && i<2) {
      }else{
        if(!(Number(tab.selectedKey) === 0 && source && item.type === "BTN_log")) {
          btnArr.push({
            key: item.type,
            icon: <i className={item.menuIcon} />,
            content: item.menuName,
            disabled: disable,
            onClick: () => this.onRightMenuClick(item.type)
          })
        }
      }
    })
    btnArr.push({
      key: "BTN_COLUMN",
      icon: <i className="icon-coms-Custom" />,
      content: `${getLabel(32535, "显示列定制")}`,
      onClick: () => this.onRightMenuClick("BTN_COLUMN")
    });
    return btnArr;
  }

  onRightMenuClick = (type, record) => {
    switch (type) {
      case "BTN_Insert":
        this.createTask();
        break;
      case "BTN_EDIT":
        this.doEditById(record);
        break;
      case "BTN_BatchDelete":
        this.deleteData('batch');
        break;
        case "BTN_DEL":
        this.deleteData('single', record);
        break;
      case "BTN_TEST":
        this.test(record);
        break;
      case "BTN_log":
        this.handleClickBtnLog(record);
        break;
      case "BTN_COLUMN":
        this.handleClickBtnColumn();
        break;
      case "BTN_DOWNLOAD":
        this.downloadDriver(record);
        break;
    }
  }

  /**
   * 下载驱动
   * @param {object} record 操作的当前数据
   */
  downloadDriver = (record) => {
    const driverfilename = record.driverfilename || '';

    if(isNaN(driverfilename)){
      window.location.href = (window.ecologyContentPath || "") + '/resource/DriverFile/'+driverfilename;
    }else{
      window.location.href = (window.ecologyContentPath || "") + "/weaver/weaver.file.FileDownload?fileid="+driverfilename+"&download=1";
    }
  }

  /**
   * 【编辑】按钮对应的事件
   * @param {object} record 
   */
  doEditById = (record) => {
    const { dataSourceCreateAndEdit, dataSourceType, getForm, tab } = this.props.dataSource;

    getForm({ id: record.id });
    if (Number(tab.selectedKey) === 0) {
      dataSourceCreateAndEdit.show = true;
      dataSourceCreateAndEdit.isEdit = true;
      dataSourceCreateAndEdit.editId = record.id;
    } else {
      dataSourceType.show = true;
      dataSourceType.isEdit = true;
      dataSourceType.editId = record.id;
    }
  };

  /**
   * 【测试】 按钮的对应事件
   */
  test = (record) => {
    const { datasourceAPI } = this.props.dataSource;

    datasourceAPI().listTest({ id: record.id });
  }

  /**
   * 【新建】按钮对应的事件
   */
  createTask = () => {
    const { dataSourceCreateAndEdit, dataSourceType, tab, getFormDataSource, getFormDataSourceType, datasourceAPI } = this.props.dataSource;

    if (Number(tab.selectedKey) === 0) {
      getFormDataSource({isEdit: "0"});
      datasourceAPI().getFormRightMenus({isEdit: "0"});
      dataSourceCreateAndEdit.isEdit = false;
      dataSourceCreateAndEdit.show = true;
    } else {
      getFormDataSourceType();
      dataSourceType.isEdit = false;
      dataSourceType.show = true;
    }
  };

  /**
   * 【批量删除】 按钮的对应事件
   */
  deleteData = (type, record) => {
    const {
      dataSourceTable,
      datasourceAPI,
      datasourcetypeAPI,
      dataSourceType,
      tab
    } = this.props.dataSource;

    showDeleteDataConfirmDialog(type)
      .then(() => {
        if (Number(tab.selectedKey) === 0) {
          if('single' === type) {
            datasourceAPI().delete({ pointids: record.pointid, id: record.id });
          } else {
            datasourceAPI().batchDelete({
              ids: toJS(dataSourceTable.selectedRowKeysAllPages)
            });
          }
        } else {
          if('single' === type) {
            datasourcetypeAPI().delete({ id: record.id });
          } else {
            datasourcetypeAPI().batchDelete({
              ids: toJS(dataSourceType.table.selectedRowKeysAllPages)
            });
          }
        }
      });
  };

  /**
   * 【日志】按钮的对应事件
   */
  handleClickBtnLog = (record = {id: ''}) => {
    const {
      toggleView,
      setOperateIndex
    } = this.props.dataSource;

    setOperateIndex(record.id);
    toggleView();
  }

  /**
   * 【显示列定制】按钮的对应事件
   */
  handleClickBtnColumn = () => {
    const {
      dataSourceType={},
      tab,
      dataSourceTable,
    } = this.props.dataSource;

    if (Number(tab.selectedKey) === 0) {
      dataSourceTable.setColSetVisible(true);
      dataSourceTable.tableColSet(true);
    } else {
      dataSourceType.table.setColSetVisible(true);
      dataSourceType.table.tableColSet(true);
    }
  }

  /**
   * 切换 tab 时调用的事件
   * @param {string} v 当前选中的 tab key
   */
  handleChangeTab = v => {
    const { dataSource } = this.props;
    const { tab, datasourceAPI } = dataSource;

    dataSource.subcompanyid = "";
    tab.selectedKey = Number(v);
    if(v == 0) {
      datasourceAPI().getListConditions(() => {
        dataSource.getList();
        datasourceAPI().getListRightMenus();
      });
    } else {
      dataSource.getList();
    }
  }

  /**
   * 快速搜索框输入值联动到 form 表单中
   * @param {string} v 快速搜索框输入的值
   */
  onSearchChange = v => {
    const { searchAdvance } = this.props.dataSource;
    searchAdvance.form.updateFields({pointid: v});
  }

  /**
   * 搜索事件
   */
  handleSearchFun = () => {
    const { dataSource } = this.props;

    dataSource.searchAdvance.show = false;
    dataSource.subcompanyid = dataSource.searchAdvance.form.getFormParams().subcomId;
    dataSource.getList(true); 
    dataSource.datasourceAPI().getListRightMenus();
  }

  /**
   * 设置高级搜索面板是否显示
   * @param {boolean} e 
   * @returns 
   */
  setShowSearchAd = e => this.props.dataSource.searchAdvance.show = e;

  /**
   * 隐藏高级搜索的面板
   * @returns 
   */
  hideSearchAd = () => this.props.dataSource.searchAdvance.show = false;

  /**
   * 每行数据的操作菜单
   * @param {object} record 
   * @param {number} recordIndex 
   * @param {object} operate 
   * @param {number} opertaeIndex 
   */
  onOperatesClick = (record, recordIndex, operate, opertaeIndex) => {
    const { tab } = this.props.dataSource;
    const arr = Number(tab.selectedKey) === 0 ? ['BTN_EDIT', 'BTN_DEL', 'BTN_TEST', 'BTN_log'] : ['BTN_EDIT', 'BTN_EDIT', 'BTN_DEL', 'BTN_DOWNLOAD', 'BTN_log'];
   
    this.onRightMenuClick(arr[Number(opertaeIndex)], record);
  };

  /**
   * 重新渲染列
   * @param {array} columns 列信息
   * @returns 
   */
  redoColumnsByName = columns => {
    const { tab, getTableList } = this.props.dataSource;

    return columns.map(column => {
      column.render = (text, record, index) => {
        //前端元素转义
        const valueSpan =
          record[column.dataIndex] !== undefined
            ? record[column.dataIndex]
            : record[column.dataIndex + "span"];
            
        switch (column.dataIndex.toString()) {
          case "pointid":
          case "dbtype":
            return (
              <a
                onClick={() => this.doEditById(record)}
                dangerouslySetInnerHTML={{ __html: valueSpan }}
              />
            );
          case "type":
            return (
              <a 
                onClick={() => {
                  tab.selectedKey = 1;
                  getTableList(true);
                  doEditById({id : record.dbtypeid});
                }}
              >
                {record.typespan}
              </a>
            );
          case 'subcompanyid':
            return (
              <a 
                href={`${window.ecologyContentPath || ""}/spa/hrm/engine.html#/hrmengine/organization?showTree=false&isView=1&type=subcompany&id=${record.subcompanyid}`} 
                target="_blank"
              >
                {record.subcompanyidspan}
              </a>
            );
          default:
            return (<div dangerouslySetInnerHTML={{ __html: valueSpan }} />);
        }
      };
      return column;
    });
  };

  /**
   * 渲染列表页面
   * @returns 渲染列表页面
   */
  getWhichTable = () => {
    const { tab, dataSourceTable, dataSourceType } = this.props.dataSource;

    return (
      <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@cejcez${tab.selectedKey}`}
        key={`table_${tab.selectedKey}`}
        hasOrder={true}
        onOperatesClick={this.onOperatesClick}
        comsWeaTableStore={1 === Number(tab.selectedKey) ? dataSourceType.table : dataSourceTable}
        needScroll={true}
        getColumns={this.redoColumnsByName}
      />
    );
  };

  render() {
    const { dataSource } = this.props;
    const {
      searchAdvance,
      tab,
      loading,
      logStore,
      logView,
      toggleView,
      rightLoading,
      operateIndex,
      hasOrganization,
      subcompanyid,
      hasManageDetachableRight,
    } = dataSource;
    const formParams = searchAdvance.form.getFormParams();

    return (rightLoading
      ? null
      : <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@m0qwze`} datas={(!hasManageDetachableRight && tab.selectedKey == 0) ? [] : this.getDropMenuDatas()}>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@6490e1`}
            loading={loading}
            buttons={(!hasManageDetachableRight && tab.selectedKey == 0) ? [] : this.getWeaTopBtns()}
            title={getLabel("32264", "数据源设置")}
            icon={<i className={GeneralTitleColor.icon} />}
            iconBgcolor={GeneralTitleColor.iconBgcolor}
            showDropIcon={true}
            dropMenuDatas={(!hasManageDetachableRight && tab.selectedKey == 0) ? [] : this.getDropMenuDatas()}
          />
          <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@wrom7f`}
            showLeft={tab.selectedKey != "1" && hasOrganization && hasManageDetachableRight}
            showBtn={tab.selectedKey != "1" && hasOrganization && hasManageDetachableRight}
            leftCom={<OrganizationTree ecId={`${this && this.props && this.props.ecId || ''}_OrganizationTree@sqv1g0`} 
              ref="dataSource"
              selectedKeys={[subcompanyid]}
              refreshData={this.refreshData}
              rightStr="intergration:datasourcesetting"
              {...(this.props.orgTreeParams || {})} 
            />}
          >
            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@uo2vuu`}
              buttonsAd={this.getTabButtonsAd()}
              searchsAd={this.getSearchAD()}
              advanceHeight={searchAdvance.advanceHeight}
              searchType={Number(tab.selectedKey) === 0 && hasManageDetachableRight && ["base, advanced"]}
              datas={this.state.tabData}
              keyParam="viewcondition" 
              selectedKey={tab.selectedKey}
              showSearchAd={searchAdvance.show}
              setShowSearchAd={this.setShowSearchAd}
              onChange={this.handleChangeTab}
              hideSearchAd={this.hideSearchAd}
              searchsBaseValue={formParams.pointid}
              onSearchChange={this.onSearchChange}
              onSearch={this.handleSearchFun}
            />
            {
              (!hasManageDetachableRight && tab.selectedKey == 0) 
                ? <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@oje60c`} />
                : this.getWhichTable()
            }
          </WeaLeftRightLayout>
          <WeaLogViewComp ecId={`${this && this.props && this.props.ecId || ''}_WeaLogViewComp@f27l2w`} onCancel={toggleView} visible={logView} logStore={logStore} logType="15"
            logSmallType={Number(tab.selectedKey) === 0 ? "2" : "3"}
            targetId={operateIndex}
          />
          <CreateAndEdit ecId={`${this && this.props && this.props.ecId || ''}_CreateAndEdit@3i7pyv`} />
        </WeaRightMenu>
    );
  }
}
