import React from "react";
import {inject, observer} from "mobx-react";
import {Button} from "antd";
import {toJS} from "mobx";
import {WeaSwitch} from "comsMobx";
import {
    WeaSearchGroup,
    WeaFormItem,
    WeaTools,
    WeaTableEdit,
    WeaHelpfulTip
} from "ecCom";
import {WeaRightMenu, WeaDialog} from "ecCom";
import {checkTableFieldValueUnique}  from "../../apis/CommonService";
import {WeaLocaleProvider} from "ecCom";

const getLabel = WeaLocaleProvider.getLabel;
const { getKey } = WeaTools;
const store = ["workflowFlowStore"];


@inject(...store)
@observer
export default class RegisterWebservice extends React.Component {
   constructor(props) {
      super(props);
      this.state = {};
   }

   getBtns = () => {
        const {workflowFlowStore} = this.props;
        const {buttonLoading, menus=[]} = toJS(workflowFlowStore.status);
        return menus && menus.map(item => <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@b6u0bg@integrationWorkflowRegisterWebserviceButton${item.key}`} type="primary" disabled={buttonLoading} onClick={() => this.onRightMenuClick(item.key)}>
            {item.content}
        </Button>);
    };

    getRightMenu = () => {
        const {workflowFlowStore} = this.props;
        const {menus=[], buttonLoading} = toJS(workflowFlowStore.status);
        return menus && menus.map(item => {
            return {
              ...item,
              disabled: buttonLoading,
              icon: <i className="icon-coms-Preservation"/>,
              onClick: () => this.onRightMenuClick(item.key),
            }
        });
    }

    onRightMenuClick = (type) => {
        const {workflowFlowStore,saveCallBack} = this.props;
        const {newRegisterWebserviceForm, status, webserviceEditIndex} = workflowFlowStore;
        const {interfaceRegisterWebserviceFormHiddenFields,WebserviceMethodParameterDatas,} = toJS(status);
        if (type == "BTN_SAVE" ||type == "BTN_TEST") {
            let checkParams = {
                tableName: 'wsformactionset',
                fieldName: 'actionname',
                fieldValue: newRegisterWebserviceForm.getFormParams().actionname.replace(/^(\s*)|(\s*)$/g, ''),
                idName: 'id',
                idValue: webserviceEditIndex
            };
            checkTableFieldValueUnique(checkParams).then(result => {
                if(result&&result.isNotUnique) {
                    newRegisterWebserviceForm.showError('actionname',getLabel('129943','名称已存在'));
                }else {
                     //注册Webservice
                    newRegisterWebserviceForm.validateForm().then(f=>{
                        if(f.isValid){
                            //合并hiddenfield参数
                            let params = Object.assign({}, interfaceRegisterWebserviceFormHiddenFields, newRegisterWebserviceForm.getFormParams());
                            params.operator = "save";
                            params.dtinfo_WebserviceMethodParameterDatas = JSON.stringify(WebserviceMethodParameterDatas);
                            workflowFlowStore.getInterfaceRegisterWebserviceOperation(params,saveCallBack,type);
                        }else{
                            f.showErrors();
                            this.setState({date: new Date()});
                        }
                    });
                }
            }); 
        }
        if(type == 'BTN_DEL'){
            let params = Object.assign({}, interfaceRegisterWebserviceFormHiddenFields, newRegisterWebserviceForm.getFormParams());
            params.operator = "delete";
            workflowFlowStore.confirmModal(`${getLabel(15097, '确定要删除吗？')}`, workflowFlowStore.getInterfaceRegisterWebserviceOperation , params);

        }
    };

    mark = (key) => {
        const {workflowFlowStore} = this.props;
        const {newRegisterWebserviceForm } = workflowFlowStore;
        const dom = $(ReactDOM.findDOMNode(this.xmltextDOM)).find("textarea")[0];
        let cursor = dom.selectionStart;
        const prevStr = newRegisterWebserviceForm.getFormParams().xmltext;
        let str = prevStr.slice(0,cursor) + key + prevStr.slice(cursor);
        newRegisterWebserviceForm.updateFields({xmltext: str});
        cursor += key.length;
        setTimeout(function () {
           dom.focus();
           dom.setSelectionRange(cursor, cursor,"forword");
        },10);
    };

    getSearchs = () => {
        const {workflowFlowStore} = this.props;
        const {newRegisterWebserviceForm, status, webserviceEditIndex} = workflowFlowStore;
        const {interfaceRegisterWebserviceFormFields,WeaTableEdit_WebserviceParameterSet
            ,WebserviceMethodParameterDatas,mainFieldMarkList,detailFieldMarkList, interfaceRegisterWebserviceFormHiddenFields} = toJS(status);
        const {isFormInit} = newRegisterWebserviceForm;
        let group = [];
        let i = 0;
        const formParams = newRegisterWebserviceForm.getFormParams();
        isFormInit &&
        interfaceRegisterWebserviceFormFields &&
        interfaceRegisterWebserviceFormFields.map(c => {
            let items = [];
            c.items.map(fields => {
                let switchParams = {
                   fieldConfig: fields,
                   form: newRegisterWebserviceForm,
                   formParams: formParams,
                   onChange: v => {
                        if(getKey(fields) === 'wsurl') {
                            //获取webservice里的方法
                            let params = {wsid: newRegisterWebserviceForm.getFormParams().wsurl, operator: 'getregisteinfo'};
                            workflowFlowStore.getDataShowOperation(params);
                        }else if(getKey(fields) === 'wsoperation' && newRegisterWebserviceForm.getFormParams().wsoperation!=""){
                            //获取WebService方法的参数
                            let params = {methodid: newRegisterWebserviceForm.getFormParams().wsoperation, operator: 'getmethodinfo'};
                            workflowFlowStore.getDataShowOperation(params);
                        }else if(getKey(fields) === 'formid' && newRegisterWebserviceForm.getFormParams().formid!=""){
                            //获取主表和明细表mark
                            let formid = newRegisterWebserviceForm.getFormParams().formid;
                            let isbill = 0;
                            if(formid<0) {
                                isbill = 1;
                            }
                            let params = {formid: formid,isbill:isbill, operator: 'getMainFieldMarkListAndDetailFieldMarkList'};
                            workflowFlowStore.getInterfaceRegisterWebserviceOperation(params);
                            let hiddenFields = Object.assign({}, interfaceRegisterWebserviceFormHiddenFields, {isbill});
                            workflowFlowStore.setState({interfaceRegisterWebserviceFormHiddenFields: hiddenFields});
                        }else if(getKey(fields) === 'actionname') {
                            let checkParams = {
                                tableName: 'wsformactionset',
                                fieldName: 'actionname',
                                fieldValue: newRegisterWebserviceForm.getFormParams().actionname.replace(/^(\s*)|(\s*)$/g, ''),
                                idName: 'id',
                                idValue: webserviceEditIndex
                            };
                            checkTableFieldValueUnique(checkParams).then(result => {
                                if(result&&result.isNotUnique) {
                                    newRegisterWebserviceForm.showError('actionname',getLabel('129943','名称已存在'));
                                }
                            });
                        }
                    }
                };
                items.push({
                    com: (
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@xnrnr9@integrationWorkflowRegisterWebserviceForm${fields.domkey[0]}`}
                            label={`${fields.label}`}
                            labelCol={{span: `${fields.labelcol}`}}
                            wrapperCol={{span: `${fields.fieldcol}`}}
                            error={newRegisterWebserviceForm.getError(fields)}
                            tipPosition="bottom"
                        >
                           <nobr>
                              {
                                 getKey(fields) === "xmltext" ?
                                    <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@a81uxi@integrationWorkflowRegisterWebserviceForm${fields.domkey[0]}`} {...switchParams} ref={(e)=>{this.xmltextDOM=e;}}/>
                                    :
                                    <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@7f3xlv@integrationWorkflowRegisterWebserviceForm${fields.domkey[0]}`} {...switchParams}/>
                              }

