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

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

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

    getBtns = () => {
        const { workflowFlowStore } = this.props;
        const { buttonLoading } = toJS(workflowFlowStore.status);
        let btns = []
        btns = [
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4sdjw6@integrationWorkflowDeployButtonSave`} type='primary' disabled={buttonLoading} onClick={() => this.onRightMenuClick('BTN_SAVE')}>{getLabel(86, '保存')}</Button>
        ];

        return btns;
    }
    getRightMenu () {
        const { workflowFlowStore } = this.props;
        const { buttonLoading } = toJS(workflowFlowStore.status);
        let btnArr = [
            {
                key: 'BTN_SAVE',
                icon: <i className='icon-coms-Preservation' />,
                content: `${getLabel(86, '保存')}`,
                disabled: buttonLoading,
                onClick: () => this.onRightMenuClick('BTN_SAVE')
            },
        ]
        return btnArr;
    }
    onRightMenuClick = (type, recordId) => {
        const { workflowFlowStore } = this.props;
        const { newDeploymentForm, status } = workflowFlowStore;
        const { newDeploymentFormHiddenFields, WeaTableEdit_NodeOperateSetData, WeaTableEdit_SeqOperateSetData } = toJS(workflowFlowStore.status);

        if (type == 'BTN_SAVE') {
            let tempresult = this.tableEdit.doValidate();
            // let tempresult = this.tableEdit.refs.edit.doRequiredCheck();
            if (!tempresult.pass) {
                return;
            }
            let tempresult1 = this.tableEdit1.doValidate();
            // let tempresult1 = this.tableEdit1.refs.edit.doRequiredCheck();
            if (!tempresult1.pass) {
                return;
            }
            newDeploymentForm.validateForm().then(f => {
                if (f.isValid) {
                    //合并hiddenfield参数
                    let params = Object.assign(newDeploymentFormHiddenFields, newDeploymentForm.getFormParams());
                    params.operate = "save";
                    params.dtinfo_NodeOperateSetData = JSON.stringify(WeaTableEdit_NodeOperateSetData);
                    params.dtinfo_SeqOperateSetData = JSON.stringify(WeaTableEdit_SeqOperateSetData);
                    // params.dtinfo_WebserviceMethodParameterDatas = JSON.stringify(WebserviceMethodParameterDatas);
                    workflowFlowStore.getInterfaceDeploymentOperation(params);
                } else {
                    f.showErrors();
                    this.setState({ date: new Date() });
                }
            });

        }
    }

    getSearchs = () => {
        const {
            workflowFlowStore,
        } = this.props, {
            newDeploymentForm,
            status,
        } = workflowFlowStore, {
            newDeploymentFormFields,
            WeaTableEdit_NodeOperateSet,
            WeaTableEdit_NodeOperateSetData,
            WeaTableEdit_SeqOperateSet,
            WeaTableEdit_SeqOperateSetData,
            NodeOperateSetDataSAP,
            SeqOperateSetDataSAP
        } = toJS(status), {
            isFormInit,
        } = newDeploymentForm;
        let group = [], i = 0;
        const formParams = newDeploymentForm.getFormParams();
        isFormInit && newDeploymentFormFields && newDeploymentFormFields.forEach(c => {
            let items = [];
            c.items && c.items.forEach(fields => {
                items.push({
                    com: (
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@xb0bla@integrationWorkflowDeployForm${fields.domkey[0]}`}
                            label={`${fields.label}`}
                            labelCol={{ span: `${fields.labelcol}` }}
                            wrapperCol={{ span: `${fields.fieldcol}` }}
                            error={newDeploymentForm.getError(fields)}
                            tipPosition="bottom"
                        >
                            <nobr>
                                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@fa5led@integrationWorkflowDeployForm${fields.domkey[0]}`} fieldConfig={fields} form={newDeploymentForm} formParams={formParams} onChange={v => {
                                    if (getKey(fields) === 'workflowid' && newDeploymentForm.getFormParams().workflowid != "") {
                                        const workflowid = newDeploymentForm.getFormParams().workflowid;
                                        //获取节点下拉选项和出口下拉选项
                                        let checkParams = {
                                            tableName: 'workflowactionset',
                                            fieldName: 'workflowid',
                                            fieldValue: workflowid.replace(/^(\s*)|(\s*)$/g, ''),
                                        };
                                        checkTableFieldValueUnique(checkParams).then(result => {
                                            if (result && result.isNotUnique) {
                                                workflowFlowStore.getInterfaceDeploymentAddForm({ workflowid, fromintegration: 1, operate: 'edit' });
                                            } else {
                                                let params = { workflowid: newDeploymentForm.getFormParams().workflowid, operate: 'getWorkflowNodeListAndSequenceList' };
                                                workflowFlowStore.getInterfaceDeploymentOperation(params);
                                            }
                                        });
                                    }
                                }} />
                                {
                                    getKey(fields) === 'sqltext' ?
                                        <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@fsn1du@integrationWorkflowDeployForm${fields.domkey[0]}`} style={{ marginLeft: 10 }}
                                            width={400}
                                            title={getLabel('82995,132036', '参数可设置如下内容：当前用户id，格式为{?userid}；当前用户登陆账号，格式为{?loginid}；当前用户姓名，格式为{?username}；当前用户编号，格式为{?workcode}；当前用户密码(MD5格式)，格式为{?password}；当前用户部门id，格式为{?departmentid}；当前用户部门编码，格式为{?departmentcode}；当前用户部门名称，格式为{?departmentname}；当前用户分部id，格式为{?subcompanyid}；当前用户分部编码，格式为{?subcompanycode}；当前用户分部名称，格式为{?subcompanyname}；若联动主表字段，格式为$主表字段名$；若联动明细表字段，格式为$明细表表名_明细表字段名$')}
                                        />
                                        : getKey(fields) === 'searchById' ?
                                            <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@ix6l0c@integrationWorkflowDeployForm${fields.domkey[0]}`} style={{ marginLeft: 10 }}
                                                width={196}
                                                title={getLabel('127946', '不设置表示与查询SQL语句相同')}
                                            />
                                            : getKey(fields) === 'keyfield' ?
                                                <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@05761i@integrationWorkflowDeployForm${fields.domkey[0]}`} style={{ marginLeft: 10 }}
                                                    width={196}
                                                    title={getLabel('84576', '主键字段的值不能包含如下特殊字符：!@$%^&"\\?/<>')}
                                                />
                                                : getKey(fields) === 'detailpageurl' ?
                                                    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@u4ffq9@integrationWorkflowDeployForm${fields.domkey[0]}`} style={{ marginLeft: 10 }}
                                                        width={400}
                                                        title={getLabel('82995', '参数可设置如下内容：当前用户id，格式为{?userid}；当前用户登陆账号，格式为{?loginid}；当前用户姓名，格式为{?username}；当前用户编号，格式为{?workcode}；当前用户密码(MD5格式)，格式为{?password}；当前用户部门id，格式为{?departmentid}；当前用户部门编码，格式为{?departmentcode}；当前用户部门名称，格式为{?departmentname}；当前用户分部id，格式为{?subcompanyid}；当前用户分部编码，格式为{?subcompanycode}；当前用户分部名称，格式为{?subcompanyname}；')}
                                                    /> : ''
                                }
                            </nobr>
                        </WeaFormItem>
                    ),
                    colSpan: 1,
                    hide: newDeploymentForm.isHide(fields, (keys, allParams) => {
                        let bool = false;
                        getKey(fields) === 'showtype' && allParams.showclass == '2' && (bool = true);
                        getKey(fields) === 'datasourceid' && allParams.datafrom != '1' && (bool = true);
                        getKey(fields) === 'sqltext' && (allParams.showtype == '3' || allParams.datafrom == '0' || allParams.datafrom == '2') && (bool = true);
                        getKey(fields) === 'searchById' && (allParams.showtype == '3' || allParams.datafrom == '0' || allParams.datafrom == '2') && (bool = true);
                        getKey(fields) === 'keyfield' && allParams.showtype == '3' && (bool = true);
                        getKey(fields) === 'wsurl' && allParams.datafrom != '0' && (bool = true);
                        getKey(fields) === 'wsoperation' && allParams.datafrom != '0' && (bool = true);
                        getKey(fields) === 'wsworkname' && allParams.datafrom != '0' && (bool = true);
                        getKey(fields) === 'parentfield' && (allParams.showtype != '2' || allParams.datafrom != '1') && (bool = true);
                        getKey(fields) === 'showfield' && (allParams.showtype != '2' || allParams.datafrom != '1') && (bool = true);
                        getKey(fields) === 'customhref' && (allParams.datafrom == '1' || allParams.datafrom == '0') && (bool = true);
                        return bool;
                    })
                });

            });
            if (i == 1) {
                //节点操作
                items.push({
                    com: (
                        <div>
                            <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@cgzhdz@integrationWorkflowDeployForm${i}`}
                                ref={el => {
                                    this.tableEdit = el
                                }}
                                title={`${getLabel(83004, "节点操作")}`}
                                tableProps={{ showEmptyText: false }}
                                columns={WeaTableEdit_NodeOperateSet}
                                datas={WeaTableEdit_NodeOperateSetData}
                                draggable={false}
                                showAdd={true}
                                showDelete={true}
                                deleteConfirm={true}
                                showCopy={false}
                                rowKey='tempactionid'
                                validator={{
                                    rules: {
                                        actionname: "required",
                                        actionorder: "required",
                                        actionnodeid: 'required',
                                        interfaceid: 'required'
                                    },
                                    errorMessage: {
                                        required: getLabel('385869','此项必填'),
                                    }
                                }}
                                cells={NodeOperateSetDataSAP}
                                willEdit={(data, record) => {
                                    if (record.key == "interfaceid") {
                                        // let datas = toJS(workflowFlowStore.status.WeaTableEdit_NodeOperateSetData);
                                        let datas = data;
                                        if (record.browserDatas.length != 0) {
                                            datas[record.index].interfacetype = record.browserDatas[0].fromtype;
                                        }
                                        workflowFlowStore.setState({ WeaTableEdit_NodeOperateSetData: datas })
                                    } else {
                                        workflowFlowStore.setState({ WeaTableEdit_NodeOperateSetData: data })
                                    }

                                }}
                                onCopy={(ks, ds) => { }}
                                onDelete={(ks, ds) => { }}
                                onChange={(datas) => {
                                    workflowFlowStore.setState({ WeaTableEdit_NodeOperateSetData: datas })
                                }}
                            />
                        </div>
                    ),
                    hide: newDeploymentForm.isHide(newDeploymentForm, (keys, allParams) => {
                        return (false);
                    })
                });
                //出口操作
                items.push({
                    com: (
                        <div>
                            <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@1jiz2m@integrationWorkflowDeployForm${i}`}
                                ref={el => {
                                    this.tableEdit1 = el
                                }}
                                validator={{
                                    rules: {
                                        actionname: "required",
                                        actionorder: "required",
                                        actionnodelinkid: 'required',
                                        interfaceid: 'required'
                                    },
                                    errorMessage: {
                                        required: getLabel('385869','此项必填'),
                                    }
                                }}
                                title={`${getLabel(83005, "出口操作")}`}
                                tableProps={{ showEmptyText: false }}
                                columns={WeaTableEdit_SeqOperateSet}
                                datas={WeaTableEdit_SeqOperateSetData}
                                draggable={false}
                                showAdd={true}
                                showDelete={true}
                                deleteConfirm={true}
                                showCopy={false}
                                rowKey='tempactionid'
                                cells={SeqOperateSetDataSAP}
                                willEdit={(data, record) => {
                                    if (record.key == "interfaceid") {
                                        // let datas = toJS(workflowFlowStore.status.WeaTableEdit_SeqOperateSetData);
                                        let datas = data;
                                        if (record.browserDatas.length != 0) {
                                            datas[record.index].interfacetype = record.browserDatas[0].fromtype;
                                        }
                                        workflowFlowStore.setState({ WeaTableEdit_SeqOperateSetData: datas })
                                    } else {
                                        workflowFlowStore.setState({ WeaTableEdit_SeqOperateSetData: data })
                                    }

                                }}
                                onCopy={(ks, ds) => { }}
                                onDelete={(ks, ds) => { }}
                                onChange={(datas) => {
                                    workflowFlowStore.setState({ WeaTableEdit_SeqOperateSetData: datas })
                                }}
                            />
                        </div>
                    ),
                    hide: newDeploymentForm.isHide(newDeploymentForm, (keys, allParams) => {
                        return (false);
                    })
                });
            }
            group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@nkxe50integrationWorkflowDeployForm${i}`} center={i == 1 ? false : true} col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />);
            i++;
        });
        return group;
    }

    render () {
        const { workflowFlowStore } = this.props;
        const { showDeploymentDialog } = toJS(workflowFlowStore.status);
        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@h4ki8e`}
                title={`${getLabel('83319', '流程接口部署')}`}
                icon='icon-coms-integration'
                iconBgcolor='#1a57a0'
                visible={showDeploymentDialog}
                hasScroll={true}
                style={{ width: 900, height: 600 }}
                onCancel={() => {
                    workflowFlowStore.setState({ showDeploymentDialog: false });
                    workflowFlowStore.newDeploymentForm.reset();
                }}
                buttons={this.getBtns()}
                moreBtn={{
                    datas: this.getRightMenu(),
                    collectParams: []
                }}
            >
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@dnamfg`}
                    datas={this.getRightMenu()}
                    collectParams={[]}
                >
                    {this.getSearchs()}
                </WeaRightMenu>
            </WeaDialog>
        )
    }
}
