import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaBrowser,
	WeaButtonIcon,
	WeaInputNumber,
	WeaLocaleProvider,
} from 'ecCom';
import {
	message,
	Button
} from 'antd';
import {
	AuthorityStore,
	TopStore,
	SearchStore,
	TableListStore,
	OrgTreeStore,
	RadioGroupStore,
	DialogStore,
	FormStore,
	ImportCommon,
} from '../public/valhalla/stores/index.js';
import { isEmpty } from "lodash";
import * as api from '../apis/vacationRemain.js';
const getLabel = WeaLocaleProvider.getLabel;

class VacationRemainStore {
	@observable authorityStore = new AuthorityStore(api.getHasRight);
	@observable topStore = new TopStore(api.getRightMenu, this);
	@observable searchStore = new SearchStore('', this);
	@observable tableListStore = new TableListStore(api.getSearchList, this);
	@observable orgTreeStore = new OrgTreeStore(this);
	@observable radioGroupStore = new RadioGroupStore(api.getSearchCondition, this);

	@observable detailDialogStore = new DialogStore(this);
	@observable detailDialogSearchStore = new SearchStore('', this);
	@observable detailDialogTableStore = new TableListStore(api.getDetailSearchList, this);

	@observable editDialogStore = new DialogStore(this);
	@observable formStore = new FormStore(api.getDetailBalanceForm, this);

	@observable importExcelStore = new ImportCommon();

	@observable pageLoading = false;

	//页面加载状态
	get topLoading () {
		const {
			loading
		} = this.tableListStore.tableStore;

		return loading;
	}

