import {
	observable,
	action,
	computed,
	reaction,
	toJS,
} from 'mobx';
import {
	WeaTableNew,
} from 'comsMobx';
import {
	WeaBrowser,
	WeaLocaleProvider,
} from 'ecCom';
import {
	message,
} from 'antd';
import {
	fetch,
	array,
	callback,
	getTopButtons,
	getDropMenuDatas,
	getMenusCreationConfig,
	componentReset,
	confirmation,
} from '../util/save-time-util.js';
import {
	hrmImportCommon
} from './importCommon';
import * as asyncFetch from '../apis/vacationBalance';
const getLabel = WeaLocaleProvider.getLabel;
const {
	TableStore
} = WeaTableNew;

class HrmVacationBalanceCopy {
	//************权限*************
	@observable pageAccessPermission = {
		hasRight: false,
		loading: true,
	}

	@action getPermissionInfo = () => {
		fetch({
			asyncFetch,
			name: 'getHasRight',
			logic: (cb) => {
				const {
					hasRight
				} = cb;

				if (hasRight) {
					this.pageAccessPermission.hasRight = true;
				}
				this.pageAccessPermission.loading = false;
			}
		});
	}

	permissionDisposer = reaction(() => this.pageAccessPermission.hasRight, hasRight => {
		if (hasRight) {
			this.getTabs();
			this.refreshPage();
		}
	});

	//*************头部**************
	topComponentStaticProps = {
		icon: <i className='icon-coms-hrm'/>,
		iconBgcolor: '#217346',
		showDropIcon: true,
		title: getLabel('505619', "假期余额设置"),
	};

	@observable top = {
		btnMenu: [],
	}

	batchEditing = () => {
		confirmation.showSaveConfirm({
			content: getLabel(505620, '批处理将会初始化假期余额信息，确定批处理？'),
			logic: () => this._batchEditing()
		});
	}

	_batchEditing = () => {
		if (!this.isEmptyYear) {
			message.warning(getLabel('505621', "请指定年份！"));
			return
		}

		fetch({
			asyncFetch,
			name: 'batchProcessing',
			fetchParams: this.tableAsyncFetchParams,
			logic: (cb) => {
				const {
					sign
				} = cb;

				if (sign === '1') {
					message.success(cb.message);
					this.resetTableEditableDatas();
					this.getSearchList();
				} else {
					message.warning(cb.message);
				}
			}
		});
	}

	importExcel = () => {
		if (!this.isEmptyYear) {
			message.warning(getLabel('505621', "请指定年份！"));
			return
		}

		const templetName = getLabel('129833', '导入模板'),
			dialogTitle = getLabel('505622', "员工假期余额导入"),
			importType = 'balanceOfLeave',
			asyncFetchParams = this.tableAsyncFetchParams,
			visible = true;

		const paramsArray = [templetName, dialogTitle, importType, asyncFetchParams, visible, ];

		const funcs = ['setTempletName', 'setImportDialogTitle', 'setImportType', 'setFormAsyncParams', 'setImportDialogVisible']

		funcs.map((f, i) => {
			hrmImportCommon[f](paramsArray[i]);
		});
	}

	exportExcel = () => {
		if (!this.isEmptyYear) {
			message.warning(getLabel('505621', "请指定年份！"));
			return
		}

		const {
			tableStore
		} = this.table;

		if (tableStore.datas.length === 0) {
			message.warning(getLabel('505623', "暂无数据可导出！"));
			return
		}

		tableStore.exportAll();
	}

	custom = () => {
		const {
			tableStore
		} = this.table;

		['setColSetVisible', 'tableColSet'].map(f => {
			tableStore[f](true);
		});
	}

