import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaForm,
	WeaTableNew,
} from 'comsMobx';
import {
	WeaLocaleProvider,
} from 'ecCom';
import {
	Button,
	message,
} from 'antd';
import {
	toJS
} from 'mobx';
import {
	fetch,
	getMenusCreationConfig,
	getTopButtons,
	getDropMenuDatas,
	confirmation,
} from '../util/save-time-util.js';
import OvertimeRuleFormStore from './overtimeRuleForm'
import * as asyncFetch from '../apis/overtimeRule';
import * as timeSelectionApi from '../apis/timeSelection.js';
const getLabel = WeaLocaleProvider.getLabel;
const {
	TableStore
} = WeaTableNew;

class HrmOvertimeRule {
	//************权限*************
	@observable pageAccessPermission = {
		hasRight: false,
		loading: true,
	}
	//获取页面权限
	getPermissionInfo = () => {
		fetch({
			asyncFetch,
			name: 'getHasRight',
			logic: (cb) => {
				const {
					hasRight
				} = cb;

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

	//*************头部**************
	get topComponentStaticProps() {
		return {
			title: getLabel('505606', "加班规则"),
			icon: <i className='icon-coms-hrm'/>,
			iconBgcolor: '#217346',
			showDropIcon: true
		}
	}

	@observable top = {
		btnMenu: [],
	}

	//获取按钮、下拉菜单和右键菜单的复合值
	getMenus = () => {
		fetch({
			asyncFetch,
			name: 'getMenus',
			fetchParams: {
				tabKey: this.tab.selectedKey
			},
			logic: (cb) => {
				const {
					btnMenu
				} = cb;

				this.top.btnMenu = btnMenu;
			}
		});
	}

	//根据btnMenu，计算出topMenu和rightMenu
	@computed get menusCreationConfig() {
		const {
			btnMenu
		} = this.top;

		return getMenusCreationConfig(btnMenu);
	}

	//Top组件的按钮
	get topButtons() {
		const {
			topMenu
		} = this.menusCreationConfig;

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

	//保存选中的加班规则
	save = () => {
		const {
			selectedKey
		} = this.tab;

		let name, fetchParams;

		if (selectedKey === '0') {
			name = 'saveDefault';
			fetchParams = {
				ruleId: this.table.checkedRowId
			}
			callAPI();
		} else {
			name = 'saveOvertimeUnit';
			const {form} = this.formElements;

			fetchParams = {
				...form.getFormParams()
			}

			form.validateForm().then(f => {
				if (f.isValid) {
					callAPI()
				} else {
					f.showErrors();
					//强制刷新表单
					this.forceUpdateForm();
				}
			})
		}

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

				message[sign === '1' ? 'success' : 'warning'](cb.message);
			}
		});
	}
	//新建
	new = () => {
		this.openDialog({
			title: getLabel('505607', "新建加班规则"),
			type: 0, //0：代表新建
		});
	}

	//批量删除
	batchDelete = () => {
		confirmation.showDelConfirm({
			type: 1,
			logic: (type) => this.delOverTimeRule(type),
		});
	}

	//显示定制列
	custom = () => {
		const {
			tableStore
		} = this.table;

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

	}

	log = (id, source) => {
		const params = {
			logSmallType: (this.tab.selectedKey === '0') ? '3057' : '3058',
		};
		if (source === 'table') {
			Object.assign(params, {
				targetId: id,
			});
		}
		window.setLogViewProps(params);
	}

	//获取右键菜单和top组件下拉菜单的数据
	get dropMenuDatas() {
		const {
			rightMenu
		} = this.menusCreationConfig;

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

	//获取菜单元素的状态值
	getMenusState = () => {
		const {
			tableStore
		} = this.table, {
			loading,
			selectedRowKeys
		} = tableStore;

		const {
			selectedKey
		} = this.tab;

		if (selectedKey === '0') {
			return [loading, selectedRowKeys.length === 0, loading, loading];
		} else {
			return [this.formElements.loading];
		}
	}

	@observable showSearchAd = false;

	//***************标签页*****************
	get tabStaticProps() {
		return {
			datas: [{
				key: '0',
				title: getLabel('505606', "加班规则")
			}, {
				key: '1',
				title: getLabel('505608', "加班计算单位")
			}],
			keyParam: 'key',
			onChange: (key) => this.setSelectedKey(key),
			searchType:["base", "advanced"],
			showSearchAd:this.showSearchAd,
			setShowSearchAd: (bool) => this.showSearchAd = bool,
			advanceHeight: 200,
			searchsAd:this.getSearchs(),
			onAdSearch:()=> {
				this.getSearchList();
				this.searchsAd = false;
			},
			onSearch: (v)=> this.getSearchList({name:v}),
			onAdReset: () => {
				this.conditionForm.updateFields({name:'',groupIds:[],shift:[]});
			  },
			  onAdCancel: () => {
				this.searchsAd = false;
			  }
		}
	}

	getSearchs = () => {
		return <div
		onKeyDown={(e) =>{
		   if (e.keyCode == 13 && e.target.tagName === "INPUT") {
			this.getSearchList();
			this.showSearchAd = false;
		   } 
		}}
	>{this.renderForm()}</div>
	}


	renderForm = () => {
        const {
            isFormInit
        } = this.conditionForm;
        if (isFormInit)
            return this.conditionForm.render();
        else
            return '';
    }

	@observable tab = {
		selectedKey: '0'
	}

	@action setSelectedKey = (key) => {
		this.tab.selectedKey = key;

		this.getMenus();

		if (key === '0') {
			this.resetForm();
		} else {
			this.getFormMaterial();
		}
	}

	resetTab = () => {
		this.setSelectedKey('0')
	}

	//***************列表*****************
	@observable table = {
		id: '',
		checkedRowId: '',
		tableStore: new TableStore(),
	}

	//获取列表数据
	getSearchList = (data = {}) => {
		fetch({
			asyncFetch,
			name: 'getSearchList',
			fetchParams: {
				...this.conditionForm.getFormParams(),
				...data
			},
			logic: (cb) => {
				const {
					sessionkey
				} = cb;

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

	//删除加班规则
	delOverTimeRule = (type) => {
		const {
			id,
			tableStore
		} = this.table;

		fetch({
			asyncFetch,
			name: 'deleteOvertimeRules',
			fetchParams: {
				ruleIds: (type === 1) ? tableStore.selectedRowKeys.toString() : id, //type等于0 -> 单个删除; type等于1 -> 批量删除
			},
			logic: (cb) => {
				const {
					sign
				} = cb;

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

	//设置当前点击行的ID
	@action setSelectedRowId = (id) => {
		this.table.id = id;
	}

	//设置加班规则选中行的id
	@action setCheckedRowId = (id) => {
		['id', 'checkedRowId'].map(v => {
			this.table[v] = id;
		});
	}

	@action resetTable = () => {
		this.table.tableStore = new TableStore();
	}

	//**************弹框****************
	//弹框组件的常量参数
	dialogStaticProps = {
		icon: 'icon-coms-hrm',
		iconBgcolor: '#217346',
		hasScroll: true,
	}

	@observable dialog = {
		title: '',
		visible: false,
		type: 0,
	}

	//弹框的样式
	get style() {
		return {
			width: 900,
			height: 600
		}
	}

	//保存节假日设置信息
	saveOverTimeRules = () => {
		const {
			form
		} = this.formElements, {
			id
		} = this.table, {
			type
		} = this.dialog;

		const fetchParams = form.getFormParams();

		//type等于1代表：编辑加班规则
		(type === 1) && Object.assign(fetchParams, {
			ruleId: id
		});

		Object.assign(fetchParams, this.getRestTimeParams());

		//忽略校验隐藏的必填字段
		this.neglectHiddenField();

		//校验休息时间
		if (!this.verifyRestTime()) return

		form.validateForm().then(f => {
			if (f.isValid) {
				this.canOperateForm(false);

				fetch({
					asyncFetch,
					name: (type === 0) ? 'addOvertimeRules' : 'editOvertimeRules',
					fetchParams,
					logic: (cb) => {
						const {
							sign
						} = cb;

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

					}
				});
			} else {
				f.showErrors();
				//强制刷新表单
				this.forceUpdateForm();
			}
		});
	}

	@action canOperateForm = (bool) => {
		this.formElements.loading = !bool;
	}

	getRestTimeParams = () => {
		const params = {};

		const {
			rstTimes,
			vacationTimes
		} = this.restTime;

		const decorate = (datas, mark) => {
			datas.map((time, index) => {
				Object.keys(time).map(key => {
					Object.assign(params, {
						[`${key}${mark}_${index}`]: time[key]
					});
				});
			});
		}

		[rstTimes, vacationTimes].map((times, index) => {
			const mark = (index === 0) ? 3 : 1;
			decorate(times, mark)
		});

		Object.assign(params, {
			restTimeLen3: rstTimes.length,
			restTimeLen1: vacationTimes.length,
		});
		return params;
	}

	//校验休息时间
	verifyRestTime = () => {
		const {
			hasRestTime3,
			hasRestTime1
		} = this.formElements.form.getFormParams(), {
			rstTimes,
			vacationTimes,
		} = this.restTime;

		//必填项是否完整
		const isComplete = (datas) => {
			for (let i = 0; i < datas.length; i++) {
				const {
					startTime,
					endTime
				} = datas[i];

				if (!startTime || !endTime) {
					message.warning(getLabel('505609', "休息时间区间不完整！"));
					return false
				}

			}
			return true
		}


		//判断time是否符合规范
		const isRightTime = (data, index) => {
			const {
				startTime,
				endTime,
			} = data;

			const start = startTime.split(':').map(v => parseInt(v)),
				end = endTime.split(':').map(v => parseInt(v));

			if ((start[0] > end[0]) || (start[0] === end[0] && start[1] > end[1])) {
				message.warning(`${getLabel('505610', "开始时间不能大于结束时间！")}`);
				return false
			}
			return true;
		}

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

				if (!isRightTime(data)) return false
			}
			return true;
		}

		//校验【休息日加班】休息时间
		if (hasRestTime3 === '1') {
			if (!isComplete(rstTimes) || !isStickToRule(rstTimes)) return false;
		}

		//校验【节假日加班】休息时间
		if (hasRestTime1 === '1') {
			if (!isComplete(vacationTimes) || !isStickToRule(vacationTimes)) return false;
		}

		return true;
	}
	//忽略校验隐藏的必填字段
	neglectHiddenField = () => {
		//重置e9HideFormFieldKeys容器
		window.e9HideFormFieldKeys = [];

		const {
			form
		} = this.formElements;

		[2, 3, 1].map(v => {
			if (form.getFormParams()[`paidLeaveEnable${v}`] === '0') {
				['lenOfOvertime', 'lenOfLeave'].map(key => {
					window.e9HideFormFieldKeys.push(`${key}${v}`);
				});
			}
		});

	}

	@action forceUpdateForm = () => {
		this.formElements.date = new Date();
	}

	@action openDialog = (params) => {
		const {
			title,
			type,
		} = params;

		['title', 'type', 'visible'].map((v, i) => {
			this.dialog[v] = (i < 2) ? params[v] : true;
		});
		//调用“节假日设置”表单接口
		// this.getFormMaterial();
	}

	@action closeDialog = () => {
		//设置弹框隐藏
		this.dialog.visible = false;
		//重置表单数据
		this.resetForm();
		//重置休息时间表单元素
		['rstTimes', 'vacationTimes'].map(type => {
			this.resetRestTime(type);
		})
	}

	//**************表单****************
	get conversionTip(){
		return (
			<p style={{float: 'right', paddingTop: 5}}>
				<span>{`${getLabel('391',"小时")}=1${getLabel('505553',"天")}`}</span>
				<span style={{marginLeft: 10,color:'#999'}}>{`${getLabel('505611',"请假、出差、外出、加班的日折算时长会同时生效")}`}</span>
			</p>
		);
	} 

	get formConfig (){
		return {
			staticTips: {
				weekdayHoursToDay: this.conversionTip,
				weekendHoursToDay: this.conversionTip,
			},
			classNames: {
				weekdayHoursToDay: 'hrm-travel-rule-form-input',
				weekendHoursToDay: 'hrm-travel-rule-form-input',
				hoursToday: 'hrm-holiday-rule-form-input',
				timeselection: 'hrm-travel-timeselection',
			},
			staticTips: {
				hoursToday: (
					<span style={{marginLeft:15}}>{`${getLabel('391',"小时")}=1${getLabel('505553',"天")}`}</span>
				)
			},
			dynamicFields: [{
				passiveKey: 'timeselection', //时间选择方式
				activeKey: 'minimumUnit',
				showValue: '2',
			},{
				passiveKey: 'overtimeConversion', //加班时长折算方式
				activeKey: 'minimumUnit',
				showValue: '5,6',
			}]
		}
	}

	@observable formElements = {
		conditions: [],
		form: new WeaForm(),
		loading: true,
		date: new Date(), //用来刷新form组件
		minimumUnit: [],
		hasTXrules: false,
	}

	@observable overtimeConversion5 = []
	@observable overtimeConversion6 = []

	//获取表单元素提示信息
	@computed get dynamicTips() {
	    const { form } = this.formElements
	    const { minimumUnit } = form.getFormParams()
	    const overtimeConversion = this[`overtimeConversion${minimumUnit}`],
	        tips = { minimumUnit: this.formElements.minimumUnit }
	    if (overtimeConversion) {
	        return Object.assign({}, tips, { overtimeConversion })
	    }
	    return tips
	}

	//获取“节假日设置”表单数据
	getFormMaterial = () => {
		const {
			id
		} = this.table, {
			type
		} = this.dialog, {
			selectedKey
		} = this.tab;

		let name, fetchParams;
		if (selectedKey === '0') {
			name = 'getOvertimeRulesForm';
			fetchParams = (type === 1) && {
				ruleId: id
			}
		} else {
			name = 'getOvertimeUnitForm'
		}

		fetch({
			asyncFetch,
			name,
			fetchParams,
			logic: (cb) => {
				const {
					condition,
					minimumUnit,
					restTime3,
					restTime1,
					hasTXrules,
				} = cb;

				this.formElements.hasTXrules = hasTXrules;

				this.handleCondition(condition);

				['loading', 'conditions', 'form'].map((v, i) => {
					if (i < 2) {
						this.formElements[v] = (i === 0) ? false : condition
					} else {
						this.formElements[v].initFormFields(condition);
					}
				});

				if (minimumUnit) this.formElements.minimumUnit = minimumUnit;

				if (restTime3) this.restTime.rstTimes = restTime3;

				if (restTime1) this.restTime.vacationTimes = restTime1;

				if (typeof cb == 'object') {
					Object.keys(cb).forEach(key => this[key] = cb[key])
				}

			}
		});
	}

	//处理condition
	handleCondition = (condition) => {
		condition.map(c => {
			c.items.map(item => {
				const {
					domkey
				} = item;

				const key = domkey[0];
				if (['paidLeaveEnable2', 'paidLeaveEnable3', 'paidLeaveEnable1'].includes(key)) {
					item.content = (
						<span>
							<span>{`${getLabel('505612',"转为调休余额")}`}</span>
							{
								!this.formElements.hasTXrules && (
									<span>
										{ `( ${getLabel('505613',"调休余额规则未设置")} ,`}
										<a onClick={this.handleHrefClick}>{getLabel('505614',"去设置")}</a>
										{` )`}
									</span>
								)
							}
						</span>
					)
				}
			});
		});
	}

	//【去设置】链接的回调函数
	handleHrefClick = (e) => {
		e.preventDefault();
		window.open(`/spa/hrm/staticAttendance4engine/engine.html#/attendance/holidayRule`);
	}

	//重置表单
	@action resetForm = () => {
		['loading', 'conditions', 'form'].map((v, i) => {
			this.formElements[v] = (i === 0) ? true : (i === 1) ? [] : new WeaForm();
		});
	}

	@action handleFormElementsChange = () => {
		this.formElements.date = new Date();
	}

	//*************自定义组件-休息时间**************
	@observable restTime = {
		rstTimes: [{
			startTime: '',
			endTime: '',
		}],
		vacationTimes: [{
			startTime: '',
			endTime: '',
		}]
	}

	@action handleTimePickerChange = (value, rowIndex, colIndex, type) => {
		const rowData = this.restTime[type][rowIndex];
		rowData[colIndex === 0 ? 'startTime' : 'endTime'] = value;
	}

	@action addRestTime = (type) => {
		this.restTime[type].push({
			startTime: '',
			endTime: '',
		});
	}

	@action delRestTime = (rowIndex, type) => {
		this.restTime[type].splice(rowIndex, 1);
	}

	@action resetRestTime = (type) => {
		this.restTime[type] = [{
			startTime: '',
			endTime: '',
		}];
	}

	//*************OvertimeRule**************
	//重置页面
	refreshPage = async () => {
		this.resetTab();
		await this.getOvertimeSearchCondition();
		this.getSearchList();
	}

	@observable conditionForm = new WeaForm();

	getOvertimeSearchCondition = async () => {
		await asyncFetch.getOvertimeSearchCondition().then(cb => {
			const {
				api_status,
				status,
				conditions,
			} = cb;
	
			if (api_status) {
				this.conditionForm.setCondition(conditions);
			} else {
				message.error();
			}
		})
	}

	/** 选项名称定义 */
	@observable timeSelectionDialogVisible = false;
	@computed get timeSelectionDialog(){
		return {
			key: new Date().getTime(),
			...ecCom.WeaTools.getIconBGC('hrm'),
			style: {
				height: 200
			},
			title: getLabel('513303','选项名称定义'),
			hasScroll: true,
			visible: this.timeSelectionDialogVisible,
			buttons: [
				<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@wywuzo`} type="primary" onClick={() => this.saveDefForm()}>{getLabel(30986, '保存')}</Button>,
			],
			moreBtn: {
				datas: [
				  {
					key: "1",
					icon: <i className="icon-coms-Preservation" />,
					content: getLabel(30986, '保存'),
					onClick: () => this.saveDefForm()
				  },
				]
			},
			onCancel: () => {
				this.timeSelectionDialogVisible = false;
			}
		}
	}

	@action getDefForm = (selectiontype) => {
		this.selectiontype = selectiontype;
		const {form} = this.formElements;
		const {minimumUnit} = form.getFormParams();
		const params = {selectiontype, minimumUnit};
		timeSelectionApi.getTimeSelectionForm(params).then(data => {
			if(data.status == '1'){
				const {condition: fields} = data;
				this.formTarget = {
					fields,
					form: new WeaForm()
				};
				this.formTarget.form.initFormFields(fields);
				this.timeSelectionDialogVisible = true;
			}else{
				message.error(data.message);
			}
		})
	}

	@action saveDefForm = () => {
		const {form} = this.formElements;
		const {minimumUnit} = form.getFormParams();
		const params = {selectiontype: this.selectiontype, minimumUnit};

		const formData = this.formTarget.form.getFormParams();
		Object.assign(params, {...formData});

		timeSelectionApi.saveTimeSelectionForm(params).then(data => {
			if(data.status == '1'){
				this.timeSelectionDialogVisible = false;
			}else{
				message.error(data.message);
			}
		})
	}


	@observable overtimeRuleFormStore = new OvertimeRuleFormStore({ ...this, api: { ...asyncFetch, ...timeSelectionApi } })


}

const hrmOvertimeRule = new HrmOvertimeRule();

export {
	hrmOvertimeRule
}