	//菜单、按钮是否禁用
	get rightMenuStates () {
		const {
			loading,
		} = this.tableListStore.tableStore;

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

	//组织树可以展开到部门节点
	get orgTreeConfig () {
		return {
			orgTreeMoreProps: {
				isLoadSubDepartment: true,
				isLoadAllSub : false,
				params:{
					rightStr: 'KQLeaveRulesEdit:Edit',
				}
			}
		}
	}

	//设置页面标题
	get topConfig () {
		return {
			title: getLabel('505619', "假期余额设置")
		}
	}

	//不显示高级搜索
	get pageSearchConfig () {
		return {
			searchMoreProps: {
				searchType: []
			}
		}
	}

	//明细弹框内，不显示高级搜索，同时标识search组件
	get detailDialogSearchConfig () {
		return {
			searchMark: 'detail',
			searchMoreProps: {
				searchType: []
			}
		}
	}

	//明细弹框的配置
	get detailDialogConfig () {
		return {
			title: getLabel(17463, '明细'),
			dialogMark: 'detail',
			style: {
				width: 800,
				height: 600
			},
		}
	}

	//编辑弹框的配置
	get editDialogConfig () {
		return {
			title: getLabel(93, '编辑'),
			dialogMark: 'edit',
			style: {
				height: 430
			}
		}
	}

	//自定义渲染表单
	get editDialogFormConfig () {
		return {
			isCustomRender: true
		}
	}

	//获取页签的id
	@computed get ruleId () {
		const {
			datas,
			selectedKey
		} = this.searchStore;

		return datas[parseInt(selectedKey)].id;
	}

	//明细弹框内的图标按钮
	@computed get detailSearchButtons () {
		const {
			selectedRowKeys
		} = this.detailDialogTableStore.tableStore;

		const disabled = (selectedRowKeys.length === 0);

		return (
			[<WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@i3lygf`}
				buttonType="del"
				type="primary"
				onClick={this.batchDel}
				disabled={disabled}
			/>]
		)
	}
	//编辑弹框的底部按钮
	@computed get editDialogButtons () {
		const {
			loading
		} = this.formStore;

		return [
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@jiemhg`} type='primary' disabled={loading} onClick={this.handleDetailFormSaveClick}>{getLabel(505564, '保存')}</Button>
		]
	}

	//VacationRemain组件Mount前执行的操作
	preMount = () => {
		this.topStore.setTopConfig(this.topConfig);
		this.searchStore.setSearchConfig(this.pageSearchConfig);
		this.orgTreeStore.setOrgTreeConfig(this.orgTreeConfig);
	}

	//初始化页面
	init = () => {
		this.authorityStore.fetchAuthority().then(() => {
			this.resetStoreDatas();

			this.fetchPageRightInfo();
		})
	}

	//重置store中的数据
	resetStoreDatas = () => {
		['id', 'type'].forEach(val => {
			this.orgTreeStore[val] = ''
		});
		this.resetBrowser();
	}

	//保存假期余额设置
	save = () => {
		if (!this.canFetchTableList()) {
			message.warning(getLabel('505621', "请指定年份！"));
			return;
		}

		if (!this.isComplte()) {
			message.warning(getLabel(30702, '必填信息不完整'));
			return;
		}

		if (!this.isDatasNormal()) {
			return;
		}

		const params = {
			datas: JSON.stringify(this.tableListStore.tableStore.datas),
			...this.getTableListParams()
		};

		api.saveBalanceOfLeave(params).then(datas => {
			const {
				sign
			} = datas;

			if (sign === '1') {
				message.success(datas.message);
				this.fetchTableList()
			} else {
				message.warning(datas.message);
			}
		});

	}

	//假期余额信息是否完整
	isComplte = () => {
		const {
			datas
		} = this.tableListStore.tableStore;

		return datas.every(data => {
			return Object.values(data).every(val => val !== undefined)
		})
	}

	//假期余额信息是否正常
	isDatasNormal = () => {
		const {
			datas
		} = this.tableListStore.tableStore;
		return datas.every((data, index) => {
			const {
				baseAmountspan,
				extraAmountspan,
				usedAmountspan,
				baseAmount2span,
				extraAmount2span,
				usedAmount2span,
				lastname,
			} = data;

			const result1 = parseFloat(baseAmountspan) + parseFloat(extraAmountspan) >= parseFloat(usedAmountspan);

			let result2 = true;

			if (baseAmount2span !== undefined) {
				result2 = parseFloat(baseAmount2span) + parseFloat(extraAmount2span) >= parseFloat(usedAmount2span);
			}

			if (!(result1 && result2)) {
				message.warning(`${getLabel(15323, '第')}${index + 1}${getLabel(27592, '行')},${lastname}${getLabel(529327, '已休年假-初始化(天)不能大于本年年假-初始化(天)+额外年假-初始化(天)')}`);
			}
			return result1 && result2;

		})
	}

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

		const {
			setTempletName,
			setImportDialogTitle,
			setImportType,
			setImportDialogVisible,
			setSourceStore,
			setFormAsyncParams,
		} = this.importExcelStore;

		setTempletName(getLabel('129833', '导入模板'));
		setImportDialogTitle(getLabel('505622', "员工假期余额导入"));
		setImportType('balanceOfLeave');
		setFormAsyncParams(this.getTableListParams());
		setImportDialogVisible(true);
		setSourceStore(this);
	}

	//导入excel完成后调用
	getSearchList = () => {
		this.fetchTableList();
	}

	//批处理
	batchEditing = () => {
		const msg = getLabel(505620, '批处理将会初始化假期余额信息，确定批处理？');

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

		this.tableListStore.showConfirm(msg).then(() => {
			const params = this.getTableListParams();

			this.pageLoading = true;

			api.batchProcessing(params).then(datas => {
				const {
					sign
				} = datas;

				if (sign === '1') {
					message.success(datas.message);
					this.fetchTableList();
				} else {
					message.warning(datas.message);
				}

				this.pageLoading = false;
			})
		})
	}

	//导出excel
	exportExcel = () => {
		this.tableListStore.exportExcel();
	}

	//处理接口返回的数据
	processRadioGroupConfig = (items) => {
		const browserConfig = items[1];

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

	}

