import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaForm,
	WeaTableNew,
	WeaSwitch
} from 'comsMobx';
import {
	WeaTools
} from 'ecCom';
import {
	Button,
	message
} from 'antd';
import Screen from '../components/matrix/Screen';
import SubCompanyDisplaySetting from '../components/matrix/SubCompanyDisplaySetting';
import HrmBaseStore from './baseStore';
import * as api from '../apis/matrix';
import classnames from 'classnames';
import findIndex from 'lodash/findIndex';
import {
	has,
	reverse,
	sortedUniq,
	flattenDeep
} from 'lodash';
import {
	getColumIndex,
	validNumber
} from '../util/index';
import {
	i18n
} from '../public/i18n';

const {
	TableStore
} = WeaTableNew;

class HrmMatrixDataMaintenance extends HrmBaseStore {
	constructor(props) {
		super(props);
		this.tmpDom = null;
	}

	rootStore;
	importStore;
	setRootStore = (rootStore) => {
		this.rootStore = rootStore;
		rootStore.saveMatrixData = () => this.saveMatrixData();
		rootStore.importMatrix = this.importMatrix;
		rootStore.exportMatrix = this.exportMatrix;
		rootStore.clearDimission = this.clearDimission;
		rootStore.cleanData = this.cleanData;
		rootStore.definedColumn = () => this.definedColumn(this.tableStore);
	}

	setImportStore = (hrmImportResource) => {
		this.importStore = hrmImportResource;
	}
	/********************* unobservable list *********************/
	matrixInfo;
	colMap = new Map();
	showCols = [];

	tabConfig = {
		tabs: [{
			color: '#000000',
			groupId: 'target',
			title: '',
			viewCondition: '1',
		}],
		keyParam: 'viewCondition',
		activeTabKey: '1'
	}

	pageSize;
	table;
	screen = {
		condition: {},
		replaceDatas: {}
	};
	setTableRef = (t) => this.table = t;
	/********************* unobservable list *********************/

	/********************* dialog info setting *********************/
	/********************* dialog info setting *********************/

	/********************* observable list *********************/
	@observable refreshTab = new Date().getTime();
	@observable selectedRowKeys = [];
	@observable loading = false;
	@observable tableStore = new TableStore();
	// @observable radioGroupProps = {};
	// @observable subCompanyFullPathProps = {};
	@observable dataOpBtnsVisible = false;
	@observable canClear = false;
	@observable initDataFinished = false;
	@observable hasRight = true;

	tableEditConfig = {
		...this.editTableConfig,
		showTitle: false,
		draggable: false,
		showAdd: false,
		showDelete: true,
		showCopy: false,
		columns: [],
		datas: [],
		getRowSelection: (rowSelection) => {
			if (this.matrixInfo.issystem === '1' || this.matrixInfo.issystem === '2')
				return null;
			const sel = { ...rowSelection
			};
			sel.getCheckboxProps = record => {
				return {
					disabled: false
				};
			};
			return sel;
		},
		tableProps: {
			scroll: {
				//x: 450,
				y: 150
			},
			bordered: true
		}
	}

	@observable currentPage = 1;
	@observable defaultPageSize = 10;

	@observable pagination = {
		total: 0,
		showQuickJumper: true,
		pageSizeOptions: [10, 20, 50, 100],
		showSizeChanger: true,
		showTotal: (total) => {
			return `${i18n.label.total()} ${total} ${i18n.label.dataSourceCount()}`;
		},
		onShowSizeChange: (current, pageSize) => {
			this.currentPage = 1;
			this.defaultPageSize = pageSize;
			this.resetTableScroll();
			this.getMatrixData();
		},
		onChange: (current, pageSize) => {
			this.currentPage = current;
			this.resetTableScroll();
			this.getMatrixData();
		}
	}
	/********************* observable list *********************/

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

	@observable _hasData = false;
	@computed get hasData(){
		return this._hasData;
	}
	set hasData(v){this._hasData = v}
	/********************* computed list *********************/

