import {
	observable,
	action,
	computed,
	reaction,
} from 'mobx';
import {
	WeaTableNew,
} from 'comsMobx';
import {
	WeaMoreButton,
	WeaPopoverHrm,
	WeaLocaleProvider,
} from 'ecCom';
import {
	message,
} from 'antd';
import {
	fetch,
	getTopButtons,
	getDropMenuDatas,
	getMenusCreationConfig,
	componentReset,
	exportExcel,
} from '../util/save-time-util.js';
import {
	jumpToHrmSubCompany,
	jumpToHrmDept,
	jumpToHrmPost,
} from '../util/pure-util.js';
import CheckboxGroup from '../components/vacationBalanceReportCopy/CheckboxGroup';
import * as asyncFetch from '../apis/vacationBalanceReport';
import{addContentPath}from '../util/index.js';
const getLabel = WeaLocaleProvider.getLabel;
const {
	TableStore
} = WeaTableNew;

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

	//*************头部**************
	topComponentStaticProps = {
		icon: <i className='icon-coms-hrm'/>,
		iconBgcolor: '#217346',
		showDropIcon: true,
	};

	@observable isNoAccountShow = false;

	@observable top = {
		btnMenu: [],
	}

	excel = () => {
		if (this.table.datas.length === 0) {
			message.warning(getLabel('503890', '暂无数据导出'));
			return
		}

		const downloadUrl = addContentPath('/api/kq/balanceofleaverp/exportExcel');

		const params = {
			...this.tableAsyncFetchParams,
			displayColumn: this.checkedItems.toString()
		};

		exportExcel(params, downloadUrl);
	}

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

	@action clickIcon = (next) => {
		this.isNoAccountShow = !this.isNoAccountShow;

		next && next();
	}

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

				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 {
			loading
		} = this.table;

		return [loading];
	}

	//***************单选组合（RadioGroup）*****************
	@observable checkedItems = [];
	@observable checkboxConfig = [];

	@observable radioGroup = {
		config: [],
		activeParams: '',
		height: 189,
	}

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

				this.checkboxConfig = option;

				this.checkedItems = value.split(',');

				if (this.isAllVacationChecked) {
					this.checkedItems.push('all')
				}

				this.processCondition(condition);

				this.radioGroup.config = condition[0].items;

				next && next();
			}
		});
	}

	processCondition = (condition) => {
		const com = <CheckboxGroup ecId={`${this && this.props && this.props.ecId || ''}_CheckboxGroup@ekimrr`} />;

		const item = {
			com,
			label: getLabel('390081', "展示列"),
			labelcol: 4,
			fieldcol: 20,
		}

		condition[0].items.unshift(item);
	}

	//收集选中假期的key值
	@action collectCheckedItem = (val, key) => {
		const keys = this.checkedItems;

		const add = (key) => {
			keys.push(key);
		};

		const del = (key) => {
			const targetIndex = keys.findIndex(_key => _key === key);
			if (targetIndex > -1) keys.splice(targetIndex, 1);
		};

		(val === '1') ? add(key): del(key);

		this.checkedItems = keys;

		this.handleCkClick(val, key);
	}

	//checkbox框的回调函数
	handleCkClick = (val, key) => {
		if (key === 'all') {
			if (val === '1') {
				this.allVacationKeys.map(key => {
					if (!this.checkedItems.includes(key)) this.checkedItems.push(key);
				});
			} else {
				this.allVacationKeys.map(key => {
					const targetIndex = this.checkedItems.findIndex(item => item === key);
					if (targetIndex > -1) this.checkedItems.splice(targetIndex, 1);
				});
			}
		}

		if (key !== 'all' && !['subcom', 'dept', 'jobtitle','workcode'].includes(key)) {
			if (val === '0') {
				const targetIndex = this.checkedItems.findIndex(item => item === 'all');
				if (targetIndex > -1) this.checkedItems.splice(targetIndex, 1);
			} else {
				if (this.isAllVacationChecked) this.checkedItems.push('all');
			}
		}
	}

	//判断所有的假期是否都选中
	@computed get isAllVacationChecked() {
		for (let i = 0; i < this.allVacationKeys.length; i++) {
			const key = this.allVacationKeys[i];

			if (!this.checkedItems.includes(key)) {
				return false;
			}
		}
		return true;
	}

	//收集所有假期的key值
	@computed get allVacationKeys() {
		const items = this.checkboxConfig.length > 0 ? this.checkboxConfig[1] : this.checkboxConfig;

		const collector = [];

		items.map(item => {
			const key = item.key;
			if (key === 'all') return
			collector.push(key);
		});

		return collector;
	}

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

	@action exportActiveParams = (params) => {
		this.isNoAccountShow = ((['4', '5', '6', '7', '9'].indexOf(params.status || '')) > -1);
		this.radioGroup.activeParams = params;

		this.chainCall();
	}

	@computed get isEmpty() {
		const {
			activeParams
		} = this.radioGroup, {
			dateScope,
			selectedYear,
			dataScope,
			subcomId,
			deptId,
			resourceId,
		} = activeParams;

		//指定日期范围未填写
		if (dateScope === '6' && !selectedYear) {
			return true;
		}
		//分部未填写
		if (dataScope === '1' && !subcomId) {
			return true;
		}
		//部门未填写
		if (dataScope === '2' && !deptId) {
			return true;
		}
		//人员未填写
		if (dataScope === '3' && !resourceId) {
			return true;
		}

		return false
	}

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

		const callback = {
			...activeParams,
		};

		return callback;
	}

	@computed get columns() {
		const afterColumns = this.table.columns.filter(column => column.key === 'lastName' || this.checkedItems.includes(column.key));

		afterColumns.map(column => {
			const dataIndex = column.dataIndex;
			column.render = (text, record, index) => {
				const {
					id,
					deptId,
					jobtitleId,
					subcomId,
					lastName,
					workcode,
				} = record;

				switch (dataIndex) {
					case 'lastName':
						return (<div>
    						<WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@l13jxm@${column.dataIndex}`} />
    						<a href={`javaScript:openhrm(${id})`} onClick={e => window.pointerXY(e)} title={lastName} ><span dangerouslySetInnerHTML={{__html:lastName}} /></a>
  						</div>);
						break;
					case 'workcode':
						return (<div>
    						<WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@442v8m@${column.dataIndex}`} />
    						<a href={`javaScript:openhrm(${id})`} onClick={e => window.pointerXY(e)} title={workcode} >	
    							{workcode}
    						</a>
  						</div>);
						break;
					case 'subcom':
						return <a onClick={() => jumpToHrmSubCompany(subcomId)} target='_blank'>{text}</a>
						break;
					case 'dept':
						return <a onClick={() => jumpToHrmDept(deptId)} target='_blank'>{text}</a>;
						break;
					case 'jobtitle':
						return <a onClick={() => jumpToHrmPost(jobtitleId)} target='_blank'>{text}</a>;
						break;
					default:
						if (text === '-1') {
							return '/'
						} else {
							return <a onClick={() => this.handleHrefClick({id,lastName,key:dataIndex})}>{text}</a>
						}

				}
			}
		});

		return afterColumns;
	}

	handleHrefClick = (params) => {
		const {
			id,
			lastName,
			key
		} = params;


		this.dialogTitle = `${lastName} ${getLabel('505716',"的")}${getLabel('505717',"假期使用记录")}`

		this.resourceId = id;

		this.dialogTab.selectedKey = key;

		this.openDialog();
	}

	@action setRgHeight = (height) => {
		this.radioGroup.height = height !== null ? height : 180;
	}

	//***************列表*****************
	@observable resourceId = '';

	@observable table = {
		columns: [],
		datas: [],
		pageSize: 10,
		total: 0,
		loading: false,
		current: 1,
	}

	showTotal = (total) => {
		return `${getLabel('18609',"共")} ${total} ${getLabel('18256',"条")}`;
	}

	@observable winHeight = (window.innerHeight || document.documentElement.clientHeight);

	@action calculateHeight = () => {
		this.winHeight = (window.innerHeight || document.documentElement.clientHeight);
	}

	@computed get paginationCallbackParamsCollector() {
		const {
			current,
			pageSize
		} = this.table;

		const callback = {
			pageSize,
			currentPage: current,
		};

		return callback;
	}

	@computed get tableAsyncFetchParams() {
		const params = {
			...this.paginationAsyncFetchParams,
			...this.paginationCallbackParamsCollector,
		};

		return params;
	}

	@observable loading = false;

	@action getSearchList = () => {
		if (this.isEmpty) return;
		this.loading = true;
		fetch({
			asyncFetch,
			name: 'getSearchList',
			fetchParams: this.tableAsyncFetchParams,
			logic: (cb) => {
				const {
					columns,
					datas
				} = cb;

				const _columns = [...columns];

				_columns.forEach(c => {
					c.width = 100
				})

				this.table.columns = _columns;
				this.table.datas = datas;
				this.loading = false;
			}
		});
	}

	@computed get paginationAsyncFetchParams() {
		const params = {
			...this.rgCallbackParamsCollector,
			isNoAccount: this.isNoAccountShow,
		}

		return params;
	}

	@action getPageInfo = (next) => {
		if (this.isEmpty) return;

		fetch({
			asyncFetch,
			name: 'getPageInfo',
			fetchParams: this.paginationAsyncFetchParams,
			logic: (cb) => {
				['pageSize', 'total'].map(v => {
					this.table[v] = cb[v];
				});

				this.table.current = 1;

				next && next();
			}
		});
	}

	@action setCurrentPage = (current, property, next) => {
		this[property].current = current;

		next && next();
	}

	@action setSizePerPage = (pageSize, property, next,current) => {
		this[property].pageSize = pageSize;
		this[property].current = current;

		next && next();
	}

	@computed get tableScrollHeight() {
		return this.winHeight - 340
	}

	//***************弹框*****************
	dialogProps = {
		icon: 'icon-coms-hrm',
		iconBgcolor: '#217346',
		hasScroll: true,
		style: {
			width: 700,
			height: 650,
		},
		onCancel: () => this.closeDialog(),
		buttons: [<WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@7ei8ph`} />],
	};

	@observable dialog = {
		visible: false,
		loading: true,
		bottomTips: '',
	}

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

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

	dialogSelectDisposer = reaction(() => this.dialog.visible, visible => {
		if (visible) {
			this.getChangeType();
			this.dialogChainCall();
		} else {
			this.dialogSelect.value = 'All'
		}
	})

	//***************弹框内的页签*****************
	dialogTabStaticProps = {
		keyParam: 'key',
		onChange: key => this.setDialogTabKey(key, this.dialogPartChainCall),
	}

	@observable dialogTab = {
		datas: [],
		selectedKey: '',
	}

	@action setDialogTabKey = (key, next) => {
		this.dialogTab.selectedKey = key;
		next && next();
	}

	@computed get dialogTabAsyncFetchParams() {
		const params = {
			resourceId: this.resourceId,
		}

		return params;
	}

	@action getDialogTab = (next) => {
		fetch({
			asyncFetch,
			name: 'getTab',
			fetchParams: this.dialogTabAsyncFetchParams,
			logic: (cb) => {
				const {
					tab
				} = cb;

				this.dialogTab.datas = tab;

				next && next();
			}
		});
	}

	@computed get vacationName() {
		const {
			datas,
			selectedKey
		} = this.dialogTab;

		const targetData = datas.find(data => data.key === selectedKey);

		if (targetData) return targetData.title
	}

	//***************弹框内的下拉框*****************
	@observable dialogSelect = {
		options: [],
		value: 'All',
	};

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

				this.dialogSelect.options = condition[0].items[0].options;
			}
		});
	}

	@action handleSelectChange = (value, next) => {
		this.dialogSelect.value = value;

		next && next();
	}

	//***************弹框内的分页*****************
	@observable dialogPagination = {
		current: 1,
		pageSize: 10,
		total: 0
	};

	@computed get dialogPaginationAsyncFetchParams() {
		const params = {
			ruleId: this.dialogTab.selectedKey,
			changeType: this.dialogSelect.value,
			resourceId: this.resourceId,
		};

		return params;
	}

	@action getDetailPageInfo = (next) => {
		this.dialog.loading = true;

		fetch({
			asyncFetch,
			name: 'getDetailPageInfo',
			fetchParams: this.dialogPaginationAsyncFetchParams,
			logic: (cb) => {
				['total', 'pageSize'].map(v => {
					this.dialogPagination[v] = cb[v];
				});

				if (cb.total === 0) {
					this.dialog.loading = false
				}

				this.dialogPagination.current = 1;

				next && next();
			}
		});
	}

	//***************弹框内的时间线*****************
	@observable dialogTimeline = {
		dataDetail: [],
		topTips: '',
		balanceEnable: 1,
	}

	@computed get timelineAsyncFetchParams() {
		const {
			current,
			pageSize
		} = this.dialogPagination;

		const params = {
			...this.dialogPaginationAsyncFetchParams,
			pageSize,
			currentPage: current,
		}

		return params;
	}

	@action getUsageRecordDetail = () => {
		fetch({
			asyncFetch,
			name: 'getUsageRecordDetail',
			fetchParams: this.timelineAsyncFetchParams,
			logic: (cb) => {
				['dataDetail', 'topTips', 'balanceEnable'].map(v => {
					this.dialogTimeline[v] = cb[v];
				});

				this.dialog.bottomTips = cb.bottomTips;

				this.dialog.loading = false;
			}
		});
	}

	//***************其他*****************
	cwm = () => {
		this.resetDatas();
	}

	cwr = () => {
		this.resetDatas();
		this.getRadioGroupConfig(this.chainCall);
	}

	resetDatas = () => {
		this.isNoAccountShow = false;
		this.radioGroup.config = [];
		['columns', 'datas'].map(v => {
			this.table[v] = [];
		});
	}

	chainCall = () => this.getPageInfo(() => this.getSearchList());

	dialogPartChainCall = () => this.getDetailPageInfo(() => this.getUsageRecordDetail())

	dialogChainCall = () => this.getDialogTab(this.dialogPartChainCall);


}

const hrmVacationBalanceReportCopy = new HrmVacationBalanceReportCopy;
export {
	hrmVacationBalanceReportCopy
}