import {
    observable,
    action
} from 'mobx';
import {
    WeaForm
} from 'comsMobx';
import {
    WeaTableNew
} from 'comsMobx';
import {
    Modal,
    message,
} from 'antd'
import {
    i18n
} from '../public/i18n';
import * as mobx from 'mobx';
import * as Api from '../apis/enginegroup';
import * as commonApi from '../apis/common';
const toJS = mobx.toJS;
const {
    TableStore
} = WeaTableNew;

export class HrmEngineGroup {
    //ne: 新建和编辑
    //ih:importHistory
    //ir:importResult
    //il:importLog
    //sh: search
    //it:import
    //mp: mainPage

    //common
    @observable canAdd = false;
  	@observable canCreate = false;
    @observable canDel = false;
    @observable canCreateMember = false;
    @observable canDelMember = false;
    @observable detachable = false;

    @observable btnMenu = [];
    @observable wtpLoading = true;
    @observable date = '';
    @observable operation = '';
    @observable isEdit = true;
    @observable authorized = false;
    //WeaRightMenu 
    @observable rightMenu = [];
    //WeaTop
    @observable mpTitle = i18n.module.groupSet();
    @observable topMenu = [];
    @observable mpLoading = true;
    // @observable formType='';
    // @observable editId='';
    //WeaTab
    @observable groupName = '';
    @observable isMpPanelShow = false;
    @observable conditionNum = 2;
    @observable mpShForm = new WeaForm();
    @observable mpShCondition = [];
    @observable mpShLoading = true;
    //WeaTable
    @observable mpTableStore = new TableStore();
    @observable selectedRowsKeys = '';
    @observable selectedRowKey = '';
    neTitle = i18n.label.newCommonGroup;
    settingTitle = i18n.label.editCommonGroup;
    addGpMemTitle = i18n.label.addGroupMember;
    //新建弹出框
    @observable newDialogVisible = false;
    @observable neLoading = true;
    @observable neCondition = [];
    @observable neForm = new WeaForm();
    @observable isOpenSetting = false; //标识“保存并进入详细设置”按钮
    @observable groupId = ''; //保存后返回的值，用来唯一标示一个常用组
    //常用组设置
    @observable settingDialogVisible = false;
    @observable deleteType = '';
    @observable selectedRowKeys = '';
    @observable rowId = '';
    @observable selectedKey = '0';
    @observable memTableStore = new TableStore();
    @observable isEdit = false; //用来标示“新建常用组”还是“编辑常用组”
    //常用组设置-新建人员
    @observable memberIds = '';

    //常用组设置 - 添加群组成员
    @observable addGpMemDialogVisible = false;
    @observable addGpMemLoading = true;
    @observable addGpMemCondition = [];
    @observable addGpMemForm = new WeaForm();
    @observable gpMemParams = {};

