import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaForm,
	WeaSwitch
} from 'comsMobx';
import {WeaCheckbox} from 'ecCom';
import {
	Button,
	message
} from 'antd';
import HrmBaseStore from './baseStore';
import * as api from '../apis/privacySetting';
import FormInfo from '../coms/FormInfo';
import ShowSetCol from '../components/privacySetting/ShowSetCol';
import {
	i18n
} from '../public/i18n';
import concat from 'lodash/concat';
import findIndex from 'lodash/findIndex';
import has from 'lodash/has';


export class HrmPrivacySetting extends HrmBaseStore {
	/********************* unobservable list *********************/
	rightMenus = [];
	ref = {};
	allSelectedRowKeys = [];
	allSelectedRecords = [];

	topBtnAndMenu = () => {
		let btnDef = ['save'];
		let btns = [];
		let menus = [];
		this.rightMenus.map((menu, i) => {
			let disabled = false;
			if (btnDef.indexOf(menu.menuFun) < 0) {
				disabled = this[`${menu.menuFun}Editable`];
			}
			btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fb5a78@${i}`} type='primary' onClick={() => this[menu.menuFun]()} disabled={disabled}>{menu.menuName}</Button>);
			menus.push({
				key: i.toString(),
				content: menu.menuName,
				icon: <i className={menu.menuIcon}/>,
				onClick: () => this[menu.menuFun](),
				disabled
			});
		})
		return {
			btns,
			menus: [...menus, ...this.getBasicMenus()]
		}
	}

	editorDialogRightMenu = [];
	getDialogOpButtons = () => {
		let buttons = [];
		this.editorDialogRightMenu.length = 0;
		buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@dnb88c`} type="primary" op="save" onClick={() => this.saveSetting()}>{i18n.button.save()}</Button>);

		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
			});
		})

		return buttons;
	}

	itemRender = {
		showType: (field, textAreaProps, form, formParams) => {
			if (formParams.showSet === '1'){
				window.e9HideFormFieldKeys = [];
				return (<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@fog9ya`} fieldConfig={{...field, ...textAreaProps}} 
						form={form} formParams={formParams}/>)
			}else{
				window.e9HideFormFieldKeys = ['showType'];
				return null;
			}
		}
	}
	/********************* unobservable list *********************/

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

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

	/********************* observable list *********************/
	@observable spinning = false;
	@observable btnCanEdit = false;
	@observable showSetStatus = {}
	@observable privacySettingList = [];

	dialogParams = {
		...this.dialogPropsDef,
		style: {
			height: 180,
			width: 600
		},
		onCancel: () => {
			this.dialogParams.visible = false;
		}
	}
	/********************* observable list *********************/

	/********************* computed list *********************/
	@computed get batchSetEditable() {
		return !this.btnCanEdit;
	}

	@computed get syncSetEditable() {
		return !this.btnCanEdit;
	}
	/********************* computed list *********************/

	/********************* action list *********************/
	initData = () => {
		this.containerInitFinished = {
			...this.containerInitFinished,
			init: true
		}
		if(this.spinning)
			return;
		this.btnCanEdit = false;
		this.privacySettingList.length = 0;
		this.spinning = true;
		api.initData().then(rs => {
			rs.map((result, index) => {
				if (result.status === '1') {
					switch (index) {
						case 0:
							this.rightMenus = result.rightMenu;
							break;
						case 1:
							result.items.map((item, i) => {
								let setting = {};
								if(has(item, 'table')){
									const {columns, datas} = this.convertTableProps(...[item.table.columns, item.table.datas, item.table.showTypes, item.title]);
									setting = {
										groupName: item.title,
										defaultShow: true,
										tableName: item.title,
										tableProps: {
											showTitle: item.table.showTitle,
											draggable: item.table.draggable,
											columns,
											initialDatas: datas,
											datas: datas,
											showTypes: item.table.showTypes,
											selectedRowKeys: []
										}
									}
								}else{
									setting = {
										groupName: item.title,
										defaultShow: item.defaultshow,
										item: item.item
									}
								}
								this.privacySettingList.push(setting);
							})
							this.spinning = false;
							break;
					}
				}
			})
		})
	}

	convertTableProps = (columns, datas, showTypes, tableName) => {
		let cnt = 0;
		datas.map(d => {
			if(d.showSet === '1')
				cnt++;
		})
		Object.assign(this.showSetStatus, {
			[tableName]: cnt === datas.length
		})
		columns.map((col, index) => {
			if(col.dataIndex === 'showSet'){
				col.title = <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@2espp5@${index}`} content={col.title} value={this.showSetStatus[tableName]} onChange={val => this.onSelectAll(val, tableName)}/>;
				col.com = [
					<ShowSetCol ecId={`${this && this.props && this.props.ecId || ''}_ShowSetCol@5mtsqv@${index}`} options={showTypes}/>
				];
			}
		})
		return {
			columns: columns,
			datas: datas
		}
	}

	setTableRef = (ref, tableName) => {
		this.ref[tableName] = ref;
	}

	onChange = (datas, other, tableName) => {
		let cnt = 0;
		datas.map(d => {
			if(d.showSet === '1')
				cnt++;
		})
		Object.assign(this.showSetStatus, {
			[tableName]: cnt === datas.length
		})
		const index = findIndex(this.toJS(this.privacySettingList), {tableName});
		if(index < 0)
			return;
		this.privacySettingList[index].tableProps.columns.map((col, index) => {
			if(col.dataIndex === 'showSet'){
				col.title = <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@aah70w@${index}`} content={col.title.props.content} value={this.showSetStatus[tableName]} onChange={val => this.onSelectAll(val, tableName)}/>;
			}
		})
		this.privacySettingList[index].tableProps.datas = datas;
	}

	onRowSelect = (selectedRowKeys, tableName) => {
		const index = findIndex(this.toJS(this.privacySettingList), {tableName});
		if(index < 0)
			return;
		this.privacySettingList[index].tableProps.selectedRowKeys = selectedRowKeys;
		this.allSelectedRowKeys = [];
		this.allSelectedRecords = [];
		this.privacySettingList.map(setting => {
			if(has(setting, 'tableProps') && setting.tableProps.selectedRowKeys != null) {
				this.allSelectedRowKeys = concat(this.allSelectedRowKeys, ...[this.toJS(setting.tableProps.selectedRowKeys)]);
				setting.tableProps.selectedRowKeys.map(id => {
					const tableDatas = this.ref[setting.tableName].state.datas;
					let rowIndex = findIndex(tableDatas, {id});
					if(rowIndex < 0)
						return;
					this.allSelectedRecords.push(tableDatas[rowIndex]);
				})
			}
		});
		this.btnCanEdit = (this.allSelectedRowKeys.length != 0);
	}

	@action onSelectAll = (val, tableName) => {
		const index = findIndex(this.toJS(this.privacySettingList), {tableName});
		if(index < 0)
			return;
		this.privacySettingList[index].tableProps.datas.map(d => {
			d.showSet = val;
		})
		Object.assign(this.showSetStatus, {
			[tableName]: val === '1'
		})
		this.privacySettingList[index].tableProps.columns.map((col, index) => {
			if(col.dataIndex === 'showSet'){
				col.title = <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@kns7ee@${index}`} content={col.title.props.content} value={this.showSetStatus[tableName]} onChange={val => this.onSelectAll(val, tableName)}/>;
			}
		})
		this.privacySettingList[index].tableProps.datas.map(d => {
			if(d.showSet === '0'){
				d.showType = '0';
			}
		})
	}

	@action save = (callback) => {
		let datas = [];
		[...Object.keys(this.ref)].map(key => {
			datas = concat(datas, this.ref[key].state.datas);
		})
		api.savePrivacySetting({datas: JSON.stringify(datas)}).then(data => {
			if(data.status === '1'){
				callback == null && message.success(i18n.message.saveSuccess());
				this.privacySettingList.map(setting => {
					if(has(setting, 'tableProps') && setting.tableProps.selectedRowKeys != null) setting.tableProps.selectedRowKeys.length = 0;
				});
				this.btnCanEdit = false;
				callback && callback();
			}else{
				message.error(data.message);
			}
		}, error => {})
	}

	@action batchSet = () => {
		api.batchPrivacySetting().then(data => {
			if(data.status === '1'){
				this.setFormData('batchSettingForm', data.formField);
				this.showDialog();
			}else{
				message.error(data.message);
			}
		}, error => {})
	}

	showDialog = () => {
		const {
			batchSettingForm: form,
			batchSettingFormFields: fields
		} = this.formTarget;
		if(form.isFormInit){
			this.dialogParams.title = i18n.button.multiSetting();
			this.dialogParams.coms = <FormInfo ecId={`${this && this.props && this.props.ecId || ''}_FormInfo@gxgle6`} form={form} formFields={fields} itemRender={this.itemRender} menu={this.editorDialogRightMenu}/>
			this.dialogParams.visible = true;
		}
	}

	@action saveSetting = () => {
		this.formTarget.batchSettingForm.validateForm().then(f => {
			if (f.isValid) {
				const params = this.formTarget.batchSettingForm.getFormParams();
				Object.assign(params, {ids: this.allSelectedRowKeys.join(',')});
				api.saveBatchPrivacySetting(params).then(data => {
					if (data.status === '1') {
						message.success(i18n.message.saveSuccess());
						this.dialogParams.visible = false;
						this.initData();
					} else {
						message.error(data.message);
					}
				}, error => {})
			} else {
				f.showErrors();
				this.showError = new Date().getTime();
			}
		});
	}

	@action syncSet = () => {
		this.confirmInfo({
			content: i18n.confirm.syncPrivacySetting(),
			onOk: () => {
				this.save(() => {
					api.syncPrivacySetting({datas: JSON.stringify(this.allSelectedRecords)}).then(data => {
						if (data.status === '1') {
							message.success(i18n.message.opSuccess());
						} else {
							message.error(data.message);
						}
					}, error => {})
				})
			}
		})
	}

	@action log = () => {
		this.showLog({
            logSmallType: this.logTypeDef.HRM_ENGINE_PrivacySetting
		});
	}
	/********************* action list *********************/
}

export const hrmPrivacySetting = new HrmPrivacySetting();