	save = () => {
		if (!this.isEmptyYear) {
			message.warning(getLabel('505621', "请指定年份！"));
			return
		}

		const {
			tableStore
		} = this.table;

		const datas = tableStore.datas;

		for (let index = 0; index < datas.length; index++) {
			const data = datas[index];

			const {
				baseAmountspan,
				baseAmount2span,
				usedAmountspan,
				usedAmount2span,
				extraAmountspan,
				extraAmount2span,
			} = data;

			const isMix = Object.keys(data).includes('usedAmount2span');

			if (!this.verifyTableField(['baseAmountspan', 'usedAmountspan', 'extraAmountspan'], data, index)) {
				return;
			}

			if (isMix && !this.verifyTableField(['baseAmount2span', 'usedAmount2span', 'extraAmount2span'], data, index, isMix)) {
				return;
			}
		}

		fetch({
			asyncFetch,
			name: 'saveBalanceOfLeave',
			fetchParams: this.getSaveParams(),
			logic: (cb) => {
				const {
					sign
				} = cb;

				message[sign === '1' ? 'success' : 'warning'](cb.message);
				this.resetTableEditableDatas();
				this.getSearchList();
			}
		});
	}

	verifyTableField = (fields, data, dataIndex, isMix) => {
		const {
			tableStore
		} = this.table;

		const {
			lastname
		} = data;

		const columns = tableStore.columns;

		const titles = {};
		//收集列表域对应的TITLE，用于必填校验提示语。
		['baseAmount', 'usedAmount', 'extraAmount', 'canUseAmount', 'baseAmount2', 'usedAmount2', 'extraAmount2', 'canUseAmount2'].map(v => {
			const target = columns.find(c => c.dataIndex === v);
			if (!target) return;
			Object.assign(titles, {
				[`${v}span`]: target.title
			});
		});
		//找到列表域为空时对应的DATAINDEX
		const field = fields.find(field => data[field] === '');

		if (field) {
			message.warning(`${getLabel('505567',"第")} ${dataIndex + 1} ${getLabel('27592',"行")},${lastname} ${titles[field]} ${getLabel('505571',"未填写")} `);
			return false;
		}

		let flag = true;

		const estimateUsedAmount = (used, base, extra, backup) => {
			//读取已修假期、基础假期、额外假期和本年假期的数据
			const usedAmount = parseFloat(data[used]),
				baseAmount = parseFloat(data[base]),
				extraAmount = parseFloat(data[extra]),
				canUseAmount = data[backup] ? parseFloat(data[backup]) : data[backup];

			//本年假期不存在时，使用基础假期（一次性发放）。
			const choice = canUseAmount !== undefined ? canUseAmount : baseAmount;

			//当已修假期大于基础假期（或本年假期）和额外假期之和时，给出超额提示。
			if (usedAmount > (choice + extraAmount)) {
				message.warning(`${getLabel('505567',"第")} ${dataIndex + 1} ${getLabel('27592',"行")},${lastname} ${titles[used]} ${getLabel('505624',"不能大于")} ${titles[backup] ? titles[backup] : titles[base]} +  ${titles[extra]} `);
				flag = false;
			}
		}

		estimateUsedAmount('usedAmountspan', 'baseAmountspan', 'extraAmountspan', 'canUseAmountspan');

		isMix && estimateUsedAmount('usedAmount2span', 'baseAmount2span', 'extraAmount2span', 'canUseAmount2span');

		return flag;
	}

	getSaveParams = () => {
		const params = {
			...this.tabCallbackParamsCollector,
			...this.rgCallbackParamsCollector,
			hrmResourceIds: this.table.ids.toString(),
		};

		['baseAmountValues', 'usedAmountValues', 'extraAmountValues', 'baseAmount2Values', 'usedAmount2Values', 'extraAmount2Values'].map(v => {
			Object.assign(params, {
				[v]: this.table[v].toString()
			});
		});

		return params;
	}

	@computed get menusAsyncFetch() {
		const params = {
			...this.treeCallbackParamsCollector,
			...this.tabCallbackParamsCollector,
		};

		return params;
	}

