import {
    action,
    computed,
    observable,
} from 'mobx';
import {
    WeaForm,
    WeaTableNew,
} from 'comsMobx';
import {
    WeaHelpfulTip,
    WeaLocaleProvider,
} from 'ecCom';
import {
    message,
    Button,
} from 'antd';
import {
    fetch,
    getMenusCreationConfig,
    getTopButtons,
    getDropMenuDatas,
} from '../util/save-time-util.js';
import * as asyncFetch from '../apis/staffCareReminder';
import { FormStore, DialogStore } from "../public/valhalla/stores/index.js";
import { BirthEditor } from "../components/birthEditor/stores/index.js";
import { i18n } from '../public/i18n.js'
const getLabel = WeaLocaleProvider.getLabel;
const {
    TableStore
} = WeaTableNew;

export class HrmStaffCareReminder {
    //************权限*************
    @observable pageAccessPermission = {
        hasRight: false,
        loading: true,
        btnMenu: [],
    }
    //获取页面权限
    @action getPermissionInfo = () => {
        fetch({
            asyncFetch,
            name: 'getHasRight',
            logic: (cb) => {
                ['hasRight', 'btnMenu', 'loading'].map((v, i) => {
                    this.pageAccessPermission[v] = (i < 2) ? cb[v] : false
                });
            }
        });
    }

    @action resetAccessPermissionProps = () => {
        ['hasRight', 'btnMenu', 'loading'].map((v, i) => {
            let value;
            if (i === 0) {
                value = false;
            } else if (i === 1) {
                value = [];
            } else {
                value = true;
            }
            this.pageAccessPermission[v] = value;
        });
    }

    //*************头部**************
    toptitle = () => getLabel('391180', "员工关怀提醒");

    topComponentStaticProps = {
        icon: <i className='icon-coms-hrm'/>,
        iconBgcolor: '#217346',
        showDropIcon: true,
    }

    @computed get menusCreationConfig() {
        const {
            btnMenu
        } = this.pageAccessPermission;

        return getMenusCreationConfig(btnMenu);
    }

    //Top组件的按钮
    get topButtons() {
        const {
            topMenu
        } = this.menusCreationConfig;

        return getTopButtons.call(this, {
            datas: topMenu,
            disabled: this.getMenusState(),
        })
    }

    //获取右键菜单和top组件下拉菜单的数据
    get dropMenuDatas() {
        const {
            rightMenu
        } = this.menusCreationConfig;


        return getDropMenuDatas.call(this, {
            datas: rightMenu,
            disabled: this.getMenusState(),
        });

    }

    //获取交互元素（按钮元素和下拉菜单元素）的状态
    getMenusState = () => {
        const {
            loading
        } = this.formElements;

        //决定按钮是否可点击
        return [loading];
    }

    save = () => {
        const {
            form
        } = this.formElements, {
            selectedKey
        } = this.tab, {
            activeKey
        } = this.tabs;

        let name, fetchParams = {
            ...form.getFormParams()
        };

        if (selectedKey === '0') {
            if (activeKey === '0') {
                name = 'saveSysRemind';
            } else {
                this.saveStaffRemindForm();
                return;
            }
        } else {
            name = 'save';
            const {
                entryCongrats
            } = fetchParams;
            Object.assign(fetchParams, {
                index: this.picture.index,
                entryCongrats: `[${entryCongrats}]`
            })
        }

        form.validateForm().then(f => {
            if (f.isValid) {
                fetch({
                    asyncFetch,
                    name,
                    fetchParams,
                    logic: (cb) => {
                        const {
                            sign
                        } = cb

                        message[sign === '1' ? 'success' : 'warning'](cb.message);
                    }
                });
            } else {
                f.showErrors();
                this.forceUpdateForm();
            }
        })
    }

    custom = () => {
        const {
            comsWeaTableStore
        } = this.table;

        ['setColSetVisible', 'tableColSet'].map(v => {
            comsWeaTableStore[v](true);
        });
    }