                               {
                                   getKey(fields) == 'retstr' ? <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@jmlzi0@integrationWorkflowRegisterWebserviceForm${fields.domkey[0]}`} style={{marginLeft: 13}} title={getLabel(389930,"SQL格式如下：update formtable_main_100 set field001='$retstr$' where requestid=$requestid$  注意：这里不能引用表单字段，只能引用系统字段及返回值")}/> : ''
                               }
                          </nobr>
                        </WeaFormItem>
                    ),
                    colSpan: 1
                });
                if (getKey(fields) === "wsnamespace" && formParams.wsoperation != "") {
                    WeaTableEdit_WebserviceParameterSet[4].title =
                        <div>
                        <span>{WeaTableEdit_WebserviceParameterSet[4].title}<span className={"wf-backstage-linkAgeViewAttr-helpTip"} style={{marginLeft:5}}>
                            <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@2o1b83@integrationWorkflowRegisterWebserviceForm${fields.domkey[0]}`} title={getLabel(  84659  ,"如果有需要传递流程数据，请以$开始并且$结束，如果是明细数据，请以$detail_字段名$形式，注意使用明细字段时，要保证字段名称唯一性!")} />
                        </span></span>
                        </div>;

                    items.push({
                        com: (
                            <div>
                                <WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@q1nemh@integrationWorkflowRegisterWebserviceForm${fields.domkey[0]}`}
                                    // title={`WebService${getLabel(17632, "参数设置")}`}
                                    tableProps={{showEmptyText: false}}
                                    columns={WeaTableEdit_WebserviceParameterSet}
                                    datas={WebserviceMethodParameterDatas}
                                    // onRowSelect={this.onRowSelect}
                                    // getRowSelection={this.getRowSelection}
                                    draggable={false}
                                    showAdd={false}
                                    showDelete={false}
                                    showCopy={false}
                                    getRowSelection={a => {return false}}
                                    onAdd={(ks, ds) => {}}
                                    onEdit={(ks, ds) => {}}
                                    onCopy={(ks, ds) => {}}
                                    onDelete={(ks, ds) => {}}
                                    onChange={(datas) => workflowFlowStore.setState({WebserviceMethodParameterDatas: datas})}
                                />
                            </div>
                        ),
                        hide: newRegisterWebserviceForm.isHide(fields, (keys, allParams) => {
                            return (  WebserviceMethodParameterDatas.length == 0);
                        })
                    });
                }

            });

            //主表字段mark
            if(i==3) {
                let obj=mainFieldMarkList[0];
                let i = 0;
                let mark = [];
    
                for (let key in obj) {
                    if(i % 6 == 5) {
                        mark.push(<nobr><span onClick={()=>{this.mark(key)}} style={{marginLeft:5,cursor:'pointer',color:'blue',whiteSpace:'nowrap'}} key={key}>{obj[key]}</span><br/></nobr>)
                    }else {
                        mark.push((<span onClick={()=>{this.mark(key)}} style={{marginLeft:5,cursor:'pointer',color:'blue',whiteSpace:'nowrap'}} key={key}>{obj[key]}</span>))
                    }
                    i++;
                }


                group.push(
                    <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@q6vrix@integrationWorkflowRegisterWebserviceForm${i}`}

                        col={1}
                        needTigger={true}
                        title={c.title}
                        showGroup={c.defaultshow}
                        // items={items}
                        center={true}
                        style={{display:((i==3 && mainFieldMarkList.length==0) )?"none":""}}
                    >
                        {mark}
                    </WeaSearchGroup>
                );

            }
            //明细表字段mark
            if(i==4) {
                for(let j=0,len=detailFieldMarkList.length;j<len;j++) {
                    let obj=detailFieldMarkList[j];
                    let mark = [];
                    let head = '';
                    let tail = '';
                    let i = 0;
                    for (let key in obj) {
                        if(key == `$grouptail${j+1}$`) {
                            tail = <span onClick={()=>{this.mark(key)}} style={{marginLeft:10,cursor:'pointer',color:'blue'}} key={key}>{obj[key]} </span>;
                        }else if(key == `$grouphead${j+1}$`) {
                            head = <span onClick={()=>{this.mark(key)}} style={{marginLeft:40,cursor:'pointer',color:'blue'}} key={key}>{obj[key]} </span>;
                        }else {
                            mark.push((<span onClick={()=>{this.mark(key)}} style={{marginLeft:5,cursor:'pointer',color:'blue'}} key={key}>{obj[key]} </span>))
                            if(i % 6 == 5) {
                                mark.push(<br/>);
                            }
                            i++;
                        }
                    }
                    group.push(
                        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@jresvg@integrationWorkflowRegisterWebserviceForm${i}`}
                            center={true}
                            col={1}
                            needTigger={true}
                            title={<p>{c.title+(j+1)}{head}{tail}</p>}
                            showGroup={c.defaultshow}
                            // items={items}
                            style={{display:((i==3 && mainFieldMarkList.length==0)  )?"none":""}}
                        >
                            {mark}

                        </WeaSearchGroup>
                    );
                }

            }
            if(i<3){
                group.push(
                    <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@s4fywt@integrationWorkflowRegisterWebserviceForm${i}`}
						center
                        col={1}
                        needTigger={true}
                        title={c.title}
                        showGroup={c.defaultshow}
                        items={items}
                        style={{display:((i==3 && mainFieldMarkList.length==0) ||(i==4 && detailFieldMarkList.length==0) )?"none":""}}
                    />
                );
            }