	/********************* action list *********************/
	setComProps = () => {
		if (this.matrixInfo.issystem != '1' && this.matrixInfo.issystem != '2') {
			this.tabConfig.tabs[0].tabButtonDef = [];
			if(this.singlePage && this.dimission){
				this.tabConfig.tabs[0].tabButtonDef.push({
					comType: 'customer',
					coms: <span style={{textAlign: 'left', color: 'red'}} dangerouslySetInnerHTML={{__html: `${this.dimission}`}}></span>
				});
			}
			if(this.dataOpBtnsVisible){
				this.tabConfig.tabs[0].tabButtonDef.push({
					comType: 'WeaButtonIcon',
					icon: 'add',
					label: i18n.button.create(),
					rightMenuIcon: this.menuIconCollection.create,
					onClickHandle: this.onAdd
				});
				this.tabConfig.tabs[0].tabButtonDef.push({
					comType: 'WeaButtonIcon',
					icon: 'del',
					label: i18n.button.delete(),
					rightMenuIcon: this.menuIconCollection.remove,
					onClickHandle: this.onRemove,
					checkAction: 'tableMultiRemoveable'
				})
			}
			this.tabConfig.tabs[0].tabButtonDef.push({
				btnType: 'ghost',
				label: i18n.button.columnVisibleSetting(),
				onClickHandle: () => this.definedColumn(this.tableStore),
			});
		} else {
			this.tabConfig.tabs[0].tabButtonDef = [{
				btnType: 'ghost',
				label: i18n.button.columnVisibleSetting(),
				onClickHandle: () => this.definedColumn(this.tableStore),
			}]
		}
		// this.refreshTab = new Date().getTime();
	}

	@action initData = (matrix, single = false) => {
		this.singlePage = single;
		this.loading = false;
		this.initDataFinished = false;
		this.hasRight = true;
		this.matrixInfo = matrix;
		this.screen.condition = {};
		this.screen.replaceDatas = {};
		this.currentPage = 1;
		this.pagination.total = 0;
		// this.setComProps();
		this.initTableEditData();
	}

	refreshCurrentData = () => {
		this.screen.condition = {};
		this.screen.replaceDatas = {};
		this.currentPage = 1;
		this.initTableEditData();
	}

	resetTableScroll = () => {
		jQuery(".ant-table-body", ReactDOM.findDOMNode(this.table)).scrollTop(0);
		jQuery(".ant-table-body", ReactDOM.findDOMNode(this.table)).scrollLeft(0);
	}

	transferTableEditColumns = (columns) => {
		this.colMap.clear();
		const cols = [{
			title: <div className='idxH'>{i18n.label.orderId()}</div>,
			dataIndex: 'dataorder',
			key: 'dataorder',
			colSpan: 1,
			className: 'idx',
			useRecord: true,
		}];
		if (columns.length > 0) {
			columns.map((typeArr, index) => {
				typeArr.map((col, i) => {
					const colCls = classnames({
							['condition']: index === 0,
							['val']: index === 1
						}),
						hCls = classnames({
							['conditionH']: index === 0,
							['valH']: index === 1
						});
					const {settings} = col;
					const showDisplaySetting = settings && settings.length > 0;

					const radioGroupProps = {}, subCompanyFullPathProps = {};
					if(showDisplaySetting){
						settings[0].items.map((condition, index) => {
							switch(index){
								case 0:
									let options = [];
									options = condition.options.map(op => {
										return {
											showname: op.showname,
											value: op.key
										}
									});
									Object.assign(radioGroupProps, {
										options,
										value: condition.value
									})
									break;
								case 1:
									Object.assign(subCompanyFullPathProps, {
										options: condition.options,
										value: condition.value
									})
									break;
							}
						})
					}
					const titleCom = (
						<div className={hCls}>
							<div className='title' title={col.title}>
								{col.title}
							</div>
							{
								showDisplaySetting && 
								<SubCompanyDisplaySetting ecId={`${this && this.props && this.props.ecId || ''}_SubCompanyDisplaySetting@pc868p@${i}`} radioGroupProps={radioGroupProps} subCompanyFullPathProps={subCompanyFullPathProps} save={(value) => this.saveSubCompanyFullPathSetting(value, col.dataIndex)}/>
							}
							<Screen ecId={`${this && this.props && this.props.ecId || ''}_Screen@n6xlyw@${i}`} replaceDatas={this.screen.replaceDatas[col.dataIndex]} doScreen={this.doScreen} resetScreen={this.resetScreen} col={col}/>
						</div>
					);
					cols.push({
						className: colCls,
						title: titleCom,
						dataIndex: col.dataIndex,
						key: col.dataIndex,
						useRecord: true,
						colSpan: 1
					})
					this.colMap.set(col.dataIndex, col);
				})
			})
		}
		return cols;
	}

