import React from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import {WeaTableNew} from 'comsMobx';
import {WeaDialog, WeaLocaleProvider, WeaTab, WeaRightMenu, WeaHelpfulTip} from 'ecCom';
import * as IntegrationUtil from "../../util/IntegrationUtil";
import uuid from "uuid";

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

@inject("hrSyncStore")
@observer
export default class LogList extends React.Component {
  state = {
    selectedKey: 0,
    showSearchAd: false,
    key: '',
    errorTipDialogVisible: false, 
  }

  // 列表重定义列
  getColumns = (columns) => {
    let newColumns = '';

    newColumns = columns && columns.map(column => {
      let newColumn = column;
      newColumn.render = (text, record, index) => { //前端元素转义
        let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
        return (
          newColumn && newColumn.dataIndex === 'synDetail' 
            ? <a onClick={() => this.handleOpenDetailDialog(record.synDetail)} dangerouslySetInnerHTML={{__html: valueSpan}}/>
            : <div dangerouslySetInnerHTML={{__html: valueSpan}}/>
        )
      };
        return newColumn;
    });
    return newColumns;
  }

  handleOpenDetailDialog = (key) => {
    const { hrSyncStore } = this.props;
    const {getLogDetailList, getLogDetailListConditions, getLogTab} = hrSyncStore;
    let type = 0;
    // let type = dataSyncForm.getFormParams().type;
    
    this.setState({key});
    hrSyncStore.setState({detailDialogVisible: true});
    type != 0 ? getLogDetailListConditions({synId: key, synType: type}) : getLogDetailListConditions({synId: key, synType: type, synTypeTab: 1});
    type != 0 ? getLogDetailList({synId: key, synType: type}) : getLogDetailList({synId: key, synType: type, synTypeTab: 1});
    getLogTab({synId: key, synType: type});
  }

  // 同步日志的高级搜索框
  getSearchAd = () => {
    const {hrSyncStore} = this.props;
    const {detailSearchForm, status} = hrSyncStore;
    const {detailSearchFormCondition} = toJS(status);

    return IntegrationUtil.getAdvancedItem(
      detailSearchForm, 
      detailSearchFormCondition,
      this.onEnterSearch,
      false,
      this && this.props && this.props.ecId || '',
      "integrationHrSync",
    );
  }

  onEnterSearch = () => {
    const { hrSyncStore } = this.props;
    const {detailSearchForm} = hrSyncStore;
    const {key, selectedKey} = this.state;
    let type = 0;
    this.setState({ showSearchAd: false });
    type != 0 
      ? hrSyncStore.getLogDetailList({...detailSearchForm.getFormParams(), synId: key, synType: type}) 
      : hrSyncStore.getLogDetailList({...detailSearchForm.getFormParams(), synId: key, synType: type, synTypeTab: Number(selectedKey) + 1});
   
  }

  // 高级搜索上的按钮
  getTabButtonsAd = () => {
    const { hrSyncStore } = this.props;
    const {detailSearchForm} = hrSyncStore;
    return IntegrationUtil.getSearchBtns(
      this.onEnterSearch,
      () => detailSearchForm.reset(),
      () => this.setState({ showSearchAd: false }),
      this && this.props && this.props.ecId || '',
      "integrationHrSync",
    );
  }

  onSearch = (value) => {
    const { hrSyncStore } = this.props;
    const {detailSearchForm} = hrSyncStore;
    const {key, selectedKey} = this.state;
    let type = 0;

    detailSearchForm.updateFields({outpk: value});
    this.setState({ showSearchAd: false });
    type != 0 
      ? hrSyncStore.getLogDetailList({outpk: value, synId: key, synType: type})
      : hrSyncStore.getLogDetailList({outpk: value, synId: key, synType: type, synTypeTab: Number(selectedKey) + 1});
  }

  handleChangeTab = (v) => {
    const { hrSyncStore } = this.props;
    const {getLogDetailList, getLogDetailListConditions, getLogTab} = hrSyncStore;
    let type = 0;
    // let type = dataSyncForm.getFormParams().type;
    const {key} = this.state;

    this.setState({selectedKey: v, uid: uuid()});
    getLogDetailListConditions({synId: key, synType: type, synTypeTab: Number(v) + 1});
    getLogDetailList({synId: key, synType: type, synTypeTab: Number(v) + 1});
  }

