import {observable, action, computed, toJS} from 'mobx';
import HrmBaseStore from './baseStore';
import {i18n} from '../public/i18n';
import * as api from '../apis/matrix';
import {WeaTableNew} from 'comsMobx';
import {WeaButtonIcon, WeaHelpfulTip, WeaBrowser, WeaLocaleProvider} from 'ecCom';
import {message, Button} from 'antd';
import isEmpty from 'lodash/isEmpty';
import get from 'lodash/get';

const getLabel = WeaLocaleProvider.getLabel;
const {TableStore} = WeaTableNew;

export default class MatrixMaintenanceStore extends HrmBaseStore{
    //#region constructor
    constructor(parentStore){
        super();
        this.parentStore = parentStore;
    }
    //#endregion

    //#region 变量定义
    columnHelpful = [];
    mListDialogTitle = '';//矩阵维护者对话框标题
    @observable mListDialogVisible = false;//矩阵维护者对话框是否可见
    selectedRecordId;//选中的维护者记录
    maintid;//维护者与矩阵的关系id
    @observable maintenanceList = new TableStore();//角色维护者列表
    mSettingDialogTitle = '';//矩阵维护者编辑对话框标题
    @observable mSettingDialogVisible = false;//矩阵维护者编辑对话是否可见
    @observable _mSettingDialogHeight = 0;//矩阵维护者编辑对话框动态高度
    @observable _settingTab = [];//编辑矩阵维护者tab列表
    @observable settingTabActiveIndex = '1';//编辑矩阵维护者当前激活tabId
    @observable createMaintenanceVisible = false;//添加维护者信息对话框是否可见
    createMaintenanceFormFields;//添加维护者表单
    @observable mList = new TableStore();//维护者table
    @observable conditionSettingFormVisible = false;//可维护条件表单是否可见
    conditionSettingFormFields;//可维护条件表单
    @observable conditionList = new TableStore();//可维护条件table
    @observable columnList = new TableStore();//可维护列table
    //#endregion

    //#region 属性
    get queryParams(){//角色维护者查询基本参数
        const params = {matrixid: this.parentStore.selectedMatrix.matrixid};
        this.maintid != null && Object.assign(params, {maintid: this.maintid});
        return params;
    }

    @computed get mListDialog(){//矩阵维护者对话框属性
        return {
            ...this.dialogPropsDef,
            title: this.mListDialogTitle,
            style: {
                width: 800,
                height: 500
            },
            onCancel: () => {
                this.parentStore.selectedMatrix = null;
                this.mListDialogVisible = false;
            },
            visible: this.mListDialogVisible
        }
    }

    @computed get mListRemoveable() {//矩阵维护者列表数据可删除状态
		return this.maintenanceList.selectedRowKeys.length == 0;
    }
    
    get mListTab(){//矩阵维护者列表tab属性
        return {
            tabs: [{
                color: '#000000',
                groupId: 'mListTab',
                viewCondition: '1',
                searchType: ['base', 'advanced'],
                searchKey: 'mainer',
			    doSearch: (params) => this.searchMaintenanceList(params)
            }],
            keyParam: 'viewCondition',
            activeTabKey: '1'
        }
    }

