/**
 * @author jh
 * @desc 编辑字段页面组件
 *
 */
import React from "react";
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import {WeaSwitch} from 'comsMobx';
import {Button, Row, Modal} from 'antd';
import {
    WeaTools,
    WeaDialog,
    WeaCollect,
    WeaRichText,
    WeaFormItem,
    WeaRightMenu,
    WeaMoreButton,
    WeaSearchGroup,
    WeaLocaleProvider,
    WeaAlertPage,
} from 'ecCom';

import {RichTextTitle} from "./RichTextTitle";

import isRegExp from 'lodash/isRegExp';
const getLabel = WeaLocaleProvider.getLabel; 


@observer
export class UserPhraseEdit extends React.Component {

    constructor(props) {
        super(props);

        this.getDialogBtns.bind(this);

        this.state = {
            isRequired: 'required',
            showCollect: false,
        }
    }

    render() {
        const {store,visiable,setVisiable} = this.props;
        const {
            // visiable,
            onCancelEdit,
            form,
            success,
            conditions,
            richTextOnChange,
            phraseDescValue
        } = store;

        const formParams = form.getFormParams();
        const {isRequired, showCollect} = this.state;

        let conditionGroup = [];
        let extentsConfig = [];
        this.initExtentsConfig(extentsConfig);

        if(success == -1){
            conditionGroup.push(
                <WeaAlertPage
                    icon={<i className="icon-coms-locking" style = {{color : 'rgb(203, 203, 203)'}}/>}
                    iconSize = {120}
                    paddingTop ={'15%'}
                >
                    <div style = {{color : 'rgb(154, 154, 154)',paddingTop:"10px"}}>
                        对不起，您暂时没有权限 ！
                    </div>
                </WeaAlertPage>
            );
        }else if(success == 0){
            conditionGroup.push(
                <WeaAlertPage
                    icon={<i className="icon-coms-locking" style = {{color : 'rgb(203, 203, 203)'}}/>}
                    iconSize = {120}
                    paddingTop ={'15%'}
                >
                    <div style = {{color : 'rgb(154, 154, 154)',paddingTop:"10px"}}>
                        发生异常，请刷新重新或联系管理员
                    </div>
                </WeaAlertPage>
            )
        }else{
            form.isFormInit && conditions && conditions.map((g, index) => {

                index == 0 ? conditionGroup.push(
                    <WeaSearchGroup
                        needTigger={true}
                        title={g.title}
                        center
                        showGroup={g.defaultshow}
                    >
                        {
                            g.items && g.items.map((item) => {
                                if(item.domkey[0] === 'dsporder'){
                                    item.regExp = /^(-{0,1}|(-{0,1}[0-9]{1,}[.]?[0-9]*))$/;
                                }
                                return (
                                    <Row>
                                        <WeaFormItem
                                            label={`${item.label}`}
                                            labelCol={{span: `${item.labelcol}`}}
                                            wrapperCol={{span: `${item.fieldcol}`}}
                                            error={form.getError(item)}
                                            tipPosition={'bottom'}
                                        >
                                            <WeaSwitch
                                                fieldConfig={item}
                                                form={form}
                                                formParams={formParams}
                                            />
                                        </WeaFormItem>
                                    </Row>
                                )
                            })
                        }
                    </WeaSearchGroup>
                    )
                    :
                    conditionGroup.push(
                        <WeaSearchGroup
                            needTigger={true}
                            title={<RichTextTitle isRequired={isRequired}/>}
                            showGroup={g.defaultshow}
                        >
                            <WeaRichText
                                onChange={this.onChange.bind(this)}
                                value={phraseDescValue}
                                ckConfig={this.getCkConfig()}
                                extentsConfig={extentsConfig}
                                onToolsChange={this.buttonBtnChange.bind(this)}
                                ref={'WeaRichText'}
                            />
                        </WeaSearchGroup>
                    )
            });
        }

        return (
            <WeaDialog
                title={getLabel(84562, '添加常用批示语')}
                visible={visiable}
                icon='icon-coms-workflow'
                iconBgcolor='#0079DE'
                onCancel={() => {
                    onCancelEdit();
                    setVisiable(false);
                }}
                buttons={this.getDialogBtns()}
                style={{width: 800, height: 600}}
                draggable={true}
            >
                <WeaRightMenu
                    datas={this.getMoreBtns()}
                >
                    {conditionGroup}
                </WeaRightMenu>
                {/*收藏*/}
                <WeaCollect
                    visible={showCollect}
                    favname=''
                    favouritetype={'5'}
                    importantlevel={1}
                    onClose={() => this.setState({showCollect: false})}
                    submitBack={data => console.log('onOk: ', data)}
                />
            </WeaDialog>
        );
    }