	@action getMenus = () => {
		fetch({
			asyncFetch,
			name: 'getMenus',
			fetchParams: this.menusAsyncFetch,
			logic: (cb) => {
				const {
					btnMenu,
				} = cb;

				const result = btnMenu.find(item => item.menuFun === 'batchEditing');
				if (result) result.title = getLabel('505625', "根据假期规则初始化假期基数");
				this.top.btnMenu = btnMenu;
			}
		});
	}

	@computed get menusCreationConfig() {
		const {
			btnMenu
		} = this.top;

		return getMenusCreationConfig(btnMenu);
	}

	get topButtons() {
		const {
			topMenu
		} = this.menusCreationConfig;

		return getTopButtons.call(this, {
			datas: topMenu,
			disabled: this.getMenusState(),
		})
	}

	get dropMenuDatas() {
		const {
			rightMenu
		} = this.menusCreationConfig;

		return getDropMenuDatas.call(this, {
			datas: rightMenu,
			disabled: this.getMenusState(),
		});

	}

	getMenusState = () => {
		const {
			tableStore
		} = this.table, {
			loading,
		} = tableStore;

		return [loading, loading, loading, loading];
	}


	//**************组织树******************
	orgTreeStaticProps = {
		title: getLabel('25332', "组织结构"),
		rightStr: 'KQLeaveRulesEdit:Edit',
		isLoadSubDepartment: true,
	}

	@observable orgTree = {
		triggerRefresh: false,
		organizationId: '',
		organizationType: '0',
	}

	@action handleOrgTreeNodeClick = (params) => {
		const {
			id,
			type,
		} = params;

		this.orgTree.organizationType = type;
		this.orgTree.organizationId = id;
	}

	@action triggerRefresh = () => {
		this.orgTree.triggerRefresh = !this.orgTree.triggerRefresh;
	}

	@computed get treeCallbackParamsCollector() {
		const callback = {};

		['organizationType', 'organizationId'].map(v => {
			Object.assign(callback, {
				[v]: this.orgTree[v]
			});
		});

		return callback;
	}

	treeDisposer = reaction(() => this.treeCallbackParamsCollector, treeCallbackParamsCollector => {
		// this.setTabActiveKey('0');
		this.getTabs();
	});

	//***************页签*****************
	@observable tab = {
		activeKey: '0',
		datas: [],
		ids: [],
	}

	@action setTabActiveKey = (key) => {
		this.tab.activeKey = key;
	}

	@action getTabs = () => {
		fetch({
			asyncFetch,
			name: 'getTabs',
			fetchParams: this.treeCallbackParamsCollector,
			logic: (cb) => {
				this.tab.datas = callback.getArrayDatas(cb);
				this.tab.ids = callback.getTabId(cb);
			}
		});
	}

	@computed get tabCallbackParamsCollector() {
		const {
			activeKey,
			ids
		} = this.tab;

		const callback = {};

		if (ids.length > 0) {
			Object.assign(callback, {
				ruleId: ids[parseInt(activeKey)]
			});
		}

		return callback;
	}

	@computed get hasContent() {
		const {
			datas
		} = this.tab;

		if (datas.length === 0) {
			return false;
		}
		return true;
	}

	tabDisposer = reaction(() => this.tabCallbackParamsCollector, tabCallbackParamsCollector => {
		this.getMenus();
		if (this.browser) {
			componentReset.resetBrowser(this.browser);
			this.radioGroup.hrmResourceId = '';
		}
		this.getRadioGroupConfig();
	})

	//***************单选组合（RadioGroup）*****************
	@observable radioGroup = {
		config: [],
		activeParams: {
			searchYearSelect: '',
			searchYear: '',
		},
		hrmResourceId: ''
	}

	@action getRadioGroupConfig = () => {
		fetch({
			asyncFetch,
			name: 'getSearchCondition',
			logic: (cb) => {
				const {
					conditions
				} = cb;

				this.processCondition(conditions);

				this.radioGroup.config = conditions[0].items;
			}
		});
	}

	@action handleBrowserChange = (ids) => {
		this.radioGroup.hrmResourceId = ids;
	}