    @action
    //common
    getRight = async () => {
        this.hrmDeptId = null;
		this.hrmSubComId = null;
		this.loading = true;
		const data = await commonApi.detachable();
		const {status: s, detachable} = data;
        this.detachable = s == '1' && detachable == '1';
        
        this.setWtpStatus(true); //再次调用该接口时，loading状态值置为true
        Api.getHasRight(this.params).then((res) => {
            if (res.api_status) {
                if (res.hasRight) {
                    this.authorized = true;
                    res.btnMenu && this.setBtnMenu(res.btnMenu);
                    this.btnDistribution();
                    res.hasOwnProperty('isEdit') && this.setEditStatus(res.isEdit);
                }
                this.setWtpStatus(false);
            } else {
                message.warning(res.message);
            }
        }, error => {
            message.warning(error.message);
        })
    }
    btnDistribution() {
        let topMenu = [];
        let rightMenu = [];
        this.btnMenu.map(item => {
            (item.isTop == '1' || item.isBatch == '1') && topMenu.push(item);
            !item.isBatch && rightMenu.push(item);
        });
        topMenu = topMenu.filter(item => (item.menuFun == 'new' && this.canCreate) || (item.menuFun == 'batchDelete' && this.canDel));
        rightMenu = rightMenu.filter(item => (item.menuFun == 'new' && this.canCreate) || (item.menuFun == 'batchDelete' && this.canDel) || item.isTop == '0');
        this.setTopMenu(topMenu);
        this.setRightMenu(rightMenu);
    }
    //WeaTop
    add() {
        this.neForm.validateForm().then(f => {
            if (f.isValid) {
                Api.add(this.params).then((res) => {
                    if (res.api_status) {
                        if (res.message) {
                            if (res.sign == '1') {
                                message.success(res.message);
                            } else {
                                message.warning(res.message);
                            }
                        } else {
                            if (res.sign == '1') {
                                message.success('新建成功');
                            } else {
                                message.warning('新建失败');
                            }
                        }
                        this.setNewDialogVisible(false);
                        res.orgGroupid && this.setGroupId(res.orgGroupid); //设置群组标识
                        if (this.isOpenSetting) {
                            this.setSelectedKey('0');
                            this.setSettingDialogVisible(true); //打开“编辑群组”弹出框
                        }
                        this.refresh();
                    } else {
                        message.warning(res.message);
                    }
                }, error => {
                    message.warning(error.message);
                })
            } else {
                f.showErrors();
                this.setDate(new Date());
            }
        });
    }
    edit() {
        this.neForm.validateForm().then(f => {
            if (f.isValid) {
                Api.edit(this.params).then(res => {
                    if (res.api_status) {
                        if (res.message) {
                            if (res.sign == '1') {
                                message.success(res.message);
                            } else {
                                message.warning(res.message);
                            }
                        } else {
                            if (res.sign == '1') {
                                message.success('编辑成功');
                            } else {
                                message.warning('编辑失败');
                            }
                        }
                        this.setSettingDialogVisible(false);
                        this.refresh();
                    } else {
                        message.warning(res.message);
                    }
                }, error => {
                    message.warning(error.message);
                })
            } else {
                f.showErrors();
                this.setDate(new Date());
            }
        });
    }
    delete() {
        Api.deleteRows(this.params).then((res) => {
            if (res.api_status) {
                if (res.message) {
                    if (res.sign == '1') {
                        message.success(res.message);
                    } else {
                        message.warning(res.message);
                    }
                } else {
                    if (res.sign == '1') {
                        message.success('删除成功');
                    } else {
                        message.warning('删除失败');
                    }
                }
                this.refresh();
                this.selectedRowsKeys && this.selectedRowsKeysReset();
            } else {
                message.warning(res.message);
            }
        }, error => {
            message.warning(error.message);
        })
    }
    //WeaTab
    getMpSearchCondition() {
        Api.getSearchCondition(this.params).then((res) => {
            if (res.api_status) {
                if (res.conditions) {
                    this.setMpShCondition(res.conditions);
                    this.mpShForm.initFormFields(res.conditions);
                    this.setConditionNum(res.conditions[0].items.length);
                }
                this.setMpShStatus(false);
            } else {
                message.warning(res.message);
            }
        }, error => {
            message.warning(error.message);
        })
    }
    updateFields(val) {
        this.mpShForm.updateFields({
            orgGroupName: {
                value: val
            }
        });
    }
    //WeaTable
    getTableInfo() {
        this.mpTableStore = new TableStore();
        const params = {...this.params};
        this.hrmSubComId != null && Object.assign(params, {subCompanyId: this.hrmSubComId});
        Api.getSearchList(params).then(res => {
            if (res.api_status) {
                this.canCreate = res.canAdd || false;
                this.canDel = res.canDel || false;
                this.btnDistribution();
                res.sessionkey && this.mpTableStore.getDatas(res.sessionkey, 1);
            } else {
                message.warning(res.message);
            }
        }, error => {
            message.warning(error.message);
        })
    }
    //NewAndEdit
    getNeForm() {
        this.setNeStatus(true);
        const params = {...this.params};
        this.hrmSubComId != null && Object.assign(params, {subCompanyId: this.hrmSubComId});
        Api.getNeForm(params).then(res => {
            if (res.api_status) {
                this.canAdd = res.canAdd || false;
                if (res.condition) {
                    this.setNeCondition(res.condition);
                    this.neForm.initFormFields(res.condition);
                }
                this.setNeStatus(false);
            } else {
                message.warning(res.message);
            }
        }, error => {
            message.warning(error.message);
        })
    }
    //常用组设置
    getMemTableInfo() {
        this.memTableStore = new TableStore();
        const params = {...this.params};
        this.hrmSubComId != null && Object.assign(params, {subCompanyId: this.hrmSubComId});
        Api.getMemTableInfo(params).then(res => {
            if (res.api_status) {
                this.canCreateMember = res.canAdd || false;
				this.canDelMember = res.canDel || false;
                res.sessionkey && this.memTableStore.getDatas(res.sessionkey, 1);
            } else {
                message.warning(res.message);
            }
        }, error => {
            message.warning(error.message);
        })
    }
    //常用组设置 - 添加群组成员
    getAddGpMemCondition() {
        Api.getAddGpMemForm(this.params).then(res => {
            if (res.api_status) {
                res.conditions && this.setAddGpMemCondition(res.conditions);
                this.setAddGpMemStatus(false);
            } else {
                message.warning(res.message);
            }
        }, error => {
            message.warning(error.message);
        })
    }