            i++;
        });
        return group;
    };

    render() {
        const {workflowFlowStore} = this.props;
        const {showRegisterWebserviceDialog} = toJS(workflowFlowStore.status);
        const {interfaceRegisterWebserviceFormHiddenFields} = toJS(workflowFlowStore.status);
        let title = getLabel('31691,34150', '注册Webservice接口');
        if(interfaceRegisterWebserviceFormHiddenFields && interfaceRegisterWebserviceFormHiddenFields.actionid!="") {
            title = getLabel('26473,34150', '编辑Webservice接口');
        }

        return (
            <div className="wea-integration-single">
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@uu0sru`}
                    title={title}
                    icon="icon-coms-integration"
                    iconBgcolor="#1a57a0"
                    visible={showRegisterWebserviceDialog}
                    hasScroll={true}
                    style={{width: 900, height: 600}}
                    onCancel={() => {
                        workflowFlowStore.setState({showRegisterWebserviceDialog: false});
                        workflowFlowStore.newRegisterWebserviceForm.reset();
                    }}
                    buttons={this.getBtns()}
                    moreBtn={{
                        datas: this.getRightMenu(),
                        collectParams: []
                    }}
                >
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@a188z9`} datas={this.getRightMenu()} collectParams={[]}>
                        {this.getSearchs()}
                    </WeaRightMenu>
                </WeaDialog>
            </div>
        );
    }
}
