import React from "react";
import {inject, observer} from "mobx-react";
import {Button, message} from "antd";
import {toJS} from "mobx";
import {WeaForm, WeaSwitch} from "comsMobx";
import {
    WeaDialog,
    WeaFormItem,
    WeaLocaleProvider,
    WeaRightMenu,
    WeaSearchGroup,
    WeaTools
} from "ecCom";

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

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



    getBtns = () => {
        let btns = []
        btns = [
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ogr8ny@integrationWorkflowarchiveNewFormButtonSave`} type='primary' onClick={() => this.onRightMenuClick('BTN_SAVE')}>{getLabel(86,'保存')}</Button>
          ,<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@a2n6ky@integrationWorkflowarchiveNewFormButtonSaveAndOpen`} type='primary' onClick={() => this.onRightMenuClick('BTN_SAVE_AND_OPEN')}>{getLabel(125540,'保存后详细设置')}</Button>
        ];

        return btns;
    }
    getRightMenu() {
        const {archiveStore} = this.props;
        let btnArr = [
            {
                key: 'BTN_SAVE',
                icon: <i className='icon-coms-Preservation'/>,
                content : `${getLabel(86,'保存')}`,
                onClick : () => this.onRightMenuClick('BTN_SAVE')
            },
            {
                key: 'BTN_SAVE_AND_OPEN',
                icon: <i className='icon-coms-Preservation'/>,
                content : `${getLabel(125540,'保存后详细设置')}`,
                onClick : () => this.onRightMenuClick('BTN_SAVE_AND_OPEN')
            },
        ]
        return btnArr;
    }
    onRightMenuClick = (type,recordId) => {
        const {archiveStore} = this.props;
        const {newForm, status} = archiveStore;
        const { ArchiveFormHiddenFields } = toJS(archiveStore.status);


        if(type == 'BTN_SAVE'){
            newForm.validateForm().then(f=>{
                if(f.isValid){
                    //合并hiddenfield参数
                    let params = Object.assign(ArchiveFormHiddenFields, newForm.getFormParams());
                    params.operation = "add";
                    if(params.id&&params.id.length>0) {
                        params.operation = "edit";
                    }
                    // console.log(params);
                    archiveStore.getArchiveRegisterOperation(params, (result) => {
                        let msg = `${getLabel('22619', '保存成功')}`;
                        message.success(msg);
                        archiveStore.setState({ showNewFormDialog: false })
                      });
                }else{
                    f.showErrors();
                    this.setState({date: new Date()});
                }
            });

        }else if(type == 'BTN_SAVE_AND_OPEN'){
            newForm.validateForm().then(f=>{
                if(f.isValid){
                    //合并hiddenfield参数
                    let params = Object.assign(ArchiveFormHiddenFields, newForm.getFormParams());
                    params.operation = "add";
                    archiveStore.getArchiveRegisterOperation(params,(result)=>{
                        archiveStore.newForm=new WeaForm();
                        archiveStore.getArchiveRegisterEditForm({ id: result.id });
                        archiveStore.setState({ showNewFormDialog: false });
                        if(result.ProTypeId=='0'){
                            archiveStore.getArchiveRegisterEditFormFieldXMLMapping({ id: result.id });
                        }else{
                            archiveStore.getArchiveRegisterEditFormFieldDBMapping({ id: result.id });
                        }


                        archiveStore.setState({ showNewDetailFormDialog: true, newDetailSelectedKey: 1, proType: result.ProTypeId});
                    });
                }else{
                    f.showErrors();
                    this.setState({date: new Date()});
                }
            });
        }
    }

    getSearchs = () => {
        const {archiveStore} = this.props;
        const {newForm, status} = archiveStore;
        const {ArchiveFormFields} = toJS(status);
        const {isFormInit} = newForm;
        let group = [];
        let i = 0;
        const formParams = newForm.getFormParams();
        isFormInit && ArchiveFormFields && ArchiveFormFields.map(c =>{
            let items = [];

            c.items.map(fields => {

                items.push({
                    com:(
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@9e4oxo@integrationWorkflowarchiveNewForm${fields.domkey[0]}`}
                            label={`${fields.label}`}
                            labelCol={{span: `${fields.labelcol}`}}
                            wrapperCol={{span: `${fields.fieldcol}`}}
                            error={newForm.getError(fields)}
                            tipPosition="bottom"
                        >

                            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@9fogym@integrationWorkflowarchiveNewForm${fields.domkey[0]}`} fieldConfig={fields} form={newForm} formParams={formParams}  onChange={v=> {
                                if(getKey(fields) === 'expid' ) {
                                    archiveStore.getArchiveRegisterOperation({operation:'ExpGetProInf',Proid:newForm.getFormParams().expid},(result)=>{
                                        if(result&&result.ExpGetProInf&&result.ExpGetProInf.indexOf("#")>0) {
                                            newForm.updateFields({proType:  (result.ExpGetProInf).split("#")[0]});
                                            newForm.updateFields({proFileSaveType:  (result.ExpGetProInf).split("#")[1]});
                                        }else{
                                            newForm.updateFields({proType:  ''});
                                            newForm.updateFields({proFileSaveType:  ''});
                                        }
                                    });
                                }
                            }} />
                        </WeaFormItem>),
                    colSpan:1,
                    hide: newForm.isHide(fields, (keys, allParams) => {
                        let bool = false;
                        if(allParams.isview=="1"){
                            if(getKey(fields) === 'requestid' || getKey(fields) === 'FTriggerFlag'
                                || getKey(fields) === 'FTriggerFlagValue' || getKey(fields) === 'isupdatewfdataField'){
                                bool=true;
                            }
                        }
                        getKey(fields) === 'requestid' && allParams.datarecordtype == '1' && (bool = true);
                        getKey(fields) === 'FTriggerFlag' && allParams.datarecordtype == '1' && (bool = true);
                        getKey(fields) === 'FTriggerFlagValue' && allParams.datarecordtype == '1' && (bool = true);

                        getKey(fields) === 'isupdatewfdataField' && allParams.isupdatewfdata == '1' && (bool = true);
                        return bool;
                    })
                });

            })

            group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@brifam@integrationWorkflowarchiveNewForm${i}`} center  col={1}  needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>);
            i++;
        });
        return group;
    }

    render() {
        const {archiveStore} = this.props;
        const {showNewFormDialog} = toJS(archiveStore.status);
        return (

            <div className='wea-integration-single'>
              <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@9vgttr`}
                  title={ `${getLabel( '33925,127023' ,'归档流程注册信息')}` }
                  icon='icon-coms-integration'
                  iconBgcolor='#1a57a0'
                  visible={showNewFormDialog}
                  hasScroll={true}
                  style={{width: 900, height: 600}}
                  onCancel={()=> {
                      archiveStore.setState({showNewFormDialog : false});
                      archiveStore.newForm.reset();
                  }}
                  buttons={this.getBtns()}
                  moreBtn={{
                      datas :this.getRightMenu(),
                      collectParams: []
                  }}
              >
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@sarudz`}
                    datas={this.getRightMenu()}
                    collectParams={[]}>


                    {this.getSearchs()}


                </WeaRightMenu>
              </WeaDialog>
            </div>
        )
    }
}