  // 详细日志
  getDetailColumns = (columns) => {
    let newColumns = '';
    let resultStatus = [getLabel('25009','失败') , getLabel('83326','插入成功') , getLabel('31439','更新成功'), getLabel('20461','删除成功') , getLabel('502844','封存成功'), getLabel('502845','解封成功'), getLabel('127354','警告')];

    newColumns = columns && columns.map(column => {
      let newColumn = column;
      newColumn.render = (text, record, index) => { //前端元素转义
        let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
        let title = '';
        if(newColumn && newColumn.dataIndex === 'synState') {
          if([0, 6].indexOf(Number(record.synState)) != -1) {
            title = record.error.includes('#') ? getLabel(record.error.split('#')[0].trim(), '') : record.error;
          }
        } 
        return (
          newColumn && newColumn.dataIndex === 'synState' 
            ? ([0, 6].indexOf(Number(record.synState)) != -1 ? <nobr><a onClick={() => this.handleOpenErrorTip(record.randomFieldId, record.error)} dangerouslySetInnerHTML={{__html: resultStatus[Number(record.synState)]}}/>
              <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@rbzx6n@integrationHrsyncLogList${record.synState}`} style={{marginLeft: 10, marginTop: 1}} title={title} />
            </nobr>
            : <div dangerouslySetInnerHTML={{__html: resultStatus[Number(record.synState)]}}/>)
            : <div dangerouslySetInnerHTML={{__html: valueSpan}}/>
        )
      };
        return newColumn;
    });
    return newColumns;
  }

  handleOpenErrorTip = (key, error) => {
    this.props.hrSyncStore.getRealError({error: key});
  }

  render() {
    const { hrSyncStore } = this.props;
    const {logTableStore, status, logDetailTableStore, detailSearchForm} = hrSyncStore;
    const {detailDialogVisible, detailDialogTab, errorInfo, errorTipDialogVisible} = toJS(status);
    const {selectedKey, showSearchAd} = this.state;

    return (
      <div>
        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@g8lj6z`} 
          comsWeaTableStore={logTableStore}
          hasOrder={true}
          needScroll={true}
          getColumns={this.getColumns}
        />
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@kc7zqi`}
          icon={IntegrationUtil.GeneralTitleColor.icon}
          iconBgcolor={IntegrationUtil.GeneralTitleColor.iconBgcolor}
          visible={detailDialogVisible}
          onCancel={v => {hrSyncStore.setState({detailDialogVisible: false}), this.setState({
            selectedKey: 0,
            showSearchAd: false,
            key: '',
            errorTipDialogVisible: false
          })}}
          title={getLabel(501519, '同步详情')}
          style={{width: 900, height:700}}
          hasScroll
          buttons={[]}
          moreBtn={{
            datas: [],
            collectParams: [{
              favname: `${getLabel(33719, "HR同步")}`,
              favouritetype: 1,
              objid: 0,
              link: "wui/engine.html#/integration/hrsync",
              importantlevel: 1
            }]
          }}
        >
          <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@468qm9`}
            datas={[]}
            collectParams={[{
              favname: `${getLabel(33719, "HR同步")}`,
              favouritetype: 1,
              objid: 0,
              link: "wui/engine.html#/integration/hrsync",
              importantlevel: 1
            }]}
          >
            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@05ycm0`} 
              datas={detailDialogTab}
              keyParam="viewcondition"  
              selectedKey={selectedKey}
              searchType={['base', 'advanced']}
              searchsAd={this.getSearchAd()}
              buttonsAd={this.getTabButtonsAd()}
              showSearchAd={showSearchAd}
              advanceHeight={170}
              setShowSearchAd={bool=>{
                this.setState({
                  showSearchAd: bool
                })
              }}
              onChange={v => this.handleChangeTab(v)}
              onSearch={this.onSearch}
              onSearchChange={value => detailSearchForm.updateFields({outpk: value})}
              searchsBaseValue={detailSearchForm.getFormParams().outpk}
            />
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@opvwfc`} 
              selectedKey={this.state.uid}
              comsWeaTableStore={logDetailTableStore}
              hasOrder={true}
              // needScroll={true}
              getColumns={this.getDetailColumns}
            />
          </WeaRightMenu>
        </WeaDialog>
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@j98fht`}
          icon={IntegrationUtil.GeneralTitleColor.icon}
          iconBgcolor={IntegrationUtil.GeneralTitleColor.iconBgcolor}
          visible={errorTipDialogVisible}
          onCancel={v => this.props.hrSyncStore.setState({errorTipDialogVisible: false, errorInfo: ''})}
          title={getLabel('22045','详情')}
          style={{width: 400, height:200}}
          hasScroll
          buttons={[]}
          moreBtn={{
            datas: [],
            collectParams: [{
              favname: `${getLabel(33719, "HR同步")}`,
              favouritetype: 1,
              objid: 0,
              link: "wui/engine.html#/integration/hrsync",
              importantlevel: 1
            }]
          }}
        >
          <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@wq9zws`}
            datas={[]}
            collectParams={[{
              favname: `${getLabel(33719, "HR同步")}`,
              favouritetype: 1,
              objid: 0,
              link: "wui/engine.html#/integration/hrsync",
              importantlevel: 1
            }]}
          > 
            <div style={{paddingLeft:5, paddingRight: 5, overflow:'auto', width: 400, height: 200}}>
              <div dangerouslySetInnerHTML={{__html: errorInfo}} />
            </div>
          </WeaRightMenu>
        </WeaDialog>
      </div>
    )
  }
}