    buttonBtnChange(name = '', ids = '', list = [], type = '',addfileid=''){
        let returnInfo = [];
        if(name === 'Upload'){
            if(type === 'image'){
                list.map(item => {
                    const imglink  = `/weaver/weaver.file.FileDownload?fileid=${item.fileid}`;
                    returnInfo.push(`<img src='${imglink}' data-imgsrc='${imglink}' alt=''/>&#8203;`);
                });
                this.refs.WeaRichText.insertHTML(returnInfo.join(''));
            }
        }
        return ' ';
    }
    /**
     * 保存
     */
    doSave() {
        const {isRequired} = this.state;
        if (isRequired == 'required') {
            Modal.warning({title:getLabel(131329,'信息确认'),okText: getLabel(33703, '确认'), content: getLabel(384146, '必要信息不完整，红色*为必填项')});
            return;
        }
        const {store, saveCallBack} = this.props;
        const {form} = store;
        const formParams  = form.getFormParams();
        const {groupid = '', dsporder = 0} =formParams;
        if(groupid == '1' && dsporder < 0) {
            Modal.warning({title:getLabel(131329,'信息确认'),okText: getLabel(33703, '确认'), content: getLabel(385772, '显示顺序不能为负数！')});
            return;
        }

        store.onSave(saveCallBack);//weaworkflow_userdefault_store.getConditionInfo
    }

    /**
     * 富文本编辑器输入onChange事件
     * @param desc
     */
    onChange(desc = '') {

        const {store} = this.props;
        const {richTextOnChange} = store;
        richTextOnChange(desc);
        this.setState({
            isRequired: desc === '' ? 'required' : ''
        });

    }

    /**
     * 富文本编辑器配置参数
     * @returns {{height: number, toolbar: string, toolbar_Full: *[]}}
     */
    getCkConfig() {
        return {
            height: 240,
            removePlugins:'resize',
            toolbar: [{name: 'document', items: ['Source']},
                {name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike',]},
                {name: 'styles', items: ['Font', 'FontSize']},
                {name: 'colors', items: ['TextColor', 'BGColor']},
                {
                    name: 'paragraph',
                    items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']
                },
                {name: 'links', items: ['Link', 'Unlink']},
                {name: 'tools', items: ['Maximize']},
                {name: 'insert', items: ['Table', '-', 'Undo', 'Redo']}]

        };
    }

    getDialogBtns() {
        const {store} = this.props;
        return [
            (
                <Button
                    type="primary"
                    disabled={store.saveDisable}
                    onClick={this.doSave.bind(this)}>{getLabel(30986, '保存')}
                </Button>),
            (<WeaMoreButton datas={this.getMoreBtns()}/>)
        ];
    }

    initExtentsConfig(extentsConfig) {
        extentsConfig.push({
            name: 'Upload',
            type: 'image',
            show: <div className="wea-cb-item">
                <span className={`wea-cbi-icon cke_button_icon cke_button__image_icon`}/>
            </div>,
            uploadUrl: '/api/doc/upload/uploadFile',
            category: 'all',
            limitType: 'jpg,gif,png',
            title: getLabel(20001, '上传图片'),
            needLoading: false
        });
    }

    getMoreBtns() {
        return [{
            key: "save",
            icon: <i className='icon-workflow-Right-menu-Preservation'/>,
            content: getLabel(30986, '保存'),
            onClick: () => {
                this.doSave();
            }
        }, {
            key: "coll",
            icon: <i className='icon-coms-Collection'/>,
            content: getLabel(28111, '收藏'),
            onClick: () => {
                this.setState({
                    showCollect: true,
                });
            }
        }
        ];
    }

}


