import {
	action,
	computed,
	reaction,
	observable,
} from 'mobx';
import {
	WeaForm,
	WeaTableNew,
} from 'comsMobx';
import {
	WeaMoreButton,
	WeaLocaleProvider,
} from 'ecCom';
import {
	Button,
	message,
} from 'antd';
import {
	fetch,
	confirmation,
	getTopButtons,
	getDropMenuDatas,
	getSearchButtons,
	getMenusCreationConfig,
} from '../util/save-time-util.js';
import * as asyncFetch from '../apis/attendanceRpSharingSetting';
const getLabel = WeaLocaleProvider.getLabel;
const {
	TableStore
} = WeaTableNew;

class HrmAttendanceRpSharingSetting {
	//************权限*************
	@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;
			}
		});
	}

	//*************头部**************
	get topProps () {
		return {
			showDropIcon: true,
			iconBgcolor: '#217346',
			icon: <i className='icon-coms-hrm' />,
			title: getLabel('505545', "考勤报表共享设置"),
		}
	}

	@observable btnMenu = [];

	@computed get toploading () {
		return this.table.comsWeaTableStore.loading;
	}

	@computed get menusCreationConfig () {
		return getMenusCreationConfig(this.btnMenu);
	}

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

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

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

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

	@computed get menuState () {
		const {
			loading,
			selectedRowKeys
		} = this.table.comsWeaTableStore;

		const isChecked = (selectedRowKeys.length === 0);
		return [loading, isChecked];
	}

	@action getRightMenu = () => {
		fetch({
			asyncFetch,
			name: 'getRightMenu',
			logic: (cb) => {
				const {
					btnMenu,
				} = cb;

				this.btnMenu = btnMenu;
			}
		});
	}

	new = () => {
		this.openDialog();
	}

	batchDelete = () => {
		confirmation.showDelConfirm({
			type: 1,
			logic: (type) => this.deleteReportShare(type),
		})
	}

	log = (id, source) => {
		const params = {
			logSmallType: '3061',
		};
		if (source === 'table') {
			Object.assign(params, {
				targetId: id,
			});
		}
		window.setLogViewProps(params);
	}

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

		comsWeaTableStore.setColSetVisible(true);
		comsWeaTableStore.tableColSet(true)
	}

	//************页签*************
	tabProps = {
		searchType: ['base', 'advanced'],
		buttonsAd: getSearchButtons({
			form: this.search.form,
			search: () => this.handleSearch(),
			reset: () => this.search.form.resetConditionValue(),
			cancel: () => this.changePanelStatus(false)
		}),
		onSearch: () => this.handleSearch(),
		onSearchChange: (val) => this.handleSearchChange(val),
		setShowSearchAd: (bool) => this.changePanelStatus(bool),
		advanceHeight: 70,
		hasMask: false,
	}

	@observable search = {
		form: new WeaForm(),
		conditions: [],
	}

	@observable tab = {
		searchsBaseValue: '',
		showSearchAd: false,
	}

	@action handleSearch = () => {
		this.getSearchList();
		if (this.tab.showSearchAd) this.changePanelStatus(false);
	}

	@action changePanelStatus = (bool) => {
		this.tab.showSearchAd = bool;
	}

	@action handleSearchChange = (val) => {
		this.tab.searchsBaseValue = val;
	}

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

				this.search.conditions = condition;
				this.search.form.initFormFields(condition);
			}
		});
	}

	//************列表*************
	tableProps = {
		hasOrder: true,
		needScroll: true,
		onOperatesClick: (record, rowIndex, operate) => {
			const {
				randomFieldId
			} = record, {
				index
			} = operate;

			this.singleRowId = randomFieldId;

			if (index === '1') {
				confirmation.showDelConfirm({
					type: 0,
					logic: (type) => this.deleteReportShare(type)
				});
			}
		}
	}

	@observable table = {
		comsWeaTableStore: new TableStore()
	}

	@computed get tableAsyncFetchParams () {
		const {
			form
		} = this.search;

		const params = {
			resourceName: this.tab.searchsBaseValue,
		};

		if (form.isFormInit) {
			Object.assign(params, {
				...this.search.form.getFormParams()
			});
		} else {
			Object.assign(params, {
				reportName: 0
			});
		}

		return params;
	}

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

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

	deleteReportShare = (type) => {
		const {
			comsWeaTableStore
		} = this.table;

		const params = {
			ids: (type === 0) ? this.singleRowId : comsWeaTableStore.selectedRowKeys.toString()
		}

		fetch({
			asyncFetch,
			name: 'deleteReportShare',
			fetchParams: params,
			logic: (cb) => {
				const {
					sign
				} = cb;

				if (sign === '1') this.getSearchList();

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

	//**************弹框****************
	dialogProps = {
		icon: 'icon-coms-hrm',
		iconBgcolor: '#217346',
		hasScroll: true,
		title: getLabel('505546', "添加共享"),
		style: {
			width: 600,
			height: 340
		},
		onCancel: () => this.closeDialog(),
		buttons: [
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3hnuph`} type="primary" onClick={() => this.saveReportShare()}>{getLabel('505564', "保存")}</Button>,
			<WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@fdde13`} />
		]
	}

	@observable dialog = {
		visible: false,
	}

	@action openDialog = () => {
		this.dialog.visible = true;
	}

	@action closeDialog = () => {
		this.dialog.visible = false;
	}

	disposer = reaction(() => this.dialog.visible, visible => {
		if (visible) {
			this.getReportShareForm()
		} else {
			this.resetReportShareForm();
		}
	});


	//************表单*************
	formConfig = {
		dynamicFields: [{
			passiveKey: 'subcomId',
			activeKey: 'shareLevel',
			showValue: '0'
		}, {
			passiveKey: 'deptId',
			activeKey: 'shareLevel',
			showValue: '1'
		}, {
			passiveKey: 'userId',
			activeKey: 'shareLevel',
			showValue: '2'
		}, {
			passiveKey: 'jobtitleId',
			activeKey: 'shareLevel',
			showValue: '3'
		}, {
			passiveKey: 'resourceIds',
			activeKey: 'resourceType',
			showValue: '1'
		}, {
			passiveKey: 'resourceManagerIds',
			activeKey: 'resourceType',
			showValue: '7'
		}]
	}

	@observable formElements = {
		conditions: [],
		form: new WeaForm(),
		loading: false,
		date: new Date(),
	}

	@action getReportShareForm = () => {
		this.formElements.loading = true;

		fetch({
			asyncFetch,
			name: 'getReportShareForm',
			logic: (cb) => {
				const {
					condition
				} = cb;

				this.formElements.loading = false;
				this.formElements.conditions = condition
				this.formElements.form.initFormFields(condition)
			}
		});
	}

	@action resetReportShareForm = () => {
		this.formElements.conditions = [];
		this.formElements.form = new WeaForm();
	}

	saveReportShare = () => {
		const {
			form
		} = this.formElements;

		this.ignoreField();

		form.validateForm().then(f => {
			if (f.isValid) {
				this.formElements.loading = true;

				fetch({
					asyncFetch,
					name: 'saveReportShare',
					fetchParams: form.getFormParams(),
					logic: (cb) => {
						const {
							sign
						} = cb;

						if (sign === '1') {
							message.success(cb.message);
							['closeDialog', 'getSearchList'].map(func => {
								this[func]();
							});
						} else {
							message.warning(cb.message);
						}

						this.formElements.loading = false;
					}
				});
			} else {
				f.showErrors();
				this.formElements.date = new Date();
			}
		});
	}

	ignoreField = () => {
		window.e9HideFormFieldKeys = [];

		const {
			shareLevel,
			resourceType,
		} = this.formElements.form.getFormParams();

		const keys = ['subcomId', 'deptId', 'userId', 'jobtitleId'];

		keys.map((key, index) => {
			if (index !== parseInt(shareLevel)) {
				window.e9HideFormFieldKeys.push(key);
			}
		});

		resourceType === '1' && window.e9HideFormFieldKeys.push('resourceManagerIds');

		resourceType === '7' && window.e9HideFormFieldKeys.push('resourceIds');

		resourceType === '8' && window.e9HideFormFieldKeys.push('resourceManagerIds', 'resourceIds');

	}


	//************其他*************
	reset = () => {
		const {
			showSearchAd,
			searchsBaseValue
		} = this.tab, {
			form,
			conditions
		} = this.search;

		if (showSearchAd) {
			this.tab.showSearchAd = false;
		}

		if (searchsBaseValue) {
			this.tab.searchsBaseValue = '';
		}

		if (form.isFormInit) {
			this.search.form = new WeaForm();
			this.search.conditions = [];
		}

		this.table.comsWeaTableStore = new TableStore();

	}

	refresh = () => {
		this.reset();
		['getSearchCondition', 'getSearchList'].map(func => {
			this[func]();
		});
	}
}

const hrmAttendanceRpSharingSetting = new HrmAttendanceRpSharingSetting();

export {
	hrmAttendanceRpSharingSetting
}