import React from "react";
import {inject, observer} from "mobx-react";
import {Button, Row} from "antd";
import {toJS} from "mobx";
import {
    WeaSearchGroup,
    WeaFormItem,
    WeaTools,
    WeaRightMenu,
    WeaDialog,
    WeaLocaleProvider,
    WeaHelpfulTip,
    WeaSteps,
    WeaNewScroll,
    WeaTable,
} from "ecCom";
import {WeaSwitch} from "comsMobx";
import './style/index.css';

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

@inject("workflowFlowStore")
@observer
export default class TestDialog extends React.Component{

    getColumns = (columns) => {
        let datas = [];
        columns && columns.map(column => {
            if(column['key'] == 'status') {
                datas.push({
                    dataIndex: column['dataIndex'],
                    key: column['key'],
                    sorter: column['sorter'],
                    title: column['title'],
                    render: (text, record) => {
                        if(text == '1') {
                            return <span style={{color: 'green'}}>√</span>
                        }else if(text == '0') {
                            return <nobr><span style={{color: 'red'}}>×</span>{record.details != undefined ? <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@6wa6d9`} style={{marginLeft: 10}}  title={record.details}/> : ''}</nobr>
                        }else if(text == '2') {
                            return <nobr><span style={{color: '#FAA825'}}>!</span>{record.details != undefined ? <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@dohw7l`} style={{marginLeft: 10}}  title={record.details}/> : ''}</nobr>
                        }
                    }
                })
            }else {
                datas.push({
                    dataIndex: column['dataIndex'],
                    key: column['key'],
                    sorter: column['sorter'],
                    title: column['title']
                })
            }
        });