	//姓名浏览按钮事件回调
	handleBrowserChange = (ids) => {
		const moreParams = {
			hrmResourceId: ids
		};

		this.radioGroupStore.setRadioGroupMoreParams(moreParams);

		this.canFetchTableList() && this.fetchTableList();

	}

	//切换年份触发的事件回调
	handleRadioGroupChange = () => {
		this.canFetchTableList() && this.fetchTableList();
	}

	//是否可以调用列表接口
	canFetchTableList = () => {
		const {
			radioGroupParams
		} = this.radioGroupStore, {
			searchYearSelect,
			searchYear
		} = radioGroupParams;

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

		return true;
	}

	//组织树事件回调
	handleOrgTreeNodeClick = () => {
		// this.searchStore.setSelectedKey('0');

		this.handleTabClick();
	}

	//页签事件回调
	handleTabClick = () => {
		this.resetBrowser();

		const {
			selectedKey,
			datas
		} = this.searchStore;

		if (!isEmpty(datas)) {
			this.topStore.fetchRightMenu({
				ruleId: datas[selectedKey].id
			});

			this.fetchRadioGroupAndTableInfo();
		}
	}

	//重置浏览按钮的参数
	resetBrowser = () => {
		this.radioGroupStore.setRadioGroupMoreParams({
			hrmResourceId: ''
		});
	}

	//获取rightLayout的数据
	fetchPageRightInfo = () => {
		this.fetchTabs().then(() => {
			const {
				selectedKey,
				datas
			} = this.searchStore;

			if (!isEmpty(datas)) {
				this.topStore.fetchRightMenu({
					ruleId: datas[selectedKey].id
				});

				this.fetchRadioGroupAndTableInfo()
			}
		})
	}

	//获取RadioGroup和Table的数据
	fetchRadioGroupAndTableInfo = () => {
		const {
			fetchRadioGroupConfig
		} = this.radioGroupStore;

		fetchRadioGroupConfig().then(() => {
			//这里不需要执行fetchTableList
		})
	}

	//获取页签数据
	fetchTabs = () => {
		return new Promise((resolve, reject) => {
			const {
				id,
				type
			} = this.orgTreeStore, {
				setDatas,
				setSelectedKey,
			} = this.searchStore;

			const params = {
				organizationType: type ? type : '0',
				organizationId: id,
			};

			api.getTabs(params).then(datas => {
				const {
					tab
				} = datas;

				setDatas(tab);
				if (!isEmpty(tab)) {
					setSelectedKey(tab[0].key);
				}

				resolve();
			})
		})
	}

	//获取列表信息
	fetchTableList = () => {
		const params = this.getTableListParams();

		this.tableListStore.fetchTableList(params);
	}

	//获取调用列表接口所需的参数
	getTableListParams = () => {
		const {
			radioGroupParams,
		} = this.radioGroupStore, {
			id,
			type
		} = this.orgTreeStore;

		const orgTreeParams = {
			organizationType: type ? type : '0',
			organizationId: id
		};

		const tabParams = {
			ruleId: this.ruleId
		};

		return Object.assign({}, orgTreeParams, radioGroupParams, tabParams);
	}

