import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaForm,
	WeaTableNew,
	WeaSwitch
} from 'comsMobx';
import {
	WeaRightMenu
} from 'ecCom';
import {
	Button,
	message
} from 'antd';
import FormInfo from '../coms/FormInfo';
import MatrixEdit from '../components/matrix/MatrixEdit';
import MatrixFieldSetting from '../components/matrix/MatrixFieldSetting';
import MatrixDataMaintenance from '../components/matrix/MatrixDataMaintenance';
import HrmBaseStore from './baseStore';
import MatrixMaintenanceStore from './matrixMaintenance';
import * as api from '../apis/matrix';
import {
	has,
	findIndex
} from 'lodash';
import {
	i18n
} from '../public/i18n';
const {
	TableStore
} = WeaTableNew;

class HrmMatrix extends HrmBaseStore {
	constructor(){
		super();
		this.stores = {
			matrixMaintenanceStore: new MatrixMaintenanceStore(this),
		}
	}

	/********************* unobservable list *********************/
	//override baseStore.tabConfig
	tabConfig = {
		tabs: [{
			color: '#000000',
			groupId: 'matrixList',
			viewCondition: '1',
			searchType: ['base', 'advanced'],
			searchKey: 'name',
			doSearch: (params) => this.getMatrixList(params)
		}],
		keyParam: 'viewCondition',
		activeTabKey: '1'
	}

	orgTreeProps = {
        needSearch: true,
        isLoadSubDepartment: false,
        topPrefix: 'hrmSearch',
        inputLeftDom: `<b>${i18n.label.organization()}</b>`,
        // needDropMenu: true,
        treeNodeClick: this.treeNodeClick,
        params: {
            rightStr: 'Matrix:Maint'
        }
    }

	// maintenanceTabConfig = {
	// 	tabs: [{
	// 		color: '#000000',
	// 		groupId: 'matrixMaintenance',
	// 		viewCondition: '1',
	// 		searchType: ['base', 'advanced'],
	// 		searchKey: 'mainer',
	// 		tabButtonDef: [{
	// 			comType: 'button',
	// 			icon: 'icon-coms-Add-to-hot',
	// 			label: i18n.button.create(),
	// 			rightMenuIcon: this.menuIconCollection.create,
	// 			onClickHandle: this.createMaintenance
	// 		}, {
	// 			comType: 'button',
	// 			icon: 'icon-coms-form-delete-hot',
	// 			label: i18n.button.delete(),
	// 			rightMenuIcon: this.menuIconCollection.remove,
	// 			onClickHandle: this.removeMaintenance,
	// 			checkAction: 'maintenanceListTableMultiRemoveable'
	// 		}]
	// 	}],
	// 	keyParam: 'viewCondition',
	// 	activeTabKey: '1'
	// }

	topMenusDef = () => {
		let arr = [];
		this.authorizationInfo.hasMenuRight && arr.push({
			key: '1',
			content: i18n.button.create(),
			icon: <i className={this.menuIconCollection.create}/>,
			onClick: () => this.getMatrixInfoForm()
		});
		return [...arr, ...this.getBasicMenus('HRM_ENGINE_Matrix_List')]
	}

	selectedMatrix;
	/********************* unobservable list *********************/