    @computed get mListTabBtn(){//矩阵维护者列表tab按钮
        return [
            <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@j7k2of`} buttonType='add' type='primary' onClick={() => this.createMaintenance()} />,
            <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@hn3syk`} buttonType='del' type='primary' disabled={this.mListRemoveable} onClick={() => this.deleteMatrixMaintenanceRecord()} />
        ]
    }

    set mSettingDialogHeight(v){//设置矩阵维护者编辑对话框高度
        this._mSettingDialogHeight = v;
    }

    @computed get mSettingDialogHeight(){
        return this._mSettingDialogHeight;
    }

    @computed get mSettingDialog(){//动态设置矩阵维护者编辑对话框属性
        return {
            ...this.dialogPropsDef,
            title: this.mSettingDialogTitle,
            style: {
                width: 700,
                height: 450
            },
            onCancel: () => {
                this.maintid = null;
                this.selectedRecordId = null;
                this.mSettingDialogVisible = false;
                this.showMaintenance();
            },
            visible: this.mSettingDialogVisible
        }
    }

    @computed get settingTab(){//矩阵维护者编辑对话框tab
        const props = {
            tabs: toJS(this._settingTab),
            keyParam: 'viewCondition',
            activeTabKey: this.settingTabActiveIndex
        }
        if(props.tabs.length > 0){
            switch(this.settingTabActiveIndex){
                case '1':
                    Object.assign(props.tabs[0], {
                        searchType: ['base', 'advanced'],
                        searchKey: 'typevalue',
                        doSearch: params => this.getMaintenanceList({...params, maintid: this.maintid || ''})
                    });
                    break;
                case '2':
                    break;
                case '3':
                    Object.assign(props.tabs[2], {
                        searchType: ['base'],
                        searchKey: 'mainer',
                        doSearch: params => this.getMatrixMaintColList({...params, maintid: this.maintid || ''})
                    });
                    break;
            }
        }

        return props;
    }
    
    @computed get settingTabBtn(){//矩阵维护者编辑对话框tab按钮
        let tip = '';
        switch(this.settingTabActiveIndex){
            case '1':
                return [
                    <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@602bsv`} buttonType='add' type='primary' onClick={() => this.createMaintenanceVisible = true} />,
                    // <WeaBrowser
                    //     customized
                    //     title={getLabel('510222','添加维护者')}
                    //     icon={'icon-coms-hrm'}
                    //     iconBgcolor={'#217346'}
                    //     type={'17'}
                    //     onChange={(ids, names, datas) => this.saveMaintanence({showresource: ids})}
                    //     isSingle={false}
                    // >
                    //     <WeaButtonIcon buttonType='add' type='primary' />
                    // </WeaBrowser>,
                    <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@2ts0tp`} buttonType='del' type='primary' disabled={this.mSettingListRemoveable} onClick={() => this.deleteMaintanence()} />
                ]
            case '2':
                try{tip = this.getHelpfulCom('conditionid');}catch(e){}
                return [
                    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@q341ms`} title={tip} />,
                    <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@je9fwc`} buttonType='add' type='primary' onClick={() => this.showConditionForm()} />,
                    <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@g83efu`} buttonType='del' type='primary' disabled={this.mConditionListRemoveable} onClick={() => this.deleteCondition()} />
                ]
            case '3':
                try{tip = this.getHelpfulCom('colid');}catch(e){}
                return [
                    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@8nw5ux`} title={tip} />,
                    <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@hqujns`}
                        customized
                        title={getLabel('508123','选择取值字段')}
                        icon={'icon-coms-hrm'}
                        iconBgcolor={'#217346'}
                        type={'matrixCol'}
                        dataParams={this.queryParams}
                        hasAdvanceSerach={false}
                        onChange={(ids, names, datas) => this.saveColumn(datas)}
                        isSingle={false}
                    >
                        <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@cz6xxm`} buttonType='add' type='primary' />
                    </WeaBrowser>,
                    <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@azpxpx`} buttonType='del' type='primary' disabled={this.mColumnListRemoveable} onClick={() => this.deleteColumn()} />
                ]
        }
    }
    
    @computed get createMaintenanceForm(){//添加维护者对话框属性
        return {
            conditions: this.createMaintenanceFormFields,
            moduleName: 'hrm',
            visible: this.createMaintenanceVisible,
            onOk: this.saveMaintanence,
            onCancel: () => this.createMaintenanceVisible = false
        }
    }

    @computed get mSettingListRemoveable() {//维护者数据可删除状态
		return this.mList.selectedRowKeys.length == 0;
    }

    @computed get mConditionListRemoveable() {//维护条件数据可删除状态
		return this.conditionList.selectedRowKeys.length == 0;
    }

    @computed get mColumnListRemoveable() {//维护列数据可删除状态
		return this.columnList.selectedRowKeys.length == 0;
    }
    
    @computed get conditionSettingForm(){//添加维护条件对话框属性
        return {
            conditions: this.conditionSettingFormFields,
            moduleName: 'hrm',
            height: 240,
            visible: this.conditionSettingFormVisible,
            onOk: this.saveCondition,
            onCancel: () => this.conditionSettingFormVisible = false
        }
    }
    
    //#endregion

    @action getHelpfulCom = dataIndex => {
        if(!isEmpty(this.columnHelpful))
            return get(this.columnHelpful, dataIndex) || null;
        return null;
    }
    
    //#region 加载角色维护者列表数据
    @action showMaintenance = (params) => {
        this.selectedRecordId = null;
        if(params != null)
            this.parentStore.selectedMatrix = params;
        this.maintid = null;
		api.initMaintenanceData(this.parentStore.selectedMatrix).then(rs => {
			rs.map((result, index) => {
				if (result.status === '1') {
					switch (index) {
						case 0://高级搜索表单
							this.setFormData('mListConditionForm', result.conditions);
							break;
						case 1://table数据
                            this.maintenanceList.getDatas(result.sessionkey, 1);
                            this.columnHelpful = result.tips;
							this.mListDialogTitle = `${i18n.label.matrixMaintenance()}:${this.parentStore.selectedMatrix.name}`;
							this.mListDialogVisible = true;
							break;
					}
				}
			});
		})
    }
    //#endregion

    //#region 快捷&高级搜索维护者列表数据
    @action searchMaintenanceList = params => {
        api.getMatrixMaintInfoList({...params, matrixid: this.parentStore.selectedMatrix.matrixid}).then(data => {
            if(data.status == '1'){
                this.maintenanceList = new TableStore();
                this.maintenanceList.getDatas(data.sessionkey, 1);
            }else{
                message.error(data.message);
            }
        });
    }
    //#endregion

    //#region 编辑操作权限
    @observable rightLevelDialogVisible = false;
    @observable rightLevelDialogTitle = '';

    get rightLevelDialogButtons(){
        const buttonDef = [
            {
                content: getLabel(30986, '保存'),
                icon: 'icon-coms-Preservation',
                onClickHandle: this.doSaveRightLevel
            }
        ]
        const buttons = [], moreBtnData = [];
        buttonDef.map((btn, index) => {
            const {content, icon, onClickHandle} = btn;
            buttons.push(
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@31tx0z@save`} type='primary' onClick={onClickHandle}>{content}</Button>)
            );

            moreBtnData.push({
                key: index.toString(),
                content,
                icon: <i className={icon} />,
                onClick: onClickHandle
            });
        })
        return {buttons, moreBtn: {datas: moreBtnData}};
    }

    @computed get rightLevelDialogProps(){
        return {
            ...this.dialogPropsDef,
            hasScroll: true,
            title: this.rightLevelDialogTitle,
            style: {
                width: 500,
                height: 200
            },
            onCancel: this.onRightLevelDialogCancelHandle,
            ...this.rightLevelDialogButtons,
            visible: this.rightLevelDialogVisible
        }
    }

    @action onRightLevelDialogCancelHandle = () => {
        this.maintid = null;
        this.rightLevelDialogVisible = false;
        this.showMaintenance();
    }

    @action doEditRightLevel = async maintid => {
        this.maintid = maintid || this.maintid;
        let data = await api.getMatrixMaintTab(this.queryParams);
        if(data.status == '1'){
            this.rightLevelDialogTitle = `${getLabel('383941','编辑权限级别')}:${data.title}`;
        }
        data = await api.getMatrixMaintRightLevelForm({maintid});
        if(data.status == '1'){
            this.setFormData('rightLevelForm', data.condition);
            this.rightLevelDialogVisible = this.formTarget.rightLevelForm.isFormInit;
        }
    }

    @action doSaveRightLevel = async () => {
        let formParams = this.formTarget.rightLevelForm.getFormParams();
        delete formParams.desc;
        const data = await api.saveMatrixMaintRightLevel({maintid: this.maintid, ...formParams});
        if(data.status == '1'){
            message.success(i18n.message.opSuccess());
            this.onRightLevelDialogCancelHandle();
        }else{
            message.error(data.message);
        }
    }
    //#endregion

    //#region 编辑矩阵维护者
    @action createMaintenance = (maintid, tabId = '1') => {//初始化数据并显示对话框
        //解决list接口被调用两次导致数据不正确的问题
        this.tabChangeHandle(tabId).then(()=>{
            this.initMaintenanceSettingData(() => this.mSettingDialogVisible = true, maintid);
        });
    }

    @action initMaintenanceSettingData = (callback, maintid) => {//初始化数据
        return new Promise( (resolve,reject)=>{
            this.maintid = maintid || this.maintid;
            api.initMaintenanceSettingData(this.queryParams).then(rs => {
                rs.map((result, index) => {
    				if (result.status === '1') {
    					switch (index) {
                            case 0://tab
                                this.mSettingDialogTitle = getLabel('508135','维护者设置');
                                if(maintid != null)
                                    this.mSettingDialogTitle += `:${result.title || ''}`;
                                if(this._settingTab.length > 0)
                                    break;
                                this._settingTab = result.tabs.map((tab, i) => {
                                    return {
                                        title: tab.title,
                                        color: '#000000',
                                        groupId: 'mListTab',
                                        viewCondition: tab.key,
                                    }
                                });
                                break;
                            case 1://高级搜索
    							this.setFormData('mSettingListConditionForm', result.conditions);
                                break;
                            case 2://添加维护者表单
                                this.createMaintenanceFormFields = result.conditions;
                                this.settingTabActiveIndex == '1' && this.getMaintenanceList();
                                this.settingTabActiveIndex == '2' && this.getMatrixMaintConditionList();
                                this.settingTabActiveIndex == '3' && this.getMatrixMaintColList();
                                break;
    						// case 3://维护者列表
                            //     this.mList = new TableStore();
    						// 	this.mList.getDatas(result.sessionkey, 1);
    						// 	break;
    					}
                        resolve();
    				}
                });
                callback && callback();
            });
        } )
    }

    @action getMaintenanceList = params => {
        this.mList = new TableStore();
        api.getMaintenanceList(params || this.queryParams).then(data => {
            if(data.status == '1'){
                this.mList.getDatas(data.sessionkey, 1);
            }else{
                message.error(data.message);
            }
        })
    }

    @action doAction = (op, record) => {
        switch(op){
            case 'modify':
                this.createMaintenance(record.maintid);
                break;
            case 'doEditRightLevel':
                this.doEditRightLevel(record.maintid);
                break;
            case 'remove':
                this.deleteMatrixMaintenanceRecord(record.maintid);
                break;
        }
    }

    @action tabChangeHandle = key => {//tab切换事件
        return new Promise( (resolve,reject)=>{
            switch(key){
                case '1':
                    this.initMaintenanceSettingData().then(()=>resolve());
                    break;
                case '2':
                    this.initConditionData().then(()=>resolve());
                    break;
                case '3':
                    this.initColumnData().then(()=>resolve());
                    break;
            }
    		this.settingTabActiveIndex = key;
        } ) 
	}
    //#endregion

    //#region 删除矩阵维护者
    @action deleteMatrixMaintenanceRecord = ids => {
        let content = "";
        if(ids == null){
            ids = this.maintenanceList.selectedRowKeys.join(',');
            content = i18n.confirm.deleteSelected();
        }else{
            content = i18n.confirm.delete();
        }

        this.confirmInfo({
            content,
            onOk: () => {
                api.delMatrixMaintInfo({id: ids}).then(data => {
                    if(data.status == '1'){
                        message.success(i18n.message.opSuccess());
                        this.searchMaintenanceList();
                    }else
                        message.error(data.message);
                })
            }
        });
    }
    //#endregion

    //#region 保存维护者
    @action saveMaintanence = data => {
        const params = { ...data,
            ...this.parentStore.selectedMatrix,
            maintid: this.maintid || ''
        };
        api.saveMatrixMaintenance(params).then(data => {
			if (data.status === '1') {
                this.maintid = data.maintid;
                this.getMaintenanceList();
				message.success(i18n.message.saveSuccess());
			} else {
				message.error(data.message);
			}
            this.createMaintenanceVisible = false;
		}, error => {})
    }
    //#endregion

    //#region 删除维护者
    @action deleteMaintanence = ids => {
        let content = "";
        if(ids == null){
            ids = this.mList.selectedRowKeys.join(',');
            content = i18n.confirm.deleteSelected();
        }else{
            content = i18n.confirm.delete();
        }
        this.confirmInfo({
            content,
            onOk: () => {
                api.removeMatrixMaintenance({...this.queryParams, delids: ids}).then(data => {
                    if(data.status == '1'){
                        if(data.empty_confirm == '1'){
                            this.hint({
                                content: data.message,
                                onOk: () => {
                                    this.mSettingDialog.onCancel();
                                }
                            });
                        }else{
                            message.success(i18n.message.opSuccess());
                            this.getMaintenanceList();
                        }
                    }else{
                        message.error(data.message);
                    }
                })
            }
        });
    }
    //#endregion

    //#region 加载可维护条件数据
    @action initConditionData = () => {
        return new Promise( (resolve,reject)=>{
            this.conditionSettingFormErrMsg = null;
            api.initConditionData(this.queryParams).then(rs => {
                rs.map((result, index) => {
    				if (result.status === '1') {
    					switch (index) {
    						case 0:
                                this.conditionSettingFormFields = result.conditions;
                                break;
                            case 1:
                                this.conditionList = new TableStore();
    							this.conditionList.getDatas(result.sessionkey, 1);
    							break;
    					}

                        resolve();
    				}else if(index == 0){
                        this.conditionSettingFormErrMsg = result.message;
                    }
                });
            })
        } )
    }

    @action showConditionForm = () => {
        if(this.conditionSettingFormErrMsg != null)
            message.error(this.conditionSettingFormErrMsg);
        else
            this.conditionSettingFormVisible = true
    }

    @action getMatrixMaintConditionList = () => {
        this.conditionList = new TableStore();
        api.getMatrixMaintConditionList(this.queryParams).then(data => {
            if(data.status == '1'){
                this.conditionList.getDatas(data.sessionkey, 1);
            }else{
                message.error(data.message);
            }
        })
    }
    //#endregion

    //#region 保存维护条件
    @action saveCondition = data => {
        const params = this.queryParams;
        if(params.maintid != null){
            api.saveMatrixMaintCondition({...params, ...data}).then(data => {
                if(data.status == '1'){
                    this.getMatrixMaintConditionList();
                    message.success(i18n.message.saveSuccess());
                }else{
                    message.error(data.message);
                }
                this.conditionSettingFormVisible = false;
            });
        }else{
            this.conditionSettingFormVisible = false;
            message.error(getLabel('508122','请先添加维护者数据') );
        }
    }

    @action deleteCondition = ids => {
        let content = "";
        if(ids == null){
            ids = this.conditionList.selectedRowKeys.join(',');
            content = i18n.confirm.deleteSelected();
        }else{
            content = i18n.confirm.delete();
        }
        this.confirmInfo({
            content,
            onOk: () => {
                api.delMatrixMaintCondition({...this.queryParams, id: ids}).then(data => {
                    if(data.status == '1'){
                        message.success(i18n.message.opSuccess());
                        this.getMatrixMaintConditionList();
                    }else{
                        message.error(data.message);
                    }
                })
            }
        });
    }
    //#endregion
    
    //#region 加载可维护条件数据
    @action initColumnData = () => {
        return new Promise( (resolve,reject)=>{
            this.columnList = new TableStore();
            api.initColumnData(this.queryParams).then(rs => {
                rs.map((result, index) => {
    				if (result.status === '1') {
    					switch (index) {
    						case 0:
                            //     this.setFormData('mColumnForm', result.conditions);
                            //     break;
                            // case 1:
    							this.columnList.getDatas(result.sessionkey, 1);
    							break;
    					}

                        resolve();
    				}
                });
            })
        } )
    }

    @action getMatrixMaintColList = params => {
        api.getMatrixMaintColList(params || this.queryParams).then(data => {
            if(data.status == '1'){
                this.columnList = new TableStore();
                this.columnList.getDatas(data.sessionkey, 1);
            }else{
                message.error(data.message);
            }
        })
    }

    @action saveColumn = datas => {
        const [id, displayname] = datas.reduce((arr, d) => {
            arr[0].push(d.id);
            arr[1].push(d.displayname);
            return arr;
        }, [[], []]);
        const params = this.queryParams;
        if(params.maintid != null){
            api.saveMatrixMaintCol({...params, id: id.join(','), displayname: displayname.join(',')}).then(data => {
                if(data.status == '1'){
                    this.getMatrixMaintColList();
                    message.success(i18n.message.saveSuccess());
                }
            });
        }else{
            message.error(getLabel('508122','请先添加维护者数据') );
        }
    }

    @action deleteColumn = ids => {
        let content = "";
        if(ids == null){
            ids = this.columnList.selectedRowKeys.join(',');
            content = i18n.confirm.deleteSelected();
        }else{
            content = i18n.confirm.delete();
        }
        this.confirmInfo({
            content,
            onOk: () => {
                api.delMatrixMaintCol({...this.queryParams, id: ids}).then(data => {
                    if(data.status == '1'){
                        message.success(i18n.message.opSuccess());
                        this.getMatrixMaintColList();
                    }else{
                        message.error(data.message);
                    }
                })
            }
        });
    }
    //#endregion
}