    log = () => {
        const {
            activeKey
        } = this.tabs;

        window.setLogViewProps({
            logSmallType: (activeKey === '0') ? '3026' : '3027',
        });
    }

    @action forceUpdateForm = () => {
        this.formElements.date = new Date();
    }


    //***************页签*****************
    @observable datas = [{
        key: '0',
        title: getLabel('391181', "生日提醒")
    }, {
        key: '1',
        title: getLabel('391182', "入职周年提醒")
    }];

    tabStaticProps = {
        keyParam: 'key',
        onChange: (key) => this.handleTabChange(key)
    };

    @observable tab = {
        selectedKey: '0',
    }

    @action handleTabChange = (key) => {
        const {
            selectedKey
        } = this.tab;
        this.tab.selectedKey = key;

        key === '0' && this.handleTabsChange('0');

        this.getFormMaterial();
    }

    //***************二级页签*****************
    tabsStaticProps = {
        type: 'card',
        onChange: (key) => this.handleTabsChange(key)
    };

    @observable tabs = {
        activeKey: '0',
    }

    @action handleTabsChange = (key) => {
        const {
            activeKey
        } = this.tabs;

        this.tabs.activeKey = key;

        const formConfig = {
            isCustomRender: true,
            api: asyncFetch.getStaffRemindForm
        };

        const srfs = this.staffRemindFormStore;
        srfs.init(formConfig);
        srfs.fetchForm({}, res => { 
            this.dispatchImg = this.getImgSrc(res.imgId) 
            this.dispatchImgId = res.imgId
        });

        this.getFormMaterial();
    }

    getImgSrc = (fileid) => {
        return fileid ? `/weaver/weaver.file.FileDownload?fileid=${fileid}` : '';
    }

    //**************表单****************
    formConfig = {
        dynamicFields: [{
            passiveKey: 'showtitle',
            activeKey: 'remindtype',
            showValue: '1'
        }, {
            passiveKey: 'showtitle2',
            activeKey: 'remindtype',
            showValue: '2'
        }, {
            passiveKey: 'greetings',
            activeKey: 'remindtype',
            showValue: '1'
        }, {
            passiveKey: 'greetings2',
            activeKey: 'remindtype',
            showValue: '2'
        }, {
            passiveKey: 'colColor',
            activeKey: 'remindtype',
            showValue: '2'
        }, {
            passiveKey: 'greColor',
            activeKey: 'remindtype',
            showValue: '2'
        }]
    }