	generateColCom = (data) => {
		data.com == null && (data.com = {});
		const dKeys = Object.keys(data);
		dKeys.map(k => {
			if (k != 'com' && k != 'index' && k != 'uuid') {
				if (k === 'dataorder')
					data[`${k}spanspan`] = data[k];
				const enable = ((data[`${k}_editable`] || '1') == '1' ? true : false);
				data.com[k] = [<div className='cellItem' style={{color: enable ? null : '#ccc'}} onClick={() => enable && this.onCellClick(data, k)} dangerouslySetInnerHTML={{ __html: data[`${k}spanspan`] }}></div>]
			}
		})
		return data;
	}

	onCellClick = (data, k) => {
		if (this.matrixInfo.issystem != '') {
			if (k === 'dataorder' || this.colMap.get(k).type === '0')
				return;
		}

		let coms;
		if (k === 'dataorder') {
			coms = {
				label: '',
				type: 'INPUT',
				editType: '1',
				key: k,
				otherParams: {
					onBlur: () => {},
					filter: (val) => validNumber(val)
				}
			}
		} else {
			coms = {
				label: '',
				type: 'BROWSER',
				editType: '1',
				key: k,
				browserConditionParam: this.colMap.get(k).coms.browserConditionParam,
				width: 120,
				otherParams: {
					ref: (dom) => {
						this.tmpDom = dom;
					},
					onBlur: () => {}
				}
			}
		}
		this.tableEditConfig.datas[data.index].com[k] = [coms];
		this.refreshTab = new Date().getTime();
	}

	transferTableEditData = (dataSource, columns, isScreen) => {
		let datas = [];
		if (dataSource.length === 0 && !isScreen) {
			let data = {
				com: {},
				index: 0
			};
			if(this.dataOpBtnsVisible){
				columns.map(col => {
					if (col.dataIndex === 'dataorder') {
						data.dataorder = '1';
						data.dataorderspan = '1';
					} else {
						data[col.dataIndex] = '';
						data[`${col.dataIndex}span`] = '';
					}
				})
				datas.push(this.generateColCom(data));
			}
		} else {
			dataSource.map((d, index) => {
				d.index = index;
				datas.push(this.generateColCom(d));
			})
		}
		return datas;
	}

	clearTableData = () => {
		this.tableEditConfig.columns = [];
		this.tableEditConfig.datas = [];
		this.selectedRowKeys.length = 0;
		this.tableEditConfig.selectedRowKeys = [];
	}

	@action initTableEditData = async (condition) => {
		this.clearTableData();
		const matrixListData = await api.getMatrixList();
		if (matrixListData.status === '1'){
			const data = matrixListData.matrixList.reduce((pre, cur) => {
				pre = pre.concat(cur);
				return pre;
			}, []);
			this.hasRight = findIndex(data, {id: this.matrixInfo.matrixid}) > -1;
		}else{
			this.hasRight = false;
			message.error(matrixListData.message);
		}
		if(!this.hasRight)
			return;

		const data = await api.getMatrixTableStringForm({matrixid: this.matrixInfo.matrixid});
		if(data.sessionkey){
			this.tableStore.getDatasCallback = () => {
				this.tableStore.tableColSet(true, (keys, datas) => {
					this.showCols = keys.map(k => k.toLowerCase());
					this.getMatrixData();
				});
			}
			this.tableStore.getDatas(data.sessionkey);
		}

		// api.initMatrixData({matrixid: this.matrixInfo.matrixid}).then(result => {
		// 	result && result.map((data, index) => {
		// 		switch(index){
		// 			case 0:
		// 				this.tableStore.getDatasCallback = () => {
		// 					this.tableStore.tableColSet(true, (keys, datas) => {
		// 						this.showCols = keys.map(k => k.toLowerCase());
		// 						this.getMatrixData();
		// 					});
		// 				}
		// 				this.tableStore.getDatas(data.sessionkey);
		// 				break;
		// 			case 1:
		// 				data.condition && data.condition[0].items.map((condition, index) => {
		// 					switch(index){
		// 						case 0:
		// 							let options = [];
		// 							options = condition.options.map(op => {
		// 								return {
		// 									showname: op.showname,
		// 									value: op.key
		// 								}
		// 							});
		// 							this.radioGroupProps = {
		// 								options,
		// 								value: condition.value
		// 							}
		// 							break;
		// 						case 1:
		// 							this.subCompanyFullPathProps = {
		// 								options: condition.options,
		// 								value: condition.value
		// 							}
		// 							break;
		// 					}
		// 				})
		// 				break;
		// 		}
		// 	});

		// })
	}