	processCondition = (conditions) => {
		const browser = conditions[0].items[1];

		conditions[0].items[1] = {
			label: getLabel('25034', "姓名"),
			com: (<div style={{width: 264,marginTop: 6}}>
					 <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@08llbh`} {...browser.browserConditionParam} ref={ref =>  this.setRef(ref,'browser')} onChange ={ids => this.handleBrowserChange(ids)}/>
				  </div>),
			labelcol: 5,
			fieldcol: 19,
		}
	}

	setRef = (ref, type) => {
		this[type] = ref;
	}

	@action exportActiveParams = (params) => {
		Object.assign(this.radioGroup.activeParams, params);
	}

	@computed get isEmptyYear() {
		const {
			activeParams
		} = this.radioGroup, {
			searchYearSelect,
			searchYear
		} = activeParams;

		if (searchYearSelect === '6' && !searchYear) {
			return false;
		}
		return true;
	}

	@computed get rgCallbackParamsCollector() {
		const {
			activeParams,
			hrmResourceId
		} = this.radioGroup;

		const callback = {
			hrmResourceId,
			...activeParams,
		};

		return callback;
	}

	//**************列表******************
	@observable table = {
		ids: [],
		baseAmountValues: [],
		usedAmountValues: [],
		extraAmountValues: [],
		baseAmount2Values: [],
		usedAmount2Values: [],
		extraAmount2Values: [],
		tableStore: new TableStore(),
	}

	//收集列表中修改过的值
	@action sortChangedTableDatasOut = (values, rowId) => {
		const {
			ids
		} = this.table;

		let currentRowIndex = ids.length;

		//判断修改的列表域对应的行是否为新的一行
		if (array.isUnique(rowId, ids)) {
			this.table.ids.push(rowId);
		} else {
			currentRowIndex = ids.findIndex(id => id === rowId);
		}

		['baseAmountValues', 'baseAmount2Values', 'usedAmountValues', 'usedAmount2Values', 'extraAmountValues', 'extraAmount2Values'].map((name, index) => {
			this.table[name][currentRowIndex] = values[index];
		});
	}

	@computed get tableAsyncFetchParams() {
		const params = {
			...this.treeCallbackParamsCollector,
			...this.tabCallbackParamsCollector,
			...this.rgCallbackParamsCollector,
		}

		return params;
	}

	@action getSearchList = () => {
		if (!this.isEmptyYear) {
			message.warning(getLabel('505621', "请指定年份！"));
			return
		}

		this.table.tableStore = new TableStore();

		fetch({
			asyncFetch,
			name: 'getSearchList',
			fetchParams: this.tableAsyncFetchParams,
			logic: (cb) => {
				const {
					sessionkey,
				} = cb;

				this.table.tableStore.getDatas(sessionkey, 1);
			}
		});
	}

	@action resetTableEditableDatas = () => {
		['ids', 'usedAmountValues', 'extraAmountValues', 'usedAmount2Values', 'extraAmount2Values'].map(v => {
			this.table[v] = [];
		});
	}

	tableDisposer = reaction(() => this.tableAsyncFetchParams, tableAsyncFetchParams => {
		const {
			ruleId,
			searchYearSelect,
			searchYear,
		} = tableAsyncFetchParams;

		if (!ruleId || (!searchYearSelect || (searchYearSelect === '6' && !searchYear))) return

		this.resetTableEditableDatas();
		this.getSearchList();
	});

	componentWillUnmount = () => {
		this.pageAccessPermission.hasRight = false;
	}

	refreshPage = () => {
		this.triggerRefresh();
		this.setTabActiveKey('0');
		this.handleOrgTreeNodeClick({
			id: '',
			type: '0'
		});
		this.rg && componentReset.resetRadioGroup(this.rg);
		this.browser && componentReset.resetBrowser(this.browser);
		this.radioGroup.hrmResourceId = '';
	}


}

const hrmVacationBalance = new HrmVacationBalanceCopy;
export {
	hrmVacationBalance
}