	//重新渲染列
	reRenderColumns = (columns) => {
		if (this.detailDialogStore.visible) {
			return columns;
		}

		const needReRenderCols = ['baseAmount', 'baseAmount2', 'usedAmount', 'usedAmount2', 'extraAmount', 'extraAmount2'];

		columns.map(column => {
			const {
				dataIndex
			} = column;

			if (needReRenderCols.includes(dataIndex)) {
				column.render = (text, record, index) => {
					return (
						<WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@ywvkdb@${dataIndex}`}
							defaultValue={record[`${dataIndex}span`]}
							min={0}
							precision={2}
							onChange={value => this.handleInputNumberChange(value, index, dataIndex)}
						/>
					)
				}
			};

			if (dataIndex === 'detailShow') {
				column.render = (text, record) => {
					const {
						randomFieldId: resourceId,
						detailShowspan
					} = record;

					return (
						<a onClick={() => this.handleDetailClick(resourceId)}>{detailShowspan}</a>
					)
				}
			}
		})
	}

	//列表数字框回调函数
	handleInputNumberChange = (value, rowIndex, dataIndex) => {
		const {
			tableStore
		} = this.tableListStore, {
			datas
		} = tableStore;

		datas.map((data, index) => {
			if (rowIndex === index) {
				Object.assign(data, {
					[`${dataIndex}span`]: value
				})
			}
		});
	}

	//点击【明细】触发的回调事件
	handleDetailClick = (id) => {
		const {
			setDialogConfig,
			openDialog,
		} = this.detailDialogStore;

		setDialogConfig(this.detailDialogConfig);

		this.detailDialogSearchStore.setSearchConfig(this.detailDialogSearchConfig);

		openDialog();

		//在当前对象中写入人员id
		this.resourceId = id;

		this.fetchDetailDialogTableList();
	}

	//获取弹框列表的信息
	fetchDetailDialogTableList = () => {
		const params = {
			...this.getTableListParams(),
			resourceId: this.resourceId
		};
		this.detailDialogTableStore.fetchTableList(params);
	}

	//点击【批量删除】触发的回调函数（明细弹框）
	batchDel = () => {
		const msg = getLabel(385625, '确定要删除选择的记录吗？');

		const {
			showConfirm,
			tableStore
		} = this.detailDialogTableStore;

		showConfirm(msg).then(() => {
			const params = {
				ids: tableStore.selectedRowKeys + ''
			};

			this.del(params);
		})
	}

	//点击【删除】触发的回调函数（明细弹框）
	singleDel = (id) => {
		const msg = getLabel(83877, '确定要删除吗？');

		const {
			showConfirm,
		} = this.detailDialogTableStore;

		showConfirm(msg).then(() => {
			const params = {
				ids: id
			};

			this.del(params);
		})
	}

	del = (params) => {
		api.deleteBalance(params).then(datas => {
			const {
				status
			} = datas;

			if (status === '1') {
				message.success(datas.message);
				this.fetchDetailDialogTableList()
			} else {
				message.warning(datas.message);
			}
		})
	}

	//列表功能的回调函数
	onOperatesClick = (record, rindex, operate) => {
		const {
			index
		} = operate, {
			randomFieldId: detailId
		} = record;

		switch (index) {
			case '0':
				this.doEdit(detailId);
				break;
			case '1':
				this.singleDel(detailId);
				break;
			case '2':
				this.detailDialogTableStore.showLog('3074', detailId);
				break;
		}

	}

	//编辑明细
	doEdit = (detailId) => {
		const {
			setDialogConfig,
			openDialog,
		} = this.editDialogStore;

		setDialogConfig(this.editDialogConfig);
		openDialog();

		this.detailId = detailId;

		this.getDetailBalanceForm();
	}

	//获取明细表单
	getDetailBalanceForm = () => {
		const {
			setFormConfig,
			fetchForm
		} = this.formStore;

		const params = {
			id: this.detailId
		};

		setFormConfig(this.editDialogFormConfig);

		fetchForm(params)
	}

	//保存明细表单
	handleDetailFormSaveClick = () => {
		const {
			form,
			validateForm
		} = this.formStore;

		validateForm(form).then(() => {
			const params = {
				...form.getFormParams(),
				id: this.detailId
			};

			api.editBalance(params).then(datas => {
				const {
					sign
				} = datas;

				if (sign === '1') {
					message.success(datas.message);
					this.editDialogStore.closeDialog();
					this.fetchDetailDialogTableList();
				} else {
					message.warning(datas.message);
				}
			})
		})
	}

	//关闭【明细】弹框
	closeDetailDialog = () => {
		this.fetchTableList();
	}

	log = () => {
		window.setLogViewProps({ logSmallType: 3074 });
	}

}

export const vacationRemainStore = new VacationRemainStore();