	@action cleanData = () => {
		this.tableEditConfig = {
			...this.tableEditConfig,
			columns: [],
			datas: [],
		}
		this.refreshTab = new Date().getTime();
	}

	@observable viewData = false;

	@action getMatrixData = (resetScrool = false) => {
		this.loading = true;
		this.viewData = false;
		// this.clearTableData();
		const params = {
			matrixid: this.matrixInfo.matrixid,
			page: this.currentPage,
			pageSize: this.defaultPageSize,
			showCols: this.showCols.join(",")
		}
		const conditionParam = this.toJS(this.screen.condition);
		if (Object.keys(conditionParam).length > 0) {
			Object.assign(params, {
				condition: JSON.stringify(conditionParam)
			})
		}else{
			this.screen = {
				condition: {},
				replaceDatas: {}
			}; 
		}
		
		api.getMatrixData(params).then(data => {
			this.dimission = '';
			if (data.status === '1') {
				this.viewData = true;
				this.dataOpBtnsVisible = (data.hasright == "1");
				this.canClear = (data.clearright == "1");
				Object.assign(this.matrixInfo, {issystem: data.issystem || ''});
				this.rootStore.dataOpBtnsVisible = this.dataOpBtnsVisible;
				this.rootStore.hassaveright = data.hassaveright || false;
				this.rootStore.canClear = this.canClear;
				const columns = this.transferTableEditColumns(data.columns);
				const datas = this.transferTableEditData(data.dataSource, columns, params.condition != null);
				this.hasData = columns.length > 1;
				this.tableEditConfig = {
					...this.tableEditConfig,
					columns,
					datas,
					tableProps: {
						...this.tableEditConfig.tableProps,
						scroll: {
							//...this.tableEditConfig.tableProps.scroll,
							x: (columns.length) * 186 + 66,
							y: this.rootStore.dialogHeight -295//this.matrixInfo.issystem === '' ? 295 : 350
						}
					}
				}
				this.dimission = data.dimission;
				this.rootStore.setDialogBottomLeft((<div style={{textAlign: 'left'}} dangerouslySetInnerHTML={{__html: data.dimission || ''}}></div>));

				this.pagination.total = data.totalCount;
				if (flattenDeep(data.columns).length === 0) {
					if(this.dataOpBtnsVisible){
						this.rootStore.dialogParams.visible = false;
						this.rootStore.showFieldSetting(this.matrixInfo);
					}else
						message.error(i18n.message.authFailed());
				} else{
					resetScrool && this.resetTableScroll();
				}

				this.setComProps();
				this.refreshTab = new Date().getTime();
				this.initDataFinished = true;
			} else {
				message.error(data.message);
				this.dataOpBtnsVisible = (data.hasright == "1");
			}

			this.loading = false;
		}, error => {
			this.loading = false;
		})
	}

	resetScreen = (dataIndex) => {
		delete this.screen.condition[dataIndex];
		delete this.screen.replaceDatas[dataIndex];
		this.currentPage = 1;
		this.getMatrixData(true);
	}

	doScreen = (dataIndex, screen) => {
		Object.assign(this.screen.condition, { ...screen.screenObj
		})
		this.screen.replaceDatas[dataIndex] = screen.replaceDatas;
		this.currentPage = 1;
		this.getMatrixData(true);
	}

	@action saveSubCompanyFullPathSetting = (value, dataIndex) => {
		const {radioValue, fullPathValue} = value;
		// this.radioGroupProps.value = radioValue;
		// this.subCompanyFullPathProps.value = fullPathValue;
		api.saveMatrixShowNameSetForm({
			matrixid: this.matrixInfo.matrixid,
			nameset: radioValue,
			orderset: fullPathValue,
			dataIndex
		}).then(data => {
			if(data.status == '1'){
				message.success(i18n.message.saveSuccess());
				this.getMatrixData(true);
			}else
				message.error(data.message);
		});
	}

	onTableEditChange = (datas) => {
		this.tableEditConfig.datas = datas;
	}

	onRowSelect = (sRowKeys, rows, dataIndex, selectedDatas) => {
		this.selectedRowKeys = sRowKeys;
	}

