import React from "react";
import { inject, observer } from "mobx-react";
import { Button, message} from 'antd';
import { toJS } from "mobx";
import {
  WeaRightMenu,
  WeaDialog,
  WeaLocaleProvider,
} from "ecCom";
import {
  checkTableFieldValueUnique
}  from "../../apis/CommonService";
import {
  onCheck
} from '../../util/IntegrationUtil';
import RegisterESBSetting from './RegisterESBSetting';

const {getLabel} = WeaLocaleProvider;

@inject("workflowFlowStore")
@observer
export default class RegisterESB extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      key: "",
      visible: false,
      detailTableInfo: {
        showCopy: false,
        showCollapse: false,
        rowKey: "rowKey",
      },
      mainTableInfo: {
        showTitle: false,
        showAdd: false,
        showDelete: false,
        showCopy: false,
        rowKey: "rowKey",
        showCollapse: false,
      }
    };
    if(props.getInstance && typeof(props.getInstance) === "function") {
      // 保存的方法方便外部调用
      props.getInstance(this);
    }
  }

  componentWillUnmount() {
    this.cleanState();
  }
  
  cleanState = (flag=0) => {
    const {
      workflowFlowStore,
      saveCallBack
    } = this.props;
    workflowFlowStore.cleanESBForm();
    workflowFlowStore.detailFormInfo = {};
    workflowFlowStore.setState({
      showRegisterESBDialog: false
    });
    this.setState({
      key: "",
      esbIdShowError: false,
      visible: false,
    })
    this.table = null;
    if(1 == flag && saveCallBack && typeof(saveCallBack) === "function") {
      saveCallBack();
    }
  }

  getBtns = (datas) => {
    let btns = [];
    datas && datas.map(m => {
      btns.push(
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@14zf6p@integrationWorkflowRegisterESBButton${m.key}`} type="primary" disabled={this.props.workflowFlowStore.status.buttonLoading} onClick={() => this.onRightMenuClick(m.type)}>
          {m.menuName}
        </Button>
      )
    })
    return btns;
  };

  getRightMenu(datas) {
    let btnArr = [];
    datas && datas.map(m => {
      btnArr.push({
        key: m.type,
        icon: <i className={m.menuIcon} />,
        content: m.menuName,
        disabled: this.props.workflowFlowStore.status.buttonLoading,
        onClick: () => this.onRightMenuClick(m.type)
      })
    })
    
    return btnArr;
  }

  // 检测请求数据是否必填
  checkRequestRequire = () => {
    const {
      workflowFlowStore
    } = this.props, {
      status,
    } = workflowFlowStore, {
      esbRequestDatas=[], 
      detailFormTabDatas=[],
      selectType=[],
    } = toJS(status);
    for(let i = 0; i < esbRequestDatas.length; i++) {
      let v = esbRequestDatas[i], flag = true;  // 是否是最后一级
      if(!v.arrs) {
        let paramKeys = v.paramKey.split('.'),
          option = detailFormTabDatas.concat(selectType).find(item => item.key === v.assignType),
          idx = esbRequestDatas.findIndex(data => {
            let dataParamKeys = data.paramKey.split('.');
            return (dataParamKeys.length > paramKeys.length) && (dataParamKeys.slice(0, paramKeys.length).join('.') === v.paramKey);
          });
        if(idx === -1) {
          flag = v.assignType 
            ? v.assignValue 
              ? (option && option.browserType)
                ? JSON.parse(v.assignValue).id
                  ? true
                  : false
                : true
              : false
            : v.required
              ? false
              : true; 
        }
      }else {
        flag = detailFormTabDatas.length
          ? v.assignType
            ? true
            : v.required
              ? false
              : true
          : true;
      }
      if(!flag) {
        message.error(getLabel('507246','对应字段必填'));
        return false;
      }
    }
    return true;
  }

  // 保存的action
  doOperateForm = (i=0) => {
    const {
      workflowFlowStore, 
      saveCallBack
    } = this.props, {
      status, 
      funForm,
      detailFormInfo,
      newRegisterESBForm, 
    } = workflowFlowStore, {
      esbActionTableDatas=[], 
      tabs=[], 
      operateSrc, 
      esbRequestDatas=[], 
      mainTable=[], 
      tableTabDatas=[],
      interfaceRegisterEsbHiddenFields={},
      funTabs=[],
      from="",
    } = toJS(status);
    // 判断当前的i是不是最后一个进行验证的，若是，则说明此刻可以进行保存操作了
    if(((tableTabDatas.length != 0) && (tableTabDatas.length - 1 === i)) || tableTabDatas.length === 0) {
      let mainInfo = "",
        detailInfo = [],
        funInfo = "",
        requestParams = "",
        mainKeyItem = mainTable ? mainTable[0] || "" : "",
        funKeyItem = funTabs ? funTabs[0] || "" : "";
      // 存放明细表的信息
      tableTabDatas && tableTabDatas.forEach(item => {
        if(mainKeyItem && item.key === mainKeyItem.key) {
          mainInfo = {
            baseInfo: {
              tableName: mainKeyItem.key,
              showName: mainKeyItem.showname
            },
            assignInfo: esbActionTableDatas
          }
        } else if(tabs.includes(item.key) && detailFormInfo && detailFormInfo[item.key]) {
            detailInfo.push({
              baseInfo: {...detailFormInfo[item.key].form.getFormParams(), tableName: item.key, showName: item.title},
              assignInfo: toJS(detailFormInfo)[item.key].paramDatas
            })
        } else if(funKeyItem && item.key === funKeyItem.key) {
          if(funForm) {
            funInfo = {...funForm.getFormParams(), showName: funKeyItem.showname, tableName: funKeyItem.key};
          }
        }
      });
      let params = {
        formInfo: {
          mainInfo,
          detailInfo,
        },
        baseInfo: {...newRegisterESBForm.getFormParams()},
        requestData: esbRequestDatas
      }
      if("1" === from) {
        params.formInfo = {
          mainInfo,
          detailInfo,
          funInfo,
        }
      }
      requestParams = operateSrc ? {
        data: JSON.stringify({...params, type: 'edit'})
      } : {
        data: JSON.stringify(params),
        ...interfaceRegisterEsbHiddenFields,
      }
      workflowFlowStore.saveAction(requestParams, () => {
        saveCallBack && typeof(saveCallBack) === "function" && saveCallBack();
        workflowFlowStore.getInterfaceRegisterList();
        message.success(getLabel('22619','保存成功'));
        this.cleanState();
      }, from);
    }
  }

  //递归验证必填
  checkRequireInfo = (index=0) => {
    const {
      workflowFlowStore, 
    } = this.props, {
      status, 
      funForm,
      detailFormInfo,
      newRegisterESBForm,
    } = workflowFlowStore, {
      tabs=[], 
      mainTable=[],
      funTabs=[],
      tableTabDatas=[], 
      from,
      esbActionTableDatas=[],
    } = toJS(status);

    let detailFormKey = tableTabDatas[index].key,
      mainFormKey = (mainTable && mainTable[0]) ? mainTable[0].key : "",
      funKey = (funTabs && funTabs[0]) ? funTabs[0].key : "",
      tableTabLength = tableTabDatas.length - 1,
      formParams = newRegisterESBForm.getFormParams();
    if(mainFormKey === detailFormKey) {
      if(this.table && this.table.mainTableEdit) {
        if(this.table.mainTableEdit.doValidate().pass) {
          if(esbActionTableDatas.length > 0) {
            if(tableTabLength === index) {
              this.doOperateForm(index);
            }else {
              this.checkRequireInfo(index+1);
            }
          }else {
            let title = `主表${getLabel('21845','赋值设置')}`;
            message.error(`"${title}"${getLabel('507906','至少有一条数据')}`);
            workflowFlowStore.setState({tabSelectedKey: detailFormKey});
          }
        } else {
          workflowFlowStore.setState({tabSelectedKey: detailFormKey}); 
        }
      }
    } else if(tabs.includes(detailFormKey)) {
      if(detailFormInfo[detailFormKey]) {
        let tableValidate = () => {
          let detailPass = this.table && this.table[`detail_${detailFormKey}`] ? this.table[`detail_${detailFormKey}`].doValidate().pass : true;
          if(detailPass) {
            if(detailFormInfo[detailFormKey].paramDatas.length > 0) {
              if(tableTabLength === index) {
                this.doOperateForm(index);
              }else {
                this.checkRequireInfo(index+1);
              }
            }else {
              let title = (tableTabDatas && tableTabDatas.find(v => v.key === detailFormKey)) ? `${tableTabDatas.find(v => v.key === detailFormKey).title}${getLabel('21845','赋值设置')}` : getLabel('21845','赋值设置');
              message.error(`"${title}"${getLabel('507906','至少有一条数据')}`);
              workflowFlowStore.setState({tabSelectedKey: detailFormKey});
            }
          }else {
            workflowFlowStore.setState({tabSelectedKey: detailFormKey});
          }
        };
        if(from === "2" && "0" != formParams.tableType) {
          tableValidate(); 
        }else {
          if(from == "2" && "2" != formParams.del) {
            window.e9HideFormFieldKeys = ["dbFieldName", "esbFieldName", "addNewRow"];
          }
          onCheck(detailFormInfo[detailFormKey].form, tableValidate, () => {
            workflowFlowStore.setState({tabSelectedKey: detailFormKey});
          })
        }
      }
    } else if(funKey === detailFormKey){
      if(funForm) {
        onCheck(funForm, () => {
          if(tableTabLength === index) {
            this.doOperateForm(index);
          }else {
            this.checkRequireInfo(index+1);
          }
        }, () => {
          workflowFlowStore.setState({tabSelectedKey: detailFormKey});  
        })
      }
    }
  }

  onRightMenuClick = (type) => {
    if(type == "BTN_SAVE") {
      this.onSave();
    }
  };

  onSave = () => {
    const {
      workflowFlowStore, 
    } = this.props, {
      status,
      newRegisterESBForm, 
    } = workflowFlowStore, {
      operateSrc, 
      tableTabDatas, 
      from
    } = toJS(status);
    let checkParams = {
      tableName: 'esb_actionset',
      fieldName: 'actionname',
      fieldValue: newRegisterESBForm.getFormParams().actionname.replace(/^(\s*)|(\s*)$/g, '')
    };
    onCheck(newRegisterESBForm, () => {
      checkTableFieldValueUnique(checkParams).then(result => {
        if (result && result.isNotUnique && (!operateSrc) && (!from)) {
          newRegisterESBForm.showError('actionname',getLabel('129943','名称已存在'));
        }else {
          //检测请求数据是否必填
          let isRequired = this.checkRequestRequire();
          if(isRequired) {
            if(tableTabDatas.length) {
              this.checkRequireInfo();
            } else {
              this.doOperateForm();
            }
          }
        }
      })
    }) 
  }

  render() {
    const { 
      workflowFlowStore,
      showDialog=true, 
    } = this.props, { 
      status, 
    } = workflowFlowStore, {
      showRegisterESBDialog, 
      operateSrc, 
      esbRightMenus, 
      from="",
    } = toJS(status);
    const {rightMenus = [], collectParams = {}} = esbRightMenus;
    return (
      <div className="wea-integration-single">
        {
          showDialog   // 是否显示弹窗，主要针对字段联动处理（默认是显示）
            ? <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@2q6a1x`}
                title={operateSrc ? getLabel("26473,381878", "编辑ESB接口") : getLabel("31691,381878", "注册ESB接口")}
                icon="icon-coms-integration"
                iconBgcolor="#1a57a0"
                visible={showRegisterESBDialog}
                hasScroll={true}
                scalable
                style={{width: 900, height: 700}}
                onCancel={() => this.cleanState('1')}
                buttons={this.getBtns(rightMenus)}
                moreBtn={{
                  datas: this.getRightMenu(rightMenus),
                  collectParams: [collectParams]
                }}
                {...this.props}
              >
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@hx32tr`} datas={this.getRightMenu(rightMenus)} collectParams={[collectParams]}>
                  <RegisterESBSetting ecId={`${this && this.props && this.props.ecId || ''}_RegisterESBSetting@uk1lh3`} 
                    getInstanceOf={(ref) => this.table = ref} 
                    {...this.props}
                  />
                </WeaRightMenu>
              </WeaDialog>
            : <RegisterESBSetting ecId={`${this && this.props && this.props.ecId || ''}_RegisterESBSetting@9q7ubp`} 
                getInstanceOf={(ref) => this.table = ref} 
                showCollapse={from != "2"}   // 是否显示form表单的基本信息头，主要针对字段联动的处理（默认是显示）
                {...this.props}
              />
        }
      </div>
    );
  }
}
