import React from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import NoRight from "../../public/NoRight";
import NonStand from "../../public/NonStand";
import { Button, Modal, Icon, message, } from "antd";
import { WeaUpload, WeaTable, WeaDialog, WeaTableEditable, WeaTools, WeaHelpfulTip, WeaLocaleProvider, WeaRightMenu, WeaTab, WeaTop, WeaFormItem, WeaSearchGroup, WeaNewScroll } from "ecCom";
import { WeaSwitch, WeaForm } from "comsMobx";
import SyncSetFields from "./partial/SyncSetFields";
import LogList from './LogList';
import * as IntegrationUtil from "../../util/IntegrationUtil";
import "./style/index.less"

const { getKey } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;

@inject("hrSyncStore")
@observer
class HrSync extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      syncTableTab: "0",
      hasSyncClick: false,
      file: [],
      filelist: [],
      sync: true,
      topTab: [
        {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(32783, "集成设置")}`,
          viewcondition: 0
        },
        {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(82923, "数据同步")}`,
          viewcondition: 1
        },
        {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(125928, "同步日志")}`,
          viewcondition: 2
        }
      ]
    }
  }

  componentDidMount() {
    const { hrSyncStore } = this.props;
    hrSyncStore.setState({selectedKey: 0});
    hrSyncStore.doInit();
  }

  componentWillReceiveProps(nextProps) {
    const { hrSyncStore } = this.props;
    if (this.props.location.key !== nextProps.location.key) {
      hrSyncStore.setState({selectedKey: 0});
      hrSyncStore.doInit();
    }
  }

  getFormSearchs = (form, datas, needTigger = true, lableCol, fieldcol) => {
    const { isFormInit } = form;
    const { hrSyncStore } = this.props;
    const {getHrSyncSettingsOperation, status, webserviceParamValuesData, setWebserviceParamValuesData} = hrSyncStore;
    const { WeaTableEdit_WebserviceParameterSet, } = toJS(status);
    let group = [];
    let className="";
    const formParams = form.getFormParams();
    isFormInit && datas && datas.map((c, index) => {
      // render webService WeaTab 同步接口方法
      const { intetype } = form.getFormParams();
      if ([2].includes(index) && intetype === "2") {
        const tabs = c.items.map((item, index) => {
          return {
            color: "#000000",
            groupid: "flowAll",
            showcount: true,
            title: item.label,
            viewcondition: index
          };
        })
        // webService WeaTab
        group.push(<div>
          <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@h9mas3@integrationHrsyncForm${index}`}
            datas={tabs}
            type="card"
            keyParam="viewcondition" 
            selectedKey={this.state.syncTableTab}
            onChange={v => this.setState({ syncTableTab: v })}
          />
        </div>)
      }
      // render 基本信息 同步表设置 同步对应字段设置方法
      let center = true;
      if (index === 1) {
        center = false;
      }
      let items = [];
      // condition
      c.items.map((fields, cIndex) => {
        let onChange = (e) => { };
        // 同步表设置
        // subcomtable  depttable jobtable hrmtable

        if (["subcomouternew"].includes(getKey(fields))) {
            className="hr-syn-table-setting";
            fields.dataParams = {
                mouldID: "integration", callSource: "hrsetting",
                dmltablename: formParams["subcomtable"],
                datasourceid: formParams["dbsource"],
            }
        }
        if (["deptouternew"].includes(getKey(fields))) {
            className="hrsync-tablesetting";
            fields.dataParams = {
                mouldID: "integration", callSource: "hrsetting",
                dmltablename: formParams["depttable"],
                datasourceid: formParams["dbsource"]
            }
        }
        if (["jobouternew"].includes(getKey(fields))) {
            className="hrsync-tablesetting";
            fields.dataParams = {
                mouldID: "integration", callSource: "hrsetting",
                dmltablename: formParams["jobtable"],
                datasourceid: formParams["dbsource"]
            }
        }
        if (["hrmouternew"].includes(getKey(fields))) {
            className="hrsync-tablesetting";
            fields.dataParams = {
                mouldID: "integration", callSource: "hrsetting",
                dmltablename: formParams["hrmtable"],
                datasourceid: formParams["dbsource"]
            }
        }

        // WEBSERVICE地址 select onchange
        if (getKey(fields) === "webserviceurl") {
          onChange = (e) => {
            getHrSyncSettingsOperation({ operation: "getregisteinfo", webserviceurl: e.webserviceurl.value }, res => {
              // update fields
              // subcommothod deptmothod jobmothod hrmmethod
              status.newFormFields[2].items.forEach(item => {
                item.options = res.webserviceMethodsList;
              })
            });
            // 清空接口方法
            form.updateFields({
              subcommothod: "",
              deptmothod: "",
              jobmothod: "",
              hrmmethod: ""
            })
            // 清空接口方法对应的数据
            webserviceParamValuesData.subWebserviceParamValuesData = [];
            webserviceParamValuesData.deptWebserviceParamValuesData = [];
            webserviceParamValuesData.jobWebserviceParamValuesData = [];
            webserviceParamValuesData.hrmWebserviceParamValuesData = [];
          }
          // 同步接口方法
        } else if (["subcommothod", "deptmothod", "jobmothod", "hrmmethod"].includes(getKey(fields))) {
          onChange = (e) => {
            getHrSyncSettingsOperation({ operation: "getmethodinfo", methodid: e[Object.keys(e)[0]]["value"] }, res => {
              const { webserviceParamValuesData } = hrSyncStore;
              setWebserviceParamValuesData(this.state.syncTableTab, res.WebserviceMethodParameterDatas);
            });
          }
        } else if (["syncmethodHz"].includes(getKey(fields))) {
          fields.otherParams = {
            valueIsObject: true
          }
        }
        items.push({
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@8yfhhe@integrationHrsyncForm${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{ span: lableCol ? lableCol : `${fields.labelcol}` }}
              wrapperCol={{ span: fieldcol ? fieldcol : `${fields.fieldcol}` }}
              error={form.getError(fields)}
              fieldType={fields.conditionType.toUpperCase()}
              tipPosition="bottom"
            > 
              <nobr>
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@rrm1ra@integrationHrsyncForm${fields.domkey[0]}`} onChange={onChange} fieldConfig={fields} form={form} formParams={formParams} />
                {getKey(fields) === 'defaultPwd' && <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@ksl6pv@integrationHrsyncForm${fields.domkey[0]}`} style={{marginLeft: 13, top: 5}} title={getLabel(501544, '默认密码只在同步新增用户时使用')} width={195} />}
              </nobr>
            </WeaFormItem>),
          col: 2,
          hide: form.isHide(fields, (keys, allParams) => {
            switch (getKey(fields)) {
              // 集成方式 数据库
              case "dbsource":
                return allParams["intetype"] !== "1";
              // 集成方式 接口方式
              case "webserviceurl":
                return allParams["intetype"] !== "2";
              // 集成方式 自定义
              case "custominterface":
                return allParams["intetype"] !== "3";
              case "defaultPwd":
              case "pwdsynctype":
              case "issynrtx":
                return allParams["intetype"] === "3";
              case "subcommothod":
                return this.state.syncTableTab !== "0";
              case "deptmothod":
                return this.state.syncTableTab !== "1";
              case "jobmothod":
                return this.state.syncTableTab !== "2";
              case "hrmmethod":
                return this.state.syncTableTab !== "3";
              case "syncmethodHz":
                return allParams["hrmethod"] === '1';
            }
            return false;
          })
        })
      });
      let title = "";
      if (needTigger) {
        const intetype = form.getFormParams().intetype;
        // 集成方式 数据库
        if (intetype === "1" && [2].includes(index)) {
          title = "";
          items = [];
        } else if (intetype === "2" && [1].includes(index)) {
          // 集成方式 接口方式
          title = "";
          items = [];
        } else if (intetype === "3" && index !== 0) {
          // 集成方式 自定义方式
          title = "";
          items = [];
        } else {
          title = c.title;
        }
        // remove 同步接口方法 title
        if ([2].includes(index)) {
          needTigger = false;
          title = "";
        }
        group.push(<WeaSearchGroup className={className} ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@ymty5p@integrationHrsyncForm${index}`} center={center} col={1} needTigger={needTigger} title={title} showGroup={c.defaultshow} items={items} />)
      } else {
        group.push(<WeaSearchGroup className={className} ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@w1559x@integrationHrsyncForm${index}`} center={center} col={1} needTigger={needTigger} showGroup={c.defaultshow} items={items} />)
      }

      // WEBSERVICE 明细表 table
      if ([2].includes(index) && intetype === "2") {
        const whichData = [
          webserviceParamValuesData.subWebserviceParamValuesData,
          webserviceParamValuesData.deptWebserviceParamValuesData,
          webserviceParamValuesData.jobWebserviceParamValuesData,
          webserviceParamValuesData.hrmWebserviceParamValuesData,
        ];
        group.push(
          <div>
            <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@7pg98t@integrationHrsyncForm${index}`}
              rowKey="paramid"
              getRowSelection={() => {
                return false;
              }}
              showTitle={false}
              tableProps={{
                showEmptyText: false,
                scroll: { x: "100%" }
              }}
              datas={toJS(whichData[this.state.syncTableTab])}
              columns={WeaTableEdit_WebserviceParameterSet}
              onChange={(datas) => {
                switch (Number(this.state.syncTableTab)) {
                  case 0:
                    webserviceParamValuesData.subWebserviceParamValuesData = datas;
                    break;
                  case 1:
                    webserviceParamValuesData.deptWebserviceParamValuesData = datas;
                    break;
                  case 2:
                    webserviceParamValuesData.jobWebserviceParamValuesData = datas;
                    break;
                  case 3:
                    webserviceParamValuesData.hrmWebserviceParamValuesData = datas;
                    break;
                }
              }}
            />
          </div>
        )
      }
    });
    return group;
  }

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

    return IntegrationUtil.getAdvancedItem(logSearchForm, logSearchFormCondition, this.searchFun, false, this && this.props && this.props.ecId || '', "integrationHrSyncIndex");
  }

  searchFun = () => {
    const { hrSyncStore } = this.props;
    const {logSearchForm} = hrSyncStore;
    hrSyncStore.getLogList(logSearchForm.getFormParams());
    hrSyncStore.setState({ showSearchAd: false });
  };

  getTabButtonsAd() {
    const { hrSyncStore } = this.props;
    const {logSearchForm} = hrSyncStore;
    let resetFun = () => logSearchForm.reset();
    let cancelFun = () => hrSyncStore.setState({showSearchAd: false});

    return IntegrationUtil.getSearchBtns(this.searchFun, resetFun, cancelFun, this && this.props && this.props.ecId || '', "integrationHrSyncIndex");
  }

  /**
   * 获取右键菜单
   * @returns {Array}
   */
  getRightMenu() {
    const { hrSyncStore } = this.props;
    const {newForm, initialNewForm} = hrSyncStore;
    const { selectedKey, rightMenus, rightMenusTab2, rowSelectIds, canexport, syncFlag, saveDisabled } = toJS(hrSyncStore.status);
    const whichRightMenu = Number(selectedKey) === 0 ? rightMenus : Number(selectedKey) === 1 ? rightMenusTab2 : '';

    let btnArr = [];
    whichRightMenu && whichRightMenu.map(m => {
      let btn = {
        key: m.type,
        icon: <i className={m.menuIcon} />,
        content: m.menuName,
        onClick: () => this.onRightMenuClick(m.type)
      };
      if (m.type == "BTN_EXP") {
        if (!canexport) {
          btn.disabled = true;
        } else {
          btn.disabled = false;
        }
      }else if(m.type == 'BTN_EXPDATA') {
        btn.disabled = !this.state.hasSyncClick;
      }else if(m.type == 'BTN_SYNC') {
        btn.disabled = syncFlag;
      }else if(m.type === "BTN_SAVE") {
        btn.disabled = saveDisabled;
      }
      if (!(m.menuIcon === 'icon-coms-delete' && rowSelectIds.length === 0)) {
        btnArr.push(btn);
      }
    });
    if (selectedKey === "1") {
      if (initialNewForm.getFormParams()["isuselhr"] === "0"){
        return [];
      }
      if (initialNewForm.getFormParams()["hrmethod"] === "2") {
        return [];
      }
      if(this.state.sync == false) {
        return [];
      }
    }

    if(selectedKey === '2') {
       // 添加列定制
      btnArr.push({
        key: "BTN_COLUMN",
        icon: <i className="icon-coms-Custom" />,
        content: `${getLabel(32535, "显示列定制")}`,
        onClick: () => this.onRightMenuClick("BTN_COLUMN")
      });
    }

    return btnArr;
  }

  getRightMenu2() {
    const { hrSyncStore } = this.props;
    const { importForm, getHrSyncSettingsOperation } = hrSyncStore;
    const { selectedKey, rightMenus, rightMenusTab2, rowSelectIds } = toJS(
      hrSyncStore.status
    );
    let btnArr = [];
    var btn = {
      key: 'aaa',
      icon: <i className={"icon-coms-File"} />,
      content: getLabel("725", "提交"),
      onClick: () => {
        this.doImport();
      }
    };
    btnArr.push(btn);

    return btnArr;
  }

  doImport() {
    const { hrSyncStore } = this.props;
    const { importForm, getHrSyncSettingsOperation } = hrSyncStore;
    const { selectedKey, rightMenus, rightMenusTab2, rowSelectIds } = toJS(
      hrSyncStore.status
    );
    let params = Object.assign({ operation: "import" }, importForm.getFormParams());
    params.file = JSON.stringify(this.state.file);
    params.filelist = JSON.stringify(this.state.filelist);
    IntegrationUtil.onCheck(importForm, () => {
      getHrSyncSettingsOperation(params, () => {
        hrSyncStore.setState({ showImportForm: false });
        hrSyncStore.doInit();
        this.setState({filelist:[]});
      })
    })
  }

  /**
   * 右键菜单点击事件
   * @param type
   */
  getAllPrams = () => {
    const { hrSyncStore } = this.props;
    const { newForm, SyncSetTable, webserviceParamValuesData } = hrSyncStore;
    const params = newForm.getFormParams();
    // 明细表数据
    // webservice 明细表
    const {
      subWebserviceParamValuesData,
      deptWebserviceParamValuesData,
      jobWebserviceParamValuesData,
      hrmWebserviceParamValuesData
    } = toJS(webserviceParamValuesData);
    const {
      WeaTableEdit_subSyncFieldData,
      WeaTableEdit_deptSyncFieldData,
      WeaTableEdit_jobSyncFieldData,
      WeaTableEdit_hrmSyncFieldData } = toJS(SyncSetTable);

    const New_WeaTableEdit_jobSyncFieldData = ((params.intetype == 1 && params.jobtable == '') || (params.intetype == 2 && params.jobmothod == "")) ? [] : WeaTableEdit_jobSyncFieldData;
    const allParams = {
      ...params,
      isUnique: true,
      subWebserviceParamValuesData: JSON.stringify(subWebserviceParamValuesData),
      deptWebserviceParamValuesData: JSON.stringify(deptWebserviceParamValuesData),
      jobWebserviceParamValuesData: JSON.stringify(jobWebserviceParamValuesData),
      hrmWebserviceParamValuesData: JSON.stringify(hrmWebserviceParamValuesData),
      WeaTableEdit_subSyncFieldData: JSON.stringify(WeaTableEdit_subSyncFieldData),
      WeaTableEdit_deptSyncFieldData: JSON.stringify(WeaTableEdit_deptSyncFieldData),
      WeaTableEdit_jobSyncFieldData: JSON.stringify(New_WeaTableEdit_jobSyncFieldData),
      WeaTableEdit_hrmSyncFieldData: JSON.stringify(WeaTableEdit_hrmSyncFieldData)
    };

    [WeaTableEdit_subSyncFieldData, WeaTableEdit_deptSyncFieldData, New_WeaTableEdit_jobSyncFieldData, WeaTableEdit_hrmSyncFieldData].map(datas => {
      let allConfig = '';
      
      datas && datas.map(data => {
        if (allConfig.indexOf(`(#@#)${data.oafieldspan}(#@#)`) < 0) {
          allConfig += `(#@#)${data.oafieldspan}(#@#)`;
        } else {
            Modal.warning({
              title: getLabel("15172", "系统提示"),
              content: getLabel('389520',"存在重复属性，请检查")
            })
            allParams.isUnique = false;
            return
        }
      })
    })

    const WebserviceParamValuesData = []
      .concat(subWebserviceParamValuesData.map(item => ({ methodtype: 1, ...item })))
      .concat(deptWebserviceParamValuesData.map(item => ({ methodtype: 2, ...item })))
      .concat(jobWebserviceParamValuesData.map(item => ({ methodtype: 3, ...item })))
      .concat(hrmWebserviceParamValuesData.map(item => ({ methodtype: 4, ...item })));
    const syncFieldData = []
      .concat(WeaTableEdit_subSyncFieldData.map(item => ({ type: 1, ...item })))
      .concat(WeaTableEdit_deptSyncFieldData.map(item => ({ type: 2, ...item })))
      .concat(New_WeaTableEdit_jobSyncFieldData.map(item => ({ type: 3, ...item })))
      .concat(WeaTableEdit_hrmSyncFieldData.map(item => ({ type: 4, ...item })))
    allParams.WebserviceParamValuesData = JSON.stringify(WebserviceParamValuesData);
    allParams.syncFieldData = JSON.stringify(syncFieldData);
    return allParams;
  }

  onRightMenuClick = (type, recordId) => {
    const { hrSyncStore } = this.props;
    const {
      newForm,
      dataSyncForm, 
      getHrSyncDataSyncOperation, 
      getHrSyncSettingsOperation, updateSyncData, logTableStore, status } = hrSyncStore;
    switch (type) {
      case "BTN_SAVE":
        const allParams = this.getAllPrams();
        if((allParams.intetype == 2) && allParams.jobmothod) {
          if(JSON.parse(allParams.WeaTableEdit_jobSyncFieldData).length == 0) {
            Modal.warning({
              title: getLabel("15172", "系统提示"),
              content: getLabel("32256", "岗位表必须有一个关键匹配标识字段，请选择")
            })
            return;
          }else {
            let WeaTableEdit_jobSyncFieldData = JSON.parse(allParams.WeaTableEdit_jobSyncFieldData);
            let keyIndex = WeaTableEdit_jobSyncFieldData.findIndex(data => data.iskeyfield == 1)
            if(keyIndex == -1) {
              Modal.warning({
                title: getLabel("15172", "系统提示"),
                content: getLabel("32256", "岗位表必须有一个关键匹配标识字段，请选择")
              })
              return;
            }
          }
        }
        if(allParams.isUnique) {
          IntegrationUtil.onCheck(newForm, () => {
            const result = hrSyncStore.syncSetField.table && hrSyncStore.syncSetField.table.doValidate();
            if (result && (!result.pass)) {
              return;
            }
            // first validate
            allParams.checkBeforeSave = true;
            getHrSyncSettingsOperation(allParams, (result) => {
              if (result && !result.error) {
                // and save
                delete allParams.checkBeforeSave;
                getHrSyncSettingsOperation(allParams, () => {
                  if(result.ret == true) {
                    message.success(getLabel(22619, '保存成功'));
                    hrSyncStore.getHrSyncSettingsForm();
                    hrSyncStore.getRightMenu();
                    hrSyncStore.getHrSyncSettingsImportForm();
                  }
                });
              } else {
                return;
              }
            })
          })
        }
        break;
      case "BTN_EXP":
        // 集成设置导出
        const expAllParams = this.getAllPrams();
        Modal.confirm({
          title: getLabel("131329", "信息确认"),
          content: getLabel("386087", "同步设置将以sql脚本文件的形式导出，确定要导出吗？"),
          onOk: () => {
			   alert("The inteface  named getHrSyncSettingsSqlFile is deleted!");
            /*getHrSyncSettingsOperation({ operation: "export", ...expAllParams }, (result) => {
              window.location.href = (window.ecologyContentPath || "") + "/api/integration/hrsync/getHrSyncSettingsSqlFile";
            });*/
          },
          onCancel: () => { }
        })
        break
      case "BTN_IMP":
        // 集成设置导入
        //status.showImportForm = true;
        break;
      case "BTN_SYNC":
        const syncparams = dataSyncForm.getFormParams();
        getHrSyncDataSyncOperation(syncparams, (res) => {
          this.setState({ hasSyncClick: true });
          updateSyncData(res);
        });
        break;
      case "BTN_EXPDATA":
        window.location.href = (window.ecologyContentPath || "") + "/weaver/weaver.file.ExcelOut";
        break;
      case "BTN_COLUMN":
        logTableStore.setColSetVisible(true);
        logTableStore.tableColSet(true);
    }
  };

  /**
   * 获取顶部按钮
   * @returns {Array}
   */
  getBtns = () => {
    const { hrSyncStore } = this.props;
    const { status, newForm, initialNewForm } = hrSyncStore;
    const { selectedKey, rightMenus, rightMenusTab2, rowSelectIds, loading, syncLoading, canexport, syncFlag, saveDisabled } = toJS(status);
    let btnArr = [];
    const whichRightMenu = Number(selectedKey) === 0 ? rightMenus : Number(selectedKey) === 1 ? rightMenusTab2 : [];
    if (whichRightMenu) {
      for (let j = 0; j < whichRightMenu.length; j++) {
        if (j == 3) {
          break
        }
        let m = whichRightMenu[j];
        let btn = null;
        if (m.type === "BTN_EXPDATA") {
          btn = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@cwdxm2`}
            type="primary"
            disabled={!this.state.hasSyncClick}
            onClick={() => {
              this.onRightMenuClick(m.type);
            }}>{`${m.menuName}`}</Button>;
        }else if(m.type === "BTN_SAVE") {
          btn = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ejtwn6`}
          type="primary"
          disabled={saveDisabled}
          onClick={() => {
            this.onRightMenuClick(m.type);
          }}>{`${m.menuName}`}</Button>;
        } else {
          btn =
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gx0tqk`}
              type="primary"
              disabled={(m.type === 'BTN_EXP' && !canexport) || (!this.state.sync && Number(selectedKey) === 1) || (m.type==="BTN_SYNC" && syncFlag)}
              onClick={() => {
                this.onRightMenuClick(m.type);
              }}>{`${m.menuName}`}</Button>;
        }
        btnArr.push(btn);
      }
    }

    // 未启用 数据同步隐藏按钮
    if (selectedKey === "1") {
      if (initialNewForm.getFormParams()["isuselhr"] === "0"){
        return [];
      }
      if (initialNewForm.getFormParams()["hrmethod"] === "2") {
        return [];
      }
    }
    return btnArr;
  };

  getDialogBtns = () => {
    return [
      (
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4jma6i@integrationHrsyncButtonSubmit`} onClick={() => {
          this.doImport();
        }} type="primary">{getLabel("725", "提交")}</Button>
      )
    ]
  }

  getDataSyncDescription = (form, condition=[]) => {
    const {isFormInit} = form;
    const formParams = form.getFormParams();
    let group = [];

    isFormInit && condition && condition.map((c, index) => {
      let items = [];
      c.items.map(fields => {
        items.push({
          com: (<div style={{marginLeft: -20}}>
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ffg45q@integrationHrsyncDesForm${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
              error={form.getError(fields)}
              tipPosition="bottom"
            >
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@57ijnj@integrationHrsyncDesForm${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} />
              {fields.showOtherCom && otherCom}
            </WeaFormItem></div>),
          colSpan: 1
        })
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@u756c2@integrationHrsyncDesForm${index}`} title={c.title} col={1} showGroup={true} items={items} />)
    })

    return group;
  }

  handleChangeTab = (v) => {
    const {hrSyncStore} = this.props;
    const {initialNewForm, getLogList} = hrSyncStore;
    const formParams = initialNewForm.getFormParams();

    if(v == 1) {
      this.setState({hasSyncClick: false, sync: true});
      let content = formParams["isuselhr"] === "0" ? getLabel("386893", "HR同步未启用!") 
        : formParams["hrmethod"] === "2" ? getLabel("32326", "未启用HR同步手动同步!") : '';
      
      if (formParams["isuselhr"] === "0" || formParams["hrmethod"] === "2") {
        this.setState({sync: false});
        hrSyncStore.setState({selectedKey: v});
        Modal.warning({
          title: getLabel("15172", "系统提示"),
          content: content
        })
        return;
      }
      // 刷新页面
      hrSyncStore.getHrSyncDataSyncForm();
      hrSyncStore.getHrSyncDataSyncRightMenu();
    }else if(v == 0) {
      hrSyncStore.newForm = new WeaForm();
      hrSyncStore.initialNewForm = new WeaForm();
      hrSyncStore.getHrSyncSettingsForm();
      hrSyncStore.getRightMenu();
      hrSyncStore.getHrSyncSettingsImportForm();
    }else if(v == 2) {
      hrSyncStore.getListConditions();
      getLogList();
    }
    hrSyncStore.setState({selectedKey: v});
  }

  render() {
    const { hrSyncStore } = this.props;
    const {
      status,
      newForm,
      dataSyncForm,
      importForm,
      syncTable,
      hasRight,
      rightLoading,
    } = hrSyncStore;
    const {
      syncFieldRelationShipSummaryLabel,
      showSearchAd,
      newFormFields,
      dataSyncFormFields,
      selectedKey,
      syncLoading,
      advanceHeight,
      showImportForm,
      hasNonStandard,
      nonStandLoading,
    } = toJS(status);
    const {
      jobSyncResultHeaderList,
      jobSyncResultDataList,
      jobTypeSyncResultHeaderList,
      jobTypeSyncResultDataList,
      deptSyncResultHeaderList,
      deptSyncResultDataList,
      subSyncResultHeaderList,
      subSyncResultDataList,
      gwSyncResultHeaderList,
      gwSyncResultDataList,
      hrmSyncResultHeaderList,
      hrmSyncResultDataList,
      hqSyncResultHeaderList,
      hqSyncResultDataList,
      lastLineSyncResultDataList,
    } = toJS(syncTable);
    const {topTab} = this.state;
    return (nonStandLoading
      ? null
      : hasNonStandard
        ? rightLoading
          ? null
          : hasRight
            ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@uf63h0`}
                datas={this.getRightMenu()}
                collectParams={{
                  favname: `${getLabel(33719, "HR同步")}`,
                  favouritetype: 1,
                  objid: 0,
                  link: "wui/engine.html#/integration/hrsync",
                  importantlevel: 1
                }}
              >
                <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@qa1vey`}
                  title={getLabel(33719, "HR同步")}
                  icon={<i className="icon-coms-integration" />}
                  iconBgcolor="#1a57a0"
                  buttons={this.getBtns()}
                  showDropIcon={true}
                  dropMenuDatas={this.getRightMenu()}
                  dropMenuProps={{
                    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@mt2vgj`}
                  datas={topTab}
                  keyParam="viewcondition" //主键
                  countParam="groupid" //数量
                  selectedKey={selectedKey}
                  searchType={selectedKey == 2 ? 'advanced' : ''}
                  advanceHeight={advanceHeight}
                  searchsAd={selectedKey == 2 ? this.getSearchAd() : []}
                  showSearchAd={showSearchAd}
                  buttonsAd={this.getTabButtonsAd()}
                  setShowSearchAd={() =>
                    hrSyncStore.setState({ showSearchAd: !showSearchAd })
                  }
                  hideSearchAd={() =>
                    hrSyncStore.setState({ showSearchAd: false })
                  }
                  onChange={this.handleChangeTab}
                  onSearch={() => hrSyncStore.getDataShowList()}
                  onSearchChange={value => {
                  }}
                />
                {
                  Number(selectedKey) === 2 
                  ? <LogList ecId={`${this && this.props && this.props.ecId || ''}_LogList@srq6yy`} />
                  : <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@5tcr9v`} height={"calc(100% - 110px)"}>
                    {
                      Number(selectedKey) === 0 
                      ? (
                          // 集成设置
                          <div>
                            {/* 基本信息 */}
                            {this.getFormSearchs(newForm, newFormFields)}
                            {/* 同步对应字段设置方法 */}
                            {newForm.getFormParams()["intetype"] !== "3" && (
                              <div>
                                <SyncSetFields ecId={`${this && this.props && this.props.ecId || ''}_SyncSetFields@lzutwo`} />
                                {/* 说明 */}
                                <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@oaf62w`}
                                  title={getLabel("25734", "说明")}
                                  needTigger={true}
                                  showGroup={true}
                                  className="boring-align"
                                  items={[{
                                    com: <div dangerouslySetInnerHTML={{
                                      __html: syncFieldRelationShipSummaryLabel && Object.keys(syncFieldRelationShipSummaryLabel).map(item => {
                                        return `${syncFieldRelationShipSummaryLabel[item]}<br/>`;
                                      }).join('')
                                    }} />
                                  }]}
                                />
                              </div>
                            )}

                            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@hhdhnl`}
                              icon={IntegrationUtil.GeneralTitleColor.icon}
                              iconBgcolor={IntegrationUtil.GeneralTitleColor.iconBgcolor}
                              style={{ width: 695, height: 300 }}
                              hasScroll={true}
                              title={getLabel("32935", "导入")}
                              visible={showImportForm}
                              onCancel={() => {
                                status.showImportForm = false;
                              }}
                              buttons={this.getDialogBtns()}
                              moreBtn={{
                                datas: this.getRightMenu2(),
                                collectParams: {
                                  favname: getLabel("32935", "导入"),
                                  favouritetype: 1,
                                  objid: 0,
                                  link: "wui/engine.html#/integration/hrsync",
                                  importantlevel: 1
                                }
                              }}
                            >
                              <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@gk6lww`}
                                datas={this.getRightMenu2()}
                                collectParams={[]}
                              >
                                {importForm.render({ col: 1 }, {
                                  onChange: () => { }
                                }, true, (item, index) => {
                                  switch (Number(index)) {
                                    case 0:
                                      return <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@kcvjqj`}
                                        needTigger={true}
                                        showGroup={true}
                                        center={true}
                                        col={1}
                                        title={item.title}
                                      >
                                        <div>
                                          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@uczesg`}
                                            label={`${item.items[0].label}`}
                                            labelCol={{ span: 9 }}
                                            wrapperCol={{ span: 10 }}
                                            tipPosition="bottom"
                                            style={{textAlign: "center"}}
                                          >
                                            <div style={{ float: 'left', marginLeft:-10 }}>
                                              <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@434t8m`}
                                                uploadUrl='/api/doc/upload/uploadFile'
                                                category='string'
                                                limitType='sql'
                                                viewAttr="3"
                                                maxFilesNumber={1}
                                                datas={this.state.filelist}
                                                onChange={(ids, list) => { this.setState({ file: ids, filelist: list }) }}
                                              >
                                                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mqedk0`}>{getLabel("125333", "选择文件")}</Button>
                                              </WeaUpload>
                                            </div>
                                            <div style={{ float: 'left', paddingLeft: 10, paddingTop: 6 }}>
                                              {this.state.filelist.length == 0 ? <p>{getLabel("384040", "未选择任何文件")}</p> : this.state.filelist.map(file => <p>{file.filename}</p>)}
                                            </div>
                                          </WeaFormItem>
                                        </div>
                                      </WeaSearchGroup>
                                    case 1:
                                      return <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@8cmor5`} 
                                        needTigger={true}
                                        showGroup={true}
                                        col={1}
                                        title={item.title}
                                        items={[{
                                          com: <div style={{marginLeft: -20}}>{item.items[0].value}</div>
                                        }]}
                                      /> 
                              }
                                })}
                              </WeaRightMenu>
                            </WeaDialog>
                          </div>
                        ) 
                      : (
                          // 数据同步
                          <div>
                            {IntegrationUtil.getFormSearchs(dataSyncForm, [dataSyncFormFields[0]], true, true, "", "", null, this && this.props && this.props.ecId || '', "integrationHrSyncIndex")}
                            {syncLoading && (
                              <div style={{ textAlign: "center", height: 200, lineHeight: "200px" }}>
                                <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@9p9wvk`} style={{ color: "#2db7f5", fontSize: "22px", }} type="loading" />
                                {getLabel('386883', '正在同步，请不要离开该页面，请稍后…')}
                              </div>
                            )}
                            {!syncLoading && this.state.hasSyncClick && (
                              <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@f6mcdb`} title={dataSyncFormFields[1].title} needTigger={true} showGroup={true}>
                                <div style={{ textAlign: "center" }}>
                                  {subSyncResultDataList.length > 0 && <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@feq0n9`} columns={subSyncResultHeaderList} dataSource={subSyncResultDataList} />}
                                  {jobSyncResultDataList.length > 0 && <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@pwyp5q`} columns={jobSyncResultHeaderList} dataSource={jobSyncResultDataList} />}
                                  {jobTypeSyncResultDataList.length > 0 && <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@7okkg7`} columns={jobTypeSyncResultHeaderList} dataSource={jobTypeSyncResultDataList} />}
                                  {deptSyncResultDataList.length > 0 && <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@mofh0o`} columns={deptSyncResultHeaderList} dataSource={deptSyncResultDataList} />}
                                  {gwSyncResultDataList.length > 0 && <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@pr7xkr`} columns={gwSyncResultHeaderList} dataSource={gwSyncResultDataList} />}
                                  {hrmSyncResultDataList.length > 0 && <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@c8xi66`} columns={hrmSyncResultHeaderList} dataSource={hrmSyncResultDataList} />}
                                  {hqSyncResultDataList.length > 0 && <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@qivr7g`} columns={hqSyncResultHeaderList} dataSource={hqSyncResultDataList} />}
                                  {lastLineSyncResultDataList.length > 0 && lastLineSyncResultDataList[0].lastLine}
                                </div>
                              </WeaSearchGroup>
                            )}
                            {!syncLoading && (!this.state.hasSyncClick) && this.getDataSyncDescription(dataSyncForm, [dataSyncFormFields[2]])}
                          </div>  
                        )
                    }
                    </WeaNewScroll>
                }
              </WeaRightMenu>
            : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@1z7x3p`}/>
        : <NonStand ecId={`${this && this.props && this.props.ecId || ''}_NonStand@3n1nlv`} />
    );
  }
}

export default HrSync;