	onAdd = () => {
		let data = {
			com: {},
			index: this.tableEditConfig.datas.length,
		};
		this.tableEditConfig.columns.map(col => {
			if (col.dataIndex === 'dataorder') {
				data.dataorder = '';
				data.dataorderspan = '';
			} else {
				data[col.dataIndex] = '';
				data[`${col.dataIndex}span`] = '';
			}
		})
		this.tableEditConfig.datas.push(this.generateColCom(data));
		this.refreshTab = new Date().getTime();
	}

	onRemove = () => {
		const datas = this.toJS(this.tableEditConfig.datas);
		const params = {
			matrixid: this.matrixInfo.matrixid,
			deleteitems: []
		};
		this.selectedRowKeys.map(index => {
			if (has(datas[index], 'uuid')) {
				params.deleteitems.push(datas[index].uuid);
			}
		})
		const removeItem = () => {
			const arr = sortedUniq(this.toJS(this.selectedRowKeys)).sort((n1, n2) => n2 - n1);
			arr.map(index => {
				this.tableEditConfig.datas.splice(index, 1);
			});
			if (this.tableEditConfig.datas.length === 0)
				this.onAdd();
			this.selectedRowKeys.length = 0;
			this.tableEditConfig.selectedRowKeys = [];
			this.pagination.total -= params.deleteitems.length;
		}

		if (params.deleteitems.length === 0) {
			removeItem();
		}

		this.confirmInfo({
			content: i18n.confirm.deleteSelected(),
			onOk: () => {
				this.showWeaLoadingGlobal();
				api.removeMatrixData(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.deleteSuccess());
						this.rootStore.getMatrixList();
						removeItem();
					} else {
						message.error(data.message);
					}
					this.hideWeaLoadingGlobal();
				}, error => {})
			}
		});
	}

	@action saveMatrixData = callback => {
		this.loading = true;
		const datas = this.toJS(this.tableEditConfig.datas);
		datas.map(data => {
			delete data.com;
		})
		const params = {
			data: JSON.stringify({
				matrixid: this.matrixInfo.matrixid,
				data: datas,
				outsubcompany: '',
				outcrmmanager: '',
				outmanager: '',
				showCols: this.showCols.join(",")
			})
		}
		let hasNewRecord = false;
		datas.map(d => {
			if(!has(d, "uuid")){
				hasNewRecord = true;
			}
		});
		api.saveMatrixData(params).then(data => {
			if (data.status === '1') {
				if(callback)
					callback();
				else{
					message.success(i18n.message.saveSuccess());
					this.rootStore.getMatrixList();
					this.getMatrixData(hasNewRecord);
				}
			} else {
				message.error(data.message);
			}
		})
	}
	downloadRef;
	setIframRef = (ref) => {
		this.downloadRef = ref;
	}

	@action importMatrix = () => {
		this.importStore.init();
		this.importStore.visible = true;
		this.importStore.title = i18n.button.importMatrix();
		this.importStore.importType = 'matrix';
		this.importStore.keyField = null;
		this.importStore.getTemplateUrl = (matrixid, type, otherParams) =>{
			api.getMatrixFile({matrixid: matrixid, type: type, showCols: this.showCols.join(","), ...otherParams}).then(data =>{
				if(data.status === '1'){
					WeaTools.downloadFile(type === 'add' ? data.addFilePath : data.updateFilePath, 'GET');
				}
			})
		}
		this.importStore.otherParams = {
			matrixid: this.matrixInfo.matrixid,
			method: "exportData",
			issystem: this.matrixInfo.issystem,
			logSmallType: this.matrixInfo.matrixid,
			showCols: this.showCols.join(",")
		};
		this.importStore.getImportForm();
	}

	@action exportMatrix = () => {
		api.matrixExport({
			otherParams: JSON.stringify({
				matrixid: this.matrixInfo.matrixid,
				method: 'exportDataNoSQ',
				showCols: this.showCols.join(",")
			})
		}).then(data => {
			if (data.status === '1')
				WeaTools.downloadFile(data.exportFile, "GET");
		})
	}

	@action setShowCols = keys => {
		this.showCols = keys.map(k => k.toLowerCase());
		this.currentPage = 1;
		this.getMatrixData();
	}

	@action clearDimission = () => {
		this.saveMatrixData(() => api.clearDimission({matrixid: this.matrixInfo.matrixid}).then(data => {
			if(data.status == '1'){
				message.success(i18n.message.opSuccess());
				this.getMatrixData();
			}else{
				message.error(data.message);
			}
		}));
	}
	/********************* action list *********************/
}

export const hrmMatrixDataMaintenance = new HrmMatrixDataMaintenance();