    memberSave() {
        Api.memberSave(this.params).then((res) => {
            if (res.api_status) {
                if (res.message) {
                    if (res.sign == '1') {
                        message.success(res.message);
                    } else {
                        message.warning(res.message);
                    }
                } else {
                    if (res.sign == '1') {
                        message.success('保存成功');
                    } else {
                        message.warning('保存失败');
                    }
                }
                this.setAddGpMemDialogVisible(false);
                this.setOperation('getMemTableInfo');
                this.getMemTableInfo();
                this.setOperation('getTableInfo');
                this.getTableInfo();
            } else {
                message.warning(res.message);
            }
        }, error => {
            message.warning(error.message);
        })

    }

    memTableRowDel() {
        Api.memTableRowDel(this.params).then((res) => {
            if (res.api_status) {
                if (res.message) {
                    if (res.sign == '1') {
                        message.success(res.message);
                    } else {
                        message.warning(res.message);
                    }
                } else {
                    if (res.sign == '1') {
                        message.success('删除成功');
                    } else {
                        message.warning('删除失败');
                    }
                }
                this.setOperation('getMemTableInfo');
                this.getMemTableInfo();
                this.setOperation('getTableInfo');
                this.getTableInfo();
                this.selectedRowsKeys && this.selectedRowsKeysReset();
            } else {
                message.warning(res.message);
            }
        }, error => {
            message.warning(error.message);
        })
    }