    @computed get entryFormConfig() {
        const {
            tips
        } = this.formElements;

        return {
            transverseSiblingComponents: {
                'entryCongrats': (<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@ch96jq`}
                            width =  {196} 
                            style={{position: 'absolute',top: 14,left: '103%'}}
                            title={<ul>{tips.map(tip => <li>{tip}</li>)}</ul>}
                />)
            },
        }
    }

    @observable formElements = {
        conditions: [],
        form: new WeaForm(),
        loading: false,
        date: new Date(), //用来刷新form组件
        explain: [],
        fontFamilys: [],
        tips: [],
    }

    //获取表单数据
    @action getFormMaterial = () => {
        const {
            selectedKey
        } = this.tab, {
            activeKey
        } = this.tabs;

        const {
            form
        } = this.formElements;
        if (form.isFormInit) {
            this.resetForm();
        }

        this.formElements.loading = true;

        let name;
        if (selectedKey === '0') {
            name = (activeKey === '0') ? 'getSysRemindForm' : 'getEpRemindForm'
        } else {
            name = 'getEntryRemindForm';
        }

        fetch({
            asyncFetch,
            name,
            logic: (cb) => {
                const {
                    condition,
                    conditions,
                    sessionkey,
                    explain,
                    imglist,
                    tips,
                } = cb;

                this.processCondition(condition || conditions);

                this.formElements.loading = false;
                this.formElements.conditions = condition || conditions;
                this.formElements.form.initFormFields(condition || conditions);

                if (explain) this.formElements.explain = explain;

                if (imglist) {
                    ['selectedid', 'index', 'defaultImg', 'imglist'].map((v, i) => {
                        this.picture[v] = (i < 3) ? imglist[v] : imglist;
                    });
                }

                if (tips) {
                    tips.splice(1,0,getLabel(530025,'单行文字不宜过长，文字过长请做换行处理。'))
                    this.formElements.tips = tips;
                }

                sessionkey && this.table.comsWeaTableStore.getDatas(sessionkey, 1);
            }
        });
    }

    processCondition = (conditions) => {
        conditions.map(c => {
            c.items.map(item => {
                const key = item.domkey[0];
                if (key === 'days') {
                    item.fieldcol = 16;
                }
                if (['greetings', 'greetings2', 'remindlevel'].includes(key)) {
                    item.fieldcol = 14;
                }
                if (key === 'entryFont') {
                    item.options[0].showname = '默认';
                    this.formElements.fontFamilys = item.options;
                }
                if (['showtitle', 'showtitle2'].includes(key)) {
                    item.options[0].disabled = true;
                }
                if (key === 'entryCongrats') {
                    const {
                        value
                    } = item;
                    const index = value.indexOf('[');
                    let str;
                    if (index > -1) {
                        str = value.substr(index + 1);
                    }
                    const lastIndex = str ? str.lastIndexOf(']') : value.lastIndexOf(']');
                    if (lastIndex > -1) {
                        str = str ? str.substr(0, lastIndex) : value.substr(0, lastIndex);
                    }
                    item.value = str ? str : value;
                }
            });
        });
    }

    //重置表单
    @action resetForm = () => {
        ['loading', 'conditions', 'form'].map((v, i) => {
            this.formElements[v] = (i === 0) ? false : (i === 1) ? [] : new WeaForm();
        });
    }

    //***************图片*****************
    @observable picture = {
        imglist: '',
        selectedid: '',
        mouseEnterIndex: '',
        index: '',
        defaultImg: ""
    }

    @action setSelectedId = (params) => {
        ['selectedid', 'index'].map(v => {
            this.picture[v] = params[v];
        });
    }

    @action setMouseEnterIndex = (index) => {
        this.picture.mouseEnterIndex = index;
    }

    //***************上传组件*****************
    @observable upload = {
        upStatus: '',
        list: [],
        id: '',
    }

    @action setList = (list) => {
        this.upload.list = list;
    }

    @action setImageId = (id) => {
        this.upload.id = id;
    }

    @action onUploading = (upStatus) => {
        this.upload.upStatus = upStatus;
        if (upStatus === 'uploaded') this.saveImg(this.getImgsFetchParams());
    }

    saveImg = (params) => {
        const {
            selectedKey
        } = this.tab, {
            type
        } = params;

        const name = (selectedKey === '0' || type === 'delete') ? 'saveImg' : 'savePicChange';

        fetch({
            asyncFetch,
            name,
            fetchParams: params,
            logic: (cb) => {
                const {
                    sign
                } = cb;

                message[sign === '1' ? 'success' : 'warning'](cb.message);

                if (sign === '1') {
                    const {
                        type,
                        cmd,
                        imgid
                    } = params;
                    (type === 'add' || cmd === 'add') && this.increaseImage();

                    (type === 'delete') && this.decreaseImage(imgid);
                }
            }
        });
    }

    delImage = (id) => {
        const params = {
            type: 'delete',
            imgid: id,
            index: this.picture.index
        }

        this.saveImg(params)
    }

    getImgsFetchParams = () => {
        const {
            list
        } = this.upload, {
            selectedKey
        } = this.tab;

        const params = {
            [(selectedKey === '0') ? 'type' : 'cmd']: 'add',
            len: list.length
        };

        list.map((lt, index) => {
            const {
                fileid,
                filename
            } = lt;

            Object.assign(params, {
                [`id${index}`]: fileid,
                [`name${index}`]: filename
            });
        });

        return params
    }

    @action increaseImage = () => {
        const {
            list
        } = this.upload, {
            imglist
        } = this.picture;

        list.map(lt => {
            const {
                fileid,
                filename
            } = lt;

            imglist.imgs.push({
                id: fileid,
                name: filename
            })
        });
    }

    @action decreaseImage = (imgid) => {
        const {
            imglist
        } = this.picture;

        let targetIndex;

        imglist.imgs.map((img, index) => {
            const {
                id,
                name
            } = img;

            if (imgid === id) {
                targetIndex = index;
            }

        });

        if (this.picture.index === targetIndex + 1) {
            this.changeSelectedIndex(targetIndex)
        }

        imglist.imgs.splice(targetIndex, 1);
    }

    changeSelectedIndex = (targetIndex) => {
        const {
            imglist
        } = this.picture;

        if (targetIndex === 0) {
            this.setSelectedId('0', 0);
        } else {
            const selectedid = imglist.imgs[targetIndex - 1].id;
            this.setSelectedId({
                selectedid,
                index: targetIndex
            });
        }
    }

    //***************权限表单*****************
    dialogStaticProps = {
        icon: 'icon-coms-hrm',
        iconBgcolor: '#217346',
        hasScroll: true,
        height: 290,
        modalClassName: 'hrm-auth',
        onOk: (data) => this.handleOk(data),
        onCancel: () => this.closeDialog(),
    }

    @observable dialogTitle = getLabel('391183', "添加管理员");

    @observable authForm = {
        conditions: [],
        visible: false,
        loading: false,
    }

    handleOk = (data) => {
        fetch({
            asyncFetch,
            name: 'saveSysMember',
            fetchParams: data,
            logic: (cb) => {
                const {
                    sign
                } = cb

                message[sign === '1' ? 'success' : 'warning'](cb.message);

                if (sign === '1') this.getFormMaterial();
            }
        });
    }

    //获取表单数据
    @action getAuthForm = () => {
        this.authForm.loading = true;
        fetch({
            asyncFetch,
            name: 'getSysRemindAddForm',
            logic: (cb) => {
                ['loading', 'conditions'].map((v, i) => {
                    this.authForm[v] = (i === 0) ? false : cb[v];
                });
            }
        });
    }

    @action openDialog = () => {
        this.authForm.visible = true
    }

    @action closeDialog = () => {
        this.authForm.visible = false
    }


    //***************列表*****************
    tableStaticProps = {
        needScroll: true,
        hasOrder: true,
        scroll: {
            y: 400
        }
    }

    @observable table = {
        comsWeaTableStore: new TableStore(),
    }

    @computed get forceFresh() {
        const {
            comsWeaTableStore
        } = this.table;

        return comsWeaTableStore.selectedRowKeys.length === 0
    }

    deleteSysMember = () => {
        const {
            comsWeaTableStore
        } = this.table;

        fetch({
            asyncFetch,
            name: 'deleteSysMember',
            fetchParams: {
                ids: comsWeaTableStore.selectedRowKeys.toString()
            },
            logic: (cb) => {
                const {
                    sign
                } = cb;

                message[sign === '1' ? 'success' : 'warning'](cb.message);

                if (sign === '1') this.getFormMaterial();
            }
        });
    }

    refreshPage = () => {
        const {
            selectedKey
        } = this.tab, {
            activeKey
        } = this.tabs;

        if (selectedKey === '0') {
            this.handleTabsChange('0')
        } else {
            this.handleTabChange('0');
        }
    }

    @observable staffRemindFormStore = new FormStore(this);

    @computed get OtherComponents() {
        const { form } = this.staffRemindFormStore;
        const { dispatchImg } = form.getFormParams();

        const config = {};

        //推送图片
        if (dispatchImg == "1") {
            config.dispatchImg = () => {
                return (
                    <span className="dispatch-img-set" onClick={this.handleDispatchImg}>{i18n.button.setting()}</span>
                )
            }
        }

        config.greetings = () =>  <WeaHelpfulTip title='暂不支持换行！' style={{position: 'absolute', top: 14, right: '105%'}}/>

        //预览
        config.review = () => this.preview;

        //弹窗贺卡设置、移动端贺卡设置
        ["pcSetting", "mobileSetting"].forEach((v, i) => {
            config[v] = () => (
                <span>
                    <i className="icon-coms-Flow-setting" onClick={() => this.handleSettingIconClick(i)}/>
                    {form.getFormParams()[v] == '1' && <i className="icon-coms-complete" /> }
                </span>
            )
        })

        return config;
    }

    //获取预览字段的值
    @computed get preview() {
        const { form } = this.staffRemindFormStore;
        const { showtitle } = form.getFormParams();

        let str = getLabel(-1, "系统管理员");;
        showtitle.split(",").sort().forEach(v => {
            if (v == "2") {
                str = `${str}-${getLabel(-1,"部门")}`;
            }
            if (v == "3") {
                str = `${str}-${getLabel(-1,"分部")}`;
            }
        })

        return (
            <div>{form.getFormParams().greetings.replace("$",str)}</div>
        )
    }

    @observable dispatchImgDialogStore = new DialogStore(this);

    get DialogButtons() {
        return [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nkq7ry@dispatchImg`} type="primary" onClick={() => this.saveDispatchImg()}>{i18n.button.save()}</Button>];
    }

    MoreBtn = {
        datas: []
    };

    handleDispatchImg = () => {
        const config = {
            title: i18n.label.setDispatchImg(),
            style: {
                width: 600,
                height: 196
            }
        };

        const ds = this.dispatchImgDialogStore;
        ds.init(config);
        ds.openDialog();
    }

    //推送图片
    @observable dispatchImg = "";

    //推送图片上传状态
    @observable dispatchImgUploadStatus = false;

    @action handleUploadChange = (ids, list) => {
        this.dispatchImg = list[0] && list[0].imgSrc;
        this.dispatchImgId = list[0] && list[0].fileidCode;
    }

    @action setUploadStatus = (status) => {
        this.dispatchImgUploadStatus = status;
    }

    @observable greetingCardSetDialogStore = new DialogStore(this);
    @observable birthEditorStore = new BirthEditor(this);

    get greetingSetMoreBtn() {
        return {}
    }


    /**
     * 概述：打开贺卡设置的弹窗
     * @param  {[Integer]} i [标识pc端贺卡设置还是移动端]
     */
    handleSettingIconClick = (i) => {
        const config = {
            title: (i == 0) ? i18n.label.dialogCardSetting() : i18n.label.emDialogCardSetting(),
            scalable: true,
            mark: "greetingSet",
            style: {
                width: window.innerWidth - 50,
                height: window.innerHeight
            },
            _closeDialog:()=>{
                this.birthEditorStore.unRe.clear();
            }
        };

        this.cardType = (i == 0) ? "pc" : "mobile";

        this.birthEditorStore = new BirthEditor(this);

        const ds = this.greetingCardSetDialogStore;
        ds.init(config);
        ds.openDialog();
    }

    delDispatchImg = () => {
        this.dispatchImg = "";
        this.dispatchImgId = "";
    }

    saveDispatchImg = () => {
        this.saveStaffRemindForm(false, () => {
            this.dispatchImgDialogStore.closeDialog();
        })
    }

    saveStaffRemindForm = (showMsg = true, callback) => {
        const { form } = this.staffRemindFormStore;
        asyncFetch.saveStaffRemindForm({ ...form.getFormParams(), imgId: this.dispatchImgId }).then(res => {
            if (res.status == "1") {
                showMsg && message.success(getLabel(83551, '保存成功！'))
                callback && callback()
            } else {
                message.error(res.message);
            }
        })
    }




}