import {observable, action, computed} from 'mobx';
import * as api from '../apis/finance';
import {message, Button} from 'antd';
import {WeaLocaleProvider} from 'ecCom';
import {WeaForm, WeaSwitch} from 'comsMobx';
import isEmpty from 'lodash/isEmpty';

const {getLabel} = WeaLocaleProvider;

class FinanceStore{
    //#region init
    @observable loading = true;
    @observable hasRight = false;
    @observable edit = false;

    rootStore;
    hrmId;
    @observable fromcard = false;

    @action clear = () => {
        this.loading = true;
        this.hasRight = false;
        this.edit = false;
        this.hrmId = null;
        this.fromcard = false;
        this._reqParams = {};
    }

    @action init = async props => {
        this.clear();
        //1.setPropsValue
        this.setPropValue(props);
        //2.hasRight
        this.hasRight = await this.getHasRight();
        //3.check is need second verify
        if(window.doCheckSecondaryVerify4ec){
            this.hasRight && window.doCheckSecondaryVerify4ec({mouldCode: 'HRM', itemCode: 'SALARY'}, this.getData);
        }else{
            //4.loaddata
            this.hasRight && this.getData({status: '1', token: ''});
        }
    }

    @action setPropValue = props => {
        const {location = {}, params = {}, hrmCard} = props;
        this.rootStore = hrmCard;
        const {hrmId = ''} = params;
        this.hrmId = hrmId;
        const {query = {}} = location;
        const {fromcard} = query;
        this.fromcard = fromcard || false;
    }
    //#endregion 

    //#region getHasRight
    @action getHasRight = async () => {
        const data = await api.getHasRight();
        if(data.status == '1')
            return data.hasRight;
        else{
            message.error(data.message);
            return false;
        }
    }
    //#endregion

    //#region top props
    @computed get topButtons(){
        const arr = [];
        !this.edit && this.buttons.hasEdit && arr.push({isTop: '1', menuFun: 'doEdit', menuIcon: 'icon-coms-edit', menuName: getLabel(93, '编辑'), type: 'BTN_EDIT'});
        this.edit && this.buttons.hasSave && arr.push({isTop: '1', menuFun: 'doSave', menuIcon: 'icon-coms-Preservation', menuName: getLabel(30986, '保存'), type: 'BTN_SAVE'});
        return arr;
    }
    
    @computed get topBtnAndMenus(){
        const buttons = [], dropMenuDatas = [];
        this.topButtons.map((btn, index) => {
            const {isTop, menuIcon, menuName, menuFun} = btn;
            const onClickHandle = this[menuFun];
            if(isTop == '1'){
                buttons.push(
                    (
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@w05exq@${index}`} type='primary' onClick={onClickHandle}>{menuName}</Button>
                    )
                )
            }
            dropMenuDatas.push({
				key: index.toString(),
				content: menuName,
				icon: <i className={menuIcon}/>,
				onClick: onClickHandle
            });
        })
        return {buttons, dropMenuDatas};
    }

    @computed get topProps(){
        const d = ecCom.WeaTools.getIconBGC('hrm');
        return {
            title: getLabel('16416',"我的工资"),
            icon: <i className={d.icon}/>,
            iconBgcolor: d.iconBgcolor,
            showDropIcon: true,
            ...this.topBtnAndMenus
        }
    }
    //#endregion

    //#region getData
    _reqParams = {};

    get reqParams(){
        return {
            ...this._reqParams,
            id: this.hrmId
        }
    }

    @action getData = async (params = {}) => {
        if(isEmpty(params))
            return;
        
        const {status, token} = params;
        if(status == '1'){
            Object.assign(this._reqParams, {token});
            this.getFormData({viewAttr: 1});
        }else{
            this.hasRight = false;
        }
        this.loading = false;
    }

    @observable form = new WeaForm();
    formFields = [];
    @computed get isFormInit(){return this.form.isFormInit}

    @computed get formProps(){
        if(this.isFormInit){
            return {
                col: 2,
                form: this.form,
                formFields: this.formFields
            }
        }
        return {};
    }

    @observable _buttons = {};
    @computed get buttons(){return this._buttons || {}}
    set buttons(v){
        this._buttons = v;
        if(this.rootStore){
            const {buttons, dropMenuDatas} = this.topBtnAndMenus;
            this.rootStore.setTopButtons(() => buttons);
            this.rootStore.setTopRightMenus(() => dropMenuDatas);
            this.rootStore.setTopShowDropIcon(true);
        }
    }

    @action getFormData = async (params = {}) => {
        const data = await api.getFormField({...this.reqParams, ...params});
        try{
            this.buttons = data.buttons;

            this.form = new WeaForm();
            this.formFields = data.fieldgroup.map(group => {
                group.items = group.items.map(field => {
                    Object.assign(field, {
                        viewAttr: this.edit ? '2' : '1'
                    });
                    field.conditionType == 'BROWSER' && Object.assign(field, {
                        browserConditionParam: {
                            ...field.browserConditionParam,
                            viewAttr: this.edit ? '2' : '1'
                        }
                    });
                    return field;
                })
                return group;
            });
            this.form.initFormFields(this.formFields);

            this.getTab();
        }catch(e){
            message.error(e);    
        }
    }

    @observable selectedTabKey = '';
    @observable tabData = [];

    @computed get tabProps(){
        return {
            datas: this.tabData,
            keyParam: 'key',
            selectedKey: this.selectedTabKey,
            onChange: this.onTabChangeHandle
        }
    }

    @action onTabChangeHandle = async key => {
        this.selectedTabKey = key;
        this.getSearchList();
    }

    @action getTab = async () => {
        const data = await api.getTabInfo({...this.reqParams});
        if(data.status == '1'){
            this.tabData = data.tabs;
            this.selectedTabKey = data.tabs.length > 0 ? data.tabs[0].key : '';
            this.getSearchList();
        }else{
            message.error(data.message);
        }
    }

    @observable columns = [];
    @observable datas = [];
    @computed get tableProps(){
        return {
            columns: this.columns,
            dataSource: this.datas,
            scroll: {
                x: this.columns.length * 100
            },
            pagination: false
        }
    }

    @action getSearchList = async () => {
        const data = await api.getSearchList({...this.reqParams, tabkey: this.selectedTabKey});
        try{
            const {table = {}} = data;
            this.columns = table.columns.map(c => {
                if(c.dataIndex.indexOf('column_')> -1){
                    c.render = function(text, record){
                        return  <span title={typeof(record[c.dataIndex]) == 'object' ? record[c.dataIndex].titles : record[c.dataIndex]}>{typeof(record[c.dataIndex]) == 'object' ? record[c.dataIndex].value : record[c.dataIndex]}</span>
                    }
                }
                return c;
            });
            this.datas = table.datas;
        }catch(e){
            message.error(e);
        }
    }
    //#endregion

    //#region doEdit
    @action doEdit = async () => {
        this.edit = true;
        this.getFormData({viewAttr: 2});
    }
    //#endregion

    //#region doSave
    @action doSave = async () => {
        const data = await api.saveFormFields({id: this.hrmId, ...this.form.getFormParams()});
        if (data.status == '1') {
            this.edit = false;
            message.success(getLabel(83551, '保存成功！'));
            this.getFormData({viewAttr: 1});
        }else{
            message.error(data.message);
        }
    }
    //#endregion
}

const financeStore = new FinanceStore();

export default financeStore;