        return datas;
    };

    /**
     * 渲染tab页面
     * @returns {Array}
     */
    getTest = (baseTabKey) => {
        const {workflowFlowStore} = this.props;
        const {status,sqlTextForm} = workflowFlowStore;
        const {form, condition} = sqlTextForm;
        const {isFormInit} = form;
        const {testColumns, testTitle, testInitDatas} = toJS(status);

        if (baseTabKey == 'base') {
            let group = [];
            let items = [];
            for(let key in testInitDatas) {
                items.push({
                    com: (<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@rmb7i3@integrationWorkflowTestTab${baseTabKey}${key}`}>
                        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@lqneoh@integrationWorkflowTestTab${baseTabKey}${key}`}
                            columns={this.getColumns(testColumns)}
                            dataSource={testInitDatas[key]}
                            pagination={false}
                        /></Row>),
                    colSpan: 1
                });
                group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@1q989l@integrationWorkflowTestTab${baseTabKey}${key}`} col={1} needTigger={true} showGroup={true} title={testTitle[key]} items={items}/>);
            }
            return group;
        }else if (baseTabKey == 'param') {
            let group = [];
            let items = [];
            isFormInit && condition && condition.map((c, index) => {
                c.items.map((field) => {
                    items.push({
                        com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@wzdjii@integrationWorkflowTestTab${baseTabKey}${field.domkey[0]}`}
                            label={`${field.label}`}
                            labelCol={{span: 5, offset: 2}}
                            wrapperCol={{span: 15}}
                            error={form.getError(field)}
                            tipPosition="bottom"
                            style={{padding: 10,}}
                        >
                            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@drq6ww@integrationWorkflowTestTab${baseTabKey}${field.domkey[0]}`} fieldConfig={field} form={form} formParams={form.getFormParams()}/>

                        </WeaFormItem>),
                        colSpan: 1
                    })
                });
                group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@uzzlqq@integrationWorkflowTestTab${baseTabKey}${index}`} center col={1} needTigger={true} title={c.title}
                                           showGroup={c.defaultshow}
                                           items={items}/>);
            });
            return <div style={{paddingTop: 15}}>{group}</div>
        }else if (baseTabKey == 'preview') {
            let group = [];
            isFormInit && condition && condition.map((c, index) => {
                c.items.map((field) => {
                    group.push(<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@we09v9@integrationWorkflowTestTab${baseTabKey}${field.domkey[0]}`}
                            label={`${field.label}`}
                            labelCol={{span: 5, offset: 4}}
                            wrapperCol={{span: 8}}
                            error={form.getError(field)}
                            tipPosition="bottom"
                            style={{padding: 15}}
                            className={(["dmlsql"]).includes(getKey(field)) ? 'specialCol_workflow' : 'normalCol'}
                        >
                            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@o62mbz@integrationWorkflowTestTab${baseTabKey}${field.domkey[0]}`} fieldConfig={field} form={form} formParams={form.getFormParams()}/>

                        </WeaFormItem>)
                });
            });
            return  <div style={{paddingTop: 25,paddingBottom:25,}}>{group}</div>;
        }
    };

    /**
     * 获取数据
     * @returns {*}
     */
    getTable = () => {
        const {workflowFlowStore} = this.props;
        const {status} = workflowFlowStore;
        const {topinfo,currentStep} = toJS(status);

        if (topinfo && topinfo.tab) {
            let group = [];
            let items = [];
            topinfo.tab.datas.map((c, index)=>{
                items.push(
                    <Step ecId={`${this && this.props && this.props.ecId || ''}_Step@gnlzgh@integrationWorkflowTestTab${c.id || c.key || index}`} description = {c.title}></Step>
                )
            });
            group.push(
                <WeaSteps ecId={`${this && this.props && this.props.ecId || ''}_WeaSteps@v28ajo@integrationWorkflowTestTabDatas`} current={currentStep}>
                    {items}
                </WeaSteps>
            );
            return (
                //<WeaTab {...topinfo.tab}
                //            onChange={tabKey => {
                //                setTimeout(function(){
                //                    topinfo.tab.selectedKey = tabKey;
                //                    workflowFlowStore.setState({
                //                        baseTabKey:tabKey,
                //                        topinfo: topinfo,
                 //                       testInitDatas: {},
                //                        errorMessage: '',
               //                     });
               //                     workflowFlowStore.initSqlTestForm();
                //                    workflowFlowStore.getTestFields(tabKey);
                 //                   let bool = workflowFlowStore.hasFormParam();
                 //                   if (bool) {
                 //                       workflowFlowStore.getTestMenu2(tabKey);
//
                  //                  } else {
                   //                     workflowFlowStore.getTestMenu(tabKey);
                    //                }
                   //                 workflowFlowStore.getTestForm(tabKey);
                  //              }, 300)
                 //           }}
               // />
                <div style={{marginLeft: 25, marginTop: 30, height: 100}}>
                    {group}
                </div>
            );
        }
    };

    //下一步操作
    onRightMenuClick = (type) => {
        const {workflowFlowStore} = this.props;
        const {status,sqlTextForm,previewTextForm} = workflowFlowStore;
        const {form, condition} = sqlTextForm;
        const {errorMessage} = toJS(status);

        switch(type) {
            case "BTN_NEXT_STEP20":
                workflowFlowStore.getTestFields("preview");
                workflowFlowStore.getTestMenu2("preview");
                workflowFlowStore.setState({
                    currentStep: 1,
                    baseTabKey:'preview',
                });
                break;
            case "BTN_LAST_STEP20":
                workflowFlowStore.getTestFields("base");
                workflowFlowStore.getTestMenu2("base");
                workflowFlowStore.getTestForm("base");
                workflowFlowStore.setState({
                    currentStep: 0,
                    baseTabKey:'base',
                });
                break;
            case "BTN_NEXT_STEP00":
                workflowFlowStore.getTestFields("param");
                workflowFlowStore.getTestMenu("param");
                workflowFlowStore.setState({
                    currentStep: 1,
                    baseTabKey:'param',
                });

                break;
            case "BTN_LAST_STEP00":
                workflowFlowStore.getTestFields("base");
                workflowFlowStore.getTestMenu("base");
                workflowFlowStore.getTestForm("base");
                workflowFlowStore.setState({
                    currentStep: 0,
                    baseTabKey:'base',
                });

                break;
            case "BTN_LAST_STEP01":
                workflowFlowStore.getTestFields("param");
                workflowFlowStore.getTestMenu("param");
                workflowFlowStore.setState({
                    currentStep: 1,
                    baseTabKey:'param',
                    errorMessage: '',
                    errorMessage2:'',
                });

                break;
            case "BTN_NEXT_STEP01":
                if (errorMessage == '') {
                    workflowFlowStore.saveParams(JSON.stringify(form.getFormParams()),);
                }
                // form.validateForm().then(f => {
                //     if (f.isValid) {
                //
                //     } else {
                //         f.showErrors();
                //         this.setState({date: new Date()});
                //     }
                // });
                break;
        }
    };

    //测试页面操作按钮
    getRightMenu = () => {
        const {workflowFlowStore} = this.props;
        const {menuinfo} = toJS(workflowFlowStore.status);
        let btnArr = [];
        menuinfo && menuinfo.map(m => {
            btnArr.push({
                key: m.type,
                icon: <i className={m.menuIcon}/>,
                content: m.menuName,
                onClick: () => this.onRightMenuClick(m.type)
            });
        });
        return btnArr;
    };

    /**
     * 渲染按钮
     * @returns {Array}
     */
    getButtons = () => {
        const {workflowFlowStore} = this.props;
        const {buttoninfo} = toJS(workflowFlowStore.status);

        let btnArr = [];
        buttoninfo && buttoninfo.map(b => {
            btnArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@xoxzjf@integrationWorkflowTestButton${b.type}`} type={b.btnType} onClick={() => this.onRightMenuClick(b.type)}>
                    {b.btnName}
                </Button>
            );
        });
        return btnArr;
    };

    /**
     * 更多按钮
     * @returns {Array}
     */
    getMoreBtn = () => {
        const {workflowFlowStore} = this.props;
        const {moreBtninfo} = toJS(workflowFlowStore.status);
        let btnArr = [];
        moreBtninfo && moreBtninfo.map(m => {
            btnArr.push({
                key: m.key,
                icon: <i className={m.icon}/>,
                content: m.btnName,
                onClick: () => this.onRightMenuClick(m.type)
            });
        });
        return btnArr;
    };

    /**
     * 错误信息描述
     * @returns {*}
     */
    getErrorMessage = () => {
        const {workflowFlowStore} = this.props;
        const {status} = workflowFlowStore;
        const {errorMessage,errorMessage2} = toJS(status);

        return <h3 style={{color: 'red', textAlign: 'center',}}>{errorMessage==''?errorMessage2:errorMessage}</h3>
    };

    render() {
        const {workflowFlowStore} = this.props;
        const {status} = workflowFlowStore;
        const {showTestVersion, topinfo, collectinfo, errorMessage,errorMessage2,baseTabKey} = toJS(status);
        //console.log("errorMessage=============="+errorMessage);
       // console.log("errorMessage2=============="+errorMessage2);
        return(
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@nw208u`}
                title={getLabel(513424, "流程流转集成测试")}
                icon={"icon-coms-integration"}
                iconBgcolor={"#1a57a0"}
                style={{width: 800, height: 600}}
                visible={showTestVersion}
                hasScroll={true}
                onCancel={() => {
                    workflowFlowStore.initTestForm();
                    workflowFlowStore.initSqlTestForm();
                }}
                buttons={this.getButtons()}
                moreBtn={{
                    datas: this.getMoreBtn(),
                    collectParams: collectinfo
                }}
            >

                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@uomfj1`} datas={this.getRightMenu()} collectParams={collectinfo}>
                    {this.getTable()}
                    <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@l6ncw3`} height={550}>
                        {errorMessage == '' && errorMessage2 == '' ? this.getTest(baseTabKey) : this.getErrorMessage()}

                    </WeaNewScroll>
                </WeaRightMenu>

            </WeaDialog>
        )
    }
}