	/********************* dialog info setting *********************/
	editorDialogRightMenu = [];
	getDialogOpButtons = () => {
		let buttons = [];
		this.editorDialogRightMenu.length = 0;
		let logSmallType;
		switch (this.dialogParams.opType) {
			case '':
				buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@w5s0y5`} type="primary" op="create" onClick={() => this.save()}>{i18n.button.save()}</Button>);
				logSmallType = this.logTypeDef.HRM_ENGINE_Matrix_List;
				break;
			case 'fieldSetting':
				buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3l172x`} type="primary" op="create" onClick={() => this.saveField()}>{i18n.button.save()}</Button>);
				buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8l71ws`} type="primary" op="entry" onClick={() => this.saveField(true)}>{i18n.button.toDataMaintenance()}</Button>);
				logSmallType = this.logTypeDef.HRM_ENGINE_Matrix_Design;
				break;
			case 'dataMaintenance':
				if(this.hassaveright){
					buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@tb21zw`} type="primary" op="create" onClick={() => this.saveMatrixData()}>{i18n.button.save()}</Button>);
				}
				buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@o4r1j7`} type="primary" op="export" onClick={() => this.exportMatrix()}>{i18n.button.export()}</Button>);
				if(this.dataOpBtnsVisible){
					buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@eisezy`} type="primary" op="import" onClick={() => this.importMatrix()}>{i18n.button.import()}</Button>);
				}
				if(this.canClear){
					buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@d6epki`} type="primary" op="sync" onClick={() => this.clearDimission()}>{i18n.button.clearDimission()}</Button>);
				}
				logSmallType = this.logTypeDef.HRM_ENGINE_Matrix_Table;
				break;
			case 'maintenance':
				logSmallType = this.logTypeDef.HRM_ENGINE_Matrix_Maint;
				break;
		}

		buttons.map((btn, index) => {
			const {
				props
			} = btn;
			this.editorDialogRightMenu.push({
				key: index.toString(),
				content: props.children,
				icon: <i className={this.menuIconCollection[props.op]}/>,
				onClick: props.onClick
			});
		});
		this.editorDialogRightMenu.push({
			key: '99',
			content: i18n.button.log(),
			icon: <i className={this.menuIconCollection.log}/>,
			onClick: () => this.showOpLog(logSmallType, this.selectedMatrix.matrixid)
		});
		if(this.dialogParams.opType == 'dataMaintenance'){
			this.editorDialogRightMenu.push({
				icon: <i className='icon-coms-task-list'/>,
				content:i18n.button.columnVisibleSetting(),
				key: 'definedColumn',
				onClick: key =>{
					this.definedColumn();
				}
			});
		}

		// if(this.dialogParams.visible){
		// 	this.dialogParams.moreBtn.datas.length = 0;
		// 	this.dialogParams.moreBtn.datas = this.editorDialogRightMenu;
		// }
		return buttons;
	}
	/********************* dialog info setting *********************/

	/********************* observable list *********************/
	dialogParams = { //override baseStore.dialogParams
		...this.dialogPropsDef,
		opType: '',
		bottomLeft: '',
		onCancel: () => {
			this.dialogParams.opType == 'dataMaintenance' && this.cleanData();
			this.dialogParams.opType = '';
			this.selectedMatrix = null;
			this.dialogParams.visible = false;
			this.dialogParams.bottomLeft = '';
		}
	}

	@observable maintenanceParams = {
		icon: "icon-coms-hrm",
		iconBgcolor: "#217346",
		visible: false,
		onOk: (data) => {
			this.saveMaintenance(data);
			this.maintenanceParams.visible = false;
		},
		onCancel: () => this.maintenanceParams.visible = false
	}

	@observable matrixList = [];
	@observable createable = false;
	@observable dataOpBtnsVisible = false;
	@observable canClear = false;
	// @observable maintenanceList = new TableStore();
	// @observable refreshDialog = new Date().getTime();

	@observable _dialogHeight;
	@computed get dialogHeight(){
		return this._dialogHeight;
	}
	set dialogHeight(v){
		this._dialogHeight = v;
	}

	/********************* observable list *********************/

	/********************* computed list *********************/
	@computed get maintenanceListTableMultiRemoveable() {
		return this.maintenanceList.selectedRowKeys.length == 0;
	}
	/********************* computed list *********************/

	/********************* action list *********************/
	@action initData = () => {
		this.selectedSubCompany = null;
		this.containerInitFinished = {
			...this.containerInitFinished,
			init: true
		}
		this.getSearchCondition();
		this.getMatrixList();
	}

	@action getSearchCondition = () => {
		api.getMatrixListConditionList().then(data => {
			if(data.status == '1'){
				this.setFormData("conditionForm", data.conditions);
			}
		})
	}

	@action getMatrixList = (params) => {
		const queryParams = {};
		params != null && Object.assign(queryParams, {...params});
		this.selectedSubCompany != null && Object.assign(queryParams, {subCompanyId: this.selectedSubCompany.id});
		api.getMatrixList(queryParams).then(data => {
			if (data.status === '1'){
				this.createable = (data.isNew == '1');
				this.matrixList = data.matrixList;
			}else
				message.error(data.message);
		}, error => {})
	}

	@action treeNodeClick = (event, ids, nodeids, nodes) => {
        const {
            data: nodeData
        } = event.node.props;
		this.selectedSubCompany = nodeData;
		this.getMatrixList();
    }

	@action getMatrixInfoForm = (params) => {
		this.selectedMatrix = params;
		if(params == null){
			params = {};
			this.selectedSubCompany != null && Object.assign(params, {subCompanyId: this.selectedSubCompany.id});
		}
		api.getMatrixInfoForm(params).then(data => {
			if (data.status === '1') {
				this.setFormData('matrixInfoForm', data.formField);
				const {
					matrixInfoForm: form,
					matrixInfoFormFields: fields
				} = this.formTarget;
				if (form.isFormInit) {
					this.dialogParams.isEdit = false;
					this.dialogParams.title = params == null ? i18n.label.createMatrix() : i18n.label.modifyMatrix();
					this.dialogParams.coms = <FormInfo ecId={`${this && this.props && this.props.ecId || ''}_FormInfo@nek5bd`} center={false} form={form} formFields={fields}></FormInfo>;
					this.dialogParams.style = {
						width: 500,
						height: 280
					}
					this.dialogParams.visible = true;
				}
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	@action save = () => {
		const {
			matrixInfoForm: form,
		} = this.formTarget;
		form.validateForm().then(f => {
			if (f.isValid) {
				let params = {
					...form.getFormParams()
				}
				let create = true;
				has(this.selectedMatrix, 'matrixid') && Object.assign(params, {
					matrixid: this.selectedMatrix.matrixid
				}) && (create = false);
				let found = false;
				this.matrixList.map(arr => {
					arr.map((matrix, i) => {
						if (matrix.name === params.name && (create || matrix.id != params.matrixid))
							found = true;
					})
				})
				if (found) {
					message.error(i18n.confirm.matrixNameExist());
					return;
				}
				api.saveMatrixInfo(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.saveSuccess());
						this.dialogParams.onCancel();
						this.getMatrixList();
					} else
						message.error(data.message);
				}, error => {
					message.error(i18n.message.actionError());
				});
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		});
	}

	@action removeMatrixInfo = (params) => {
		this.confirmInfo({
			content: i18n.confirm.deleteSelected(),
			onOk: () => {
				api.removeMatrixInfo(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.deleteSuccess());
						this.getMatrixList();
					} else {
						message.error(data.message);
					}
				}, error => {})
			}
		});
	}

	//old version
	// @action showMaintenance = (params) => {
	// 	this.selectedMatrix = params;
	// 	api.initMaintenanceData(params).then(rs => {
	// 		rs.map((result, index) => {
	// 			if (result.status === '1') {
	// 				switch (index) {
	// 					case 0:
	// 						this.setFormData('matrixMatrixConditionForm', result.conditions);
	// 						break;
	// 					case 1:
	// 						this.maintenanceList.getDatas(result.sessionkey, 1);
	// 						this.dialogParams.opType = 'maintenance';
	// 						this.dialogParams.title = `${i18n.label.matrixMaintenance()}:${params.name}`;
	// 						this.dialogParams.style = {
	// 							width: 600,
	// 							height: 450
	// 						}
	// 						this.dialogParams.coms = <MatrixEdit store={this} columnHelpful={result.tips}/>;
	// 						this.dialogParams.visible = true;
	// 						break;
	// 				}
	// 			}
	// 		})
	// 	})
	// }

	//old version
	// @action createMaintenance = () => {
	// 	this.maintenanceParams.visible = true;
	// }

	@action saveMaintenance = (params) => {
		api.saveMatrixMaintenance({ ...params,
			...this.selectedMatrix
		}).then(data => {
			if (data.status === '1') {
				message.success(i18n.message.saveSuccess());
				this.maintenanceList.getDatas();
			} else {
				message.error(data.message);
			}
		}, error => {})
	}

	@action removeMaintenance = (params) => {
		this.confirmInfo({
			content: i18n.confirm.deleteSelected(),
			onOk: () => {
				if (!has(params, 'delids')) {
					params = {
						delids: this.maintenanceList.selectedRowKeys
					}
				}
				Object.assign(params, { ...this.selectedMatrix
				});
				api.removeMatrixMaintenance(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.deleteSuccess());
						this.maintenanceList.getDatas();
					} else {
						message.error(data.message);
					}
				}, error => {})
			}
		});
	}

	@action showFieldSetting = (params) => {
		this.selectedMatrix = params;
		this.dialogParams.opType = 'fieldSetting';
		this.dialogParams.title = `${i18n.button.fieldMaintenance()}:${params.name}`;
		this.dialogParams.style = {
			width: 850,
			height: 480
		}
		this.dialogParams.coms = <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@4wk6gb`} datas={this.editorDialogRightMenu}><MatrixFieldSetting ecId={`${this && this.props && this.props.ecId || ''}_MatrixFieldSetting@bwx8j5`} matrix={this.selectedMatrix} rootStore={this}/></WeaRightMenu>;
		this.dialogParams.visible = true;
	}

	@action saveField = (showDataMaintenance) => {}

	@action showDataMaintenance = (params) => {
		this.selectedMatrix = params;
		this.dialogParams.opType = 'dataMaintenance';
		this.dialogParams.title = `${i18n.button.dataMaintenance()}:${params.name}`;
		this.dialogParams.style = {
			width: 1000,
			height: 430
		}
		this.dialogParams.coms = <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@wik9rb`} datas={this.editorDialogRightMenu}><MatrixDataMaintenance ecId={`${this && this.props && this.props.ecId || ''}_MatrixDataMaintenance@gmbf4q`} matrix={this.selectedMatrix} rootStore={this}/></WeaRightMenu>;
		this.dialogParams.visible = true;
	}

	@action saveMatrixData = () => {}
	@action importMatrix = () => {}
	@action exportMatrix = () => {}
	@action definedColumn = () => {}
	@action cleanData = () => {}
	@action clearDimission = () => {}

	@action showOpLog = (logSmallType, targetId = '') => {
		this.showLog({
			logType: '4',
			logSmallType,
			targetId
		});
	}

	@action setDialogBottomLeft = v => this.dialogParams.bottomLeft = v;
	/********************* action list *********************/
}

const hrmMatrix = new HrmMatrix();
const stores = {
	hrmMatrix,
	...hrmMatrix.stores
}

export default stores;