    paramsDistribution() {
        let operation = this.operation;
        if (operation == 'getTableInfo') {
            if (!this.mpShForm.isFormInit) {
                this.setParams({
                    orgGroupName: this.groupName
                });
            } else {
                this.setParams({ ...this.mpShForm.getFormParams()
                });
            }
        } else if (operation == 'editFrom') {
            this.setParams({
                orgGroupid: this.groupId
            });
        } else if (operation == 'save_new') {
            this.setParams({ ...this.neForm.getFormParams()
            });
        } else if (operation == 'save_edit') {
            this.setParams({ ...this.neForm.getFormParams(),
                id: this.groupId
            });
        } else if (operation == 'delete') {
            this.setParams({
                ids: this.selectedRowKey
            });
        } else if (operation == 'addGpMemSave') {
            this.setParams({ ...this.gpMemParams,
                orgGroupId: this.groupId
            });
        } else if (operation == 'memTableRowDel') {
            this.setParams({
                ids: this.rowId
            });
        } else if (operation == 'getMemTableInfo') {
            this.setParams({
                orgGroupId: this.groupId
            });
        } else {
            this.setParams({});
        }

    }
    setParams(params) {
        this.params = params;
    }
    refresh() {
        this.setOperation('getTableInfo');
        this.getTableInfo();
    }
    mobxDatasReset() {
        this.groupNameReset();
        this.mpShForm = new WeaForm();
        this.mpShCondition = [];
        this.isMpPanelShow && this.setMpPanelStatus(false);
    }
    //common
    setOperation(operation) {
        this.operation = operation;
        this.paramsDistribution();
    }
    setBtnMenu(btnMenu) {
        this.btnMenu = btnMenu;
    }
    setWtpStatus(bool) {
        this.wtpLoading = bool;
    }
    setDate(date) {
        this.date = date;
    }
    setEditStatus(bool) {
        this.isEdit = bool;
    }
    //WeaRightMenu
    setRightMenu(rightMenu) {
        this.rightMenu = rightMenu;
    }
    rightMenuReset() {
        this.rightMenu = [];
    }
    //WeaTop
    setTopMenu(topMenu) {
        this.topMenu = topMenu;
    }
    topMenuReset() {
        this.topMenu = [];
    }
    deleteSet(id, operation) {
        if (id) this.setSelectedRowKey(id);
        if (operation) this.setOperation(operation);
    }
    setFormType(formType) {
        this.formType = formType;
    }
    setSelectedRowKey(key) {
        this.selectedRowKey = key;
    }
    //WeaTab
    setSearchName(name) {
        this.groupName = name;
    }
    setConditionNum(num) {
        this.conditionNum = num;
    }
    groupNameReset() {
        this.groupName = '';
    }
    setMpShCondition(condition) {
        this.mpShCondition = condition;
    }
    setMpPanelStatus(bool) {
        this.isMpPanelShow = bool;
    }
    mpSearchReset() {
        // this.mpShForm.reset();
    }
    setMpShStatus(bool) {
        this.mpShLoading = bool;
    }
    //WeaTable
    setSelectedRowsKeys(keys) {
        this.selectedRowsKeys = keys
    }
    selectedRowsKeysReset() {
        this.selectedRowsKeys = '';
    }
    //新建常用组
    setNewDialogVisible(bool) {
        this.newDialogVisible = bool;
        if (bool) {
            this.setOperation('addForm');
            this.getNeForm();
        } else {
            this.newDialogReset();
        }
    }
    setNeCondition(condition) {
        this.neCondition = condition;
    }
    setNeStatus(bool) {
        this.neLoading = bool;
    }
    newDialogReset() {
        this.neForm = new WeaForm(); //重置form
        this.neLoading = true; //重置加载状态
    }
    isOpenSettingDialog(bool) {
        this.isOpenSetting = bool;
    }
    setGroupId(id) {
        this.groupId = id;
    }
    isEditPart(bool) { //打开弹出框或者切换tab时，设置表单的类型
        this.isEdit = bool;
    }
    //常用组设置
    setSettingDialogVisible(bool) {
        this.settingDialogVisible = bool;
        if (bool) {
            this.setOperation('editFrom');
            this.getNeForm();
        } else {
            this.settingDialogReset();
        }
    }
    setSettingCondition(condition) {
        this.settingCondition = condition;
    }
    setDeleteType(type) {
        this.deleteType = type;
    }
    settingDialogReset() {
        this.neForm = new WeaForm();
        this.neLoading = true;
    }
    setSelectedRowKeys(keys) {
        this.selectedRowKeys = keys;
    }
    setRowId(id) {
        this.rowId = id;
    }
    setSelectedKey(selectedKey) {
        this.selectedKey = selectedKey;
        if (selectedKey == '0') {
            this.isEditPart(true);
            this.setOperation('editFrom');
            this.getNeForm();
        } else {
            this.setOperation('getMemTableInfo');
            this.getMemTableInfo();
        }

    }
    //常用组设置-新建人员
    setMemberIds(ids) {
        this.memberIds = ids;
    }
    memberIdsReset() {
        this.memberIds = '';
    }
    //常用组设置 - 添加群组成员
    setAddGpMemDialogVisible(bool) {
        this.addGpMemDialogVisible = bool;
        if (bool) {
            this.setOperation('getAddGpMemCondition');
            this.getAddGpMemCondition();
        } else {
            this.addGpMemDialogReset();
        }
    }
    setAddGpMemCondition(condition) {
        this.addGpMemCondition = condition;
    }
    setAddGpMemStatus(bool) {
        this.addGpMemLoading = bool;
    }
    addGpMemDialogReset() {}
    setGpMemParams(params) {
        this.gpMemParams = params;
    }

    orgTreeProps = {
		needSearch: true,
		isLoadAllSub: true,
		topPrefix: "hrmSearch",
		inputLeftDom: `<b>${i18n.label.organization()}</b>`,
		// needDropMenu: true,
		treeNodeClick: this.treeNodeClick,
		params: {
			rightStr: "GroupsSet:Maintenance"
		},
	};

	@action treeNodeClick = (event, ids, nodeids, nodes) => {
		this.hrmDeptId = null;
		this.hrmSubComId = null;
		const { data } = event.node.props;
		const {type, id} = data;
		if(type == 1 || type == 0)
			this.hrmSubComId = id;
		else if(type == 2)
			this.hrmDeptId = id;
		this.getTableInfo();
	};
}