/**
 * @author jh
 */


import { observable, action, toJS } from 'mobx';
import { message, Modal } from 'antd';
import { WeaLocaleProvider } from 'ecCom';

import { ListStore } from './listStore';
import * as API from '../../apis/userDefaultSettingApi';

const getLabel = WeaLocaleProvider.getLabel;

export default class UserPhraseEditStore extends ListStore {
    @observable visiable = false;
    @observable phraseDescValue ='';
    @observable saveDisable = false;
    @observable success = -1; // -1无权限；0异常；1成功

    conditions = [];

    phraseId = '';

    constructor() {
        super();
        this.onEdit = this.onEdit.bind(this);
        this.onCancelEdit = this.onCancelEdit.bind(this);
        this.richTextOnChange = this.richTextOnChange.bind(this);
    }


    /**
     * 获取设置信息
     * @param id
     */
    onEdit(id = '', defaultRemark) {
        const para = {
            id,
        };
        API.doEdit(para).then((reVal) => {
            super.resetForm();
            this.form.initFormFields(reVal.conditions);
            this.conditions = reVal.conditions;
            this.phraseDescValue = defaultRemark || reVal.phraseDescValue;
            // this.visiable = true;
            this.phraseId = id;
            this.success = reVal.success;
        });
    }

    /**
     * 保存
     */
    onSave(callFun) {
        if (this.realLength(this.phraseDescValue) > 4000) {
            Modal.warning({ title: getLabel(131329, '信息确认'), okText: getLabel(33703, '确认'), content: getLabel(385840, '文本长度不能超过4000(1个中文字符等于3个长度)') });
            return;
        }
        this.form.validateForm().then((f) => {
            if (f.isValid) {
                this.saveDisable = true;
                const para = {
                    id: this.phraseId,
                    phraseDesc: this.phraseDescValue,
                };
                const formPara = { ...this.form.getFormParams(), ...para };
                API.doSave(formPara).then((reVal) => {
                    message.success(reVal.msg);
                    this.onCancelEdit();
                    this.saveDisable = false;
                    callFun && callFun();
                });
            } else {
                f.showErrors();
            }
        });
    }
    /**
     * 关闭编辑弹框
     */
    onCancelEdit() {
       this.visiable = false;
    }

    /**
     * 富文本编辑器
     */
    richTextOnChange(desc = '') {
        this.phraseDescValue = desc;
    }

    realLength(str) {
        let j = 0;
        for (let i = 0; i <= str.length - 1; i++) {
            j += 1;
            if ((str.charCodeAt(i)) > 127) {
                j += 2;
            }
        }
        return j;
    }
    @action
    setStates = (states = {}) => {
        const keys = Object.keys(states);
        keys.forEach((key) => {
            this[key] = states[key];
        });
    }
}
