import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaCheckbox,
	WeaHelpfulTip,
	WeaInputNumber,
	WeaLocaleProvider,
} from 'ecCom';
import {
	WeaSwitch,
	WeaForm
} from 'comsMobx';
import {
	Button,
	message,
} from 'antd';
import {
	AuthorityStore,
	TopStore,
	SearchStore,
	TableListStore,
	DialogStore,
	FormStore,
} from '../public/valhalla/stores/index.js';
import * as api from '../apis/vacationType.js';
import * as timeSelectionApi from '../apis/timeSelection.js';
const getLabel = WeaLocaleProvider.getLabel;

const queryParams = {
	selectiontype: 0
}

class VacationTypeStore {
	@observable authorityStore = new AuthorityStore(api.getHasRight);
	@observable topStore = new TopStore(api.getRightMenu, this);
	@observable searchStore = new SearchStore(api.getSearchCondition, this);
	@observable tableListStore = new TableListStore(api.getSearchList, this);
	@observable dialogStore = new DialogStore(this);
	@observable formStore = new FormStore(api.getLeaveTypesForm, this);
	@observable isEnable = true;

	get topLoading() {
		const {
			loading
		} = this.tableListStore.tableStore;

		return loading;
	}

	get rightMenuStates() {
		const {
			loading,
			selectedRowKeys
		} = this.tableListStore.tableStore;

		return [loading, loading, selectedRowKeys.length === 0];
	}

	get topConfig() {
		return {
			title: getLabel(505572, "假期类型")
		}
	}

	get searchConfig() {
		return {
			linkageFieldName: 'leaveName'
		}
	}

	get formConfig() {
		return {
			linkageConfigs: this.linkageConfigs,
			isCustomRender: true,
			customRenderKeyList: ['proportion']
		}
	}

	get linkageConfigs() {
		return [
			//流程可见范围
			{
				passiveKey: 'scopeValue', //分部
				activeKey: 'scopeType',
				showValue: '1'
			},
			{
				passiveKey: 'scopeValueDepartment', 
				activeKey: 'scopeType',
				showValue: '2'
			},
			{
				passiveKey: 'scopeValueMember',
				activeKey: 'scopeType',
				showValue: '3'
			},
			//计算请假时长方式
			{
				passiveKey: 'hoursToDay', //日折算时长
				activeKey: 'computingMode',
				showValue: '2',
			},
			//时间选择方式
			{
				passiveKey: 'timeselection', //时间选择方式
				activeKey: 'minimumUnit',
				showValue: '2',
			},
			{
				passiveKey: 'filterHolidays', 
				activeKey: 'computingMode',
				showValue: '2',
			},
			{
				passiveKey: 'conversion', 
				activeKey: 'minimumUnit',
				showValue: '5,6',
			},
			{
				passiveKey: 'schevacation', 
				activeKey: 'schevacationON',
				showValue: '1',
			},
		]
	}

	get OtherComponents() {
		return {
			hoursToDay: () => { //日折算时长
				return (
					<span style={{marginLeft: 10}}>
						{`${getLabel('391',"小时")}=1${getLabel('505553',"天")}`}
						<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@hpht7c`}
							style={{marginLeft: 10}}
	         				title={getLabel('505576',"当计算请假时长方式选择按自然日计算请假时长时，需设置日折算时长。")}
	        			/>
					</span>
				)
			},
			timeselection: (item, form) => {//时间选择方式
				const {
					timeselection
				} = form.getFormParams();
				if(timeselection == 1)
					return (
						<span className="name-def" onClick={() => this.getDefForm()}>{getLabel('513303','选项名称定义')}</span>
					)
				else
					return <span><WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@orvxow`} style={{marginLeft: 10}} title={getLabel('514037','前端选择具体起止时间时，时长不满半天的算半天，满半天不满一天的，算一天')} /></span>;
			},
			minimumUnit: (item, form) => { //请假单位
				const {
					minimumUnit
				} = form.getFormParams();

				return (
					<p>
						<i className='icon-coms-content-o'/>
						<span dangerouslySetInnerHTML={{__html: this.minimumUnit[parseInt(minimumUnit)-1]}} style={{marginLeft: 5}}/>
					</p>
				)
			},
			proportion: (item, form) => { //余额单位变更时的换算比例
				return (
					<span style={{marginLeft: 10}}>
						{`${getLabel('391',"小时")}=1${getLabel('505553',"天")}`}
						<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@ril0rx`}
							style={{marginLeft: 10}}
	         				title={getLabel('505577',"编辑假期时当请假单位在天与小时之间变更时需设置假期余额的换算比例，设置保存后会自动进行历史余额的换算：如原有余额为5天，请假单位变更为小时，设置换算比例为8小时=1天，则保存后余额自动换算为40小时")}
	        			/>
					</span>
				)
			},
			conversion:(item, form)=>{
				const {
					minimumUnit,
					conversion,
				} = form.getFormParams();

				const tips = this[`conversion${minimumUnit}`]

				return (
					<p>
						<i className='icon-coms-content-o'/>
						{tips && <span dangerouslySetInnerHTML={{__html: tips[parseInt(conversion)-1]}} style={{marginLeft: 5}}/>}
					</p>
				)
			}
		}
	}

	get newDialogConfig() {
		return {
			title: getLabel(505573, '新建假期类型'),
			style: {
				width: 600,
				height: 300
			}
		}
	}

	get editDialogConfig() {
		return {
			title: getLabel(505574, '编辑假期类型'),
			style: {
				width: 600,
				height: 300
			}
		}
	}

	get DialogButtons() {
		if (this.isEnable) {
			return (
				[<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pozp8n`} type='primary' disable={this.formStore.loading} onClick={() => this.handleSaveClick()}>{getLabel(505564, '保存')}</Button>]
			)
		}else{
			return [];
		}
	}

	get MoreBtn() {
		return {
			datas: []
		}
	}

	preMount = () => {
		this.topStore.setTopConfig(this.topConfig);
		this.searchStore.setSearchConfig(this.searchConfig);
	}

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

			this.topStore.fetchRightMenu();

			this.searchStore.fetchSearchForm().then(() => {
				const params = this.searchStore.form.getFormParams();
				this.tableListStore.fetchTableList(params);
			})
		})
	}

	//关闭下拉面板
	resetStoreDatas = () => {
		this.searchStore.showSearchAd = false;
	}

	//新建假期类型
	new = () => {
		const {
			setDialogConfig,
			openDialog,
		} = this.dialogStore;

		this.dialogType = 'new';

		setDialogConfig(this.newDialogConfig);

		openDialog();

		this.getForm();
	}

	batchDelete = () => {
		const msg = getLabel(385625, '确定要删除选择的记录吗？');

		this.tableListStore.showConfirm(msg).then(() => {
			const {
				selectedRowKeys
			} = this.tableListStore.tableStore;

			const params = {
				typeIds: selectedRowKeys + ''
			};

			this.del(params);

		})
	}

	singleDel = (typeId) => {
		const msg = getLabel(83877, '确定要删除吗？');

		this.tableListStore.showConfirm(msg).then(() => {
			const params = {
				typeIds: typeId
			};

			this.del(params);
		});
	}

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

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

	//编辑假期类型
	doEdit = (typeId) => {
		const {
			setDialogConfig,
			openDialog,
		} = this.dialogStore;

		this.dialogType = 'edit';

		this.typeId = typeId;

		setDialogConfig(this.editDialogConfig);

		openDialog();

		const params = {
			typeId
		};
		this.getForm(params);
	}

	log = (id) => {
		this.tableListStore.showLog('3059', id);
	}

	custom = () => {
		this.tableListStore.colSet()
	}

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

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

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

	//保存按钮事件回调
	handleSaveClick = () => {
		const {
			form,
			validateForm,
		} = this.formStore;

		this.setHideFormFieldKeys();

		validateForm(form).then(() => {
			this.isNameRepeat().then(() => {
				const params = form.getFormParams();

				if (this.dialogType === 'edit') {
					Object.assign(params, {
						typeId: this.typeId
					});
				}

				const apiName = (this.dialogType === 'new') ? 'addLeaveTypes' : 'editLeaveTypes';

				this.formStore.loading = true;

				api[apiName](params).then(datas => {
					const {
						sign
					} = datas;

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

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

	setHideFormFieldKeys = () => {
		const {
			form,
			conditions,
			collectHideFormFieldKeys
		} = this.formStore, {
			scopeType, //流程可见范围,
			computingMode, //计算请假时长方式
		} = form.getFormParams();

		//默认一项：假期名称
		const needValidation = ['leaveName','showOrder'];

		if (scopeType === '1') { //分部
			needValidation.push('scopeValue');
		}
		if (scopeType === '2') { 
			needValidation.push('scopeValueDepartment');
		}
		if (scopeType === '3') { //分部
			needValidation.push('scopeValueMember');
		}
		if (computingMode === '2') { //按自然日计算请假时长
			needValidation.push('hoursToDay');
		}

		window.e9HideFormFieldKeys = collectHideFormFieldKeys(needValidation);
	}

	isNameRepeat = () => {
		return new Promise((resolve, reject) => {
			const {
				form
			} = this.formStore, {
				leaveName
			} = form.getFormParams();

			const params = {
				leaveName
			}

			if (this.dialogType === 'edit') {
				Object.assign(params, {
					typeId: this.typeId
				})
			}

			api.isNameRepeat(params).then(datas => {
				const {
					isRepeat
				} = datas;

				if (isRepeat) {
					form.showError('leaveName', `${getLabel(388883,'假期名称')}${getLabel(18082,'重复')}`)
				} else {
					resolve();
				}
			})
		})
	}

	//表单事件回调
	handleFormChange = (datas) => {
		const {
			minimumUnit
		} = datas;

		if (minimumUnit) {
			const {
				value
			} = minimumUnit;

			const {
				setCustomRenderKeyList
			} = this.formStore;

			const d = ['1','2','4'],h = ['3','5','6']

			if (
				 (d.includes(value) && h.includes(this.prevMinimumUnit) ) ||
				 ( h.includes(value) && d.includes(this.prevMinimumUnit) )
			) {
				setCustomRenderKeyList('');
			} else {
				setCustomRenderKeyList(['proportion']);
			}

			this.prevMinimumUnit = value

		}
	}

	getForm = (params) => {
		const {
			setFormConfig,
			setCustomRenderKeyList,
			fetchForm,
		} = this.formStore;

		setFormConfig(this.formConfig);
		setCustomRenderKeyList(['proportion']);
		fetchForm(params, this.exportFormDatas);
	}

	exportFormDatas = (datas) => {
		['isEnable', 'minimumUnit','conversion5','conversion6'].forEach(val => {
			this[val] = datas[val];
		});
		this.getDefaultVacationUnit(datas.condition);
	}

	getDefaultVacationUnit = (condition) => {
		condition.forEach(c => c.items.forEach(item => {
			if (item.domkey[0] === "minimumUnit") {
				this.prevMinimumUnit = item.options.find(option => option.selected).key;
			}
		}))
	}

	handleSearch = () => {
		const params = this.searchStore.form.getFormParams();
		this.tableListStore.fetchTableList(params);
	}

	reRenderColumns = (columns) => {
		let _this = this;
		columns.map(column => {
			if (column.dataIndex === 'leaveName') { //假期名称
				column.render = (text, record) => {
					const {
						leaveName,
						randomFieldId: typeId
					} = record;

					return <a onClick={()=>this.doEdit(typeId)}>{leaveName}</a>
				}
			}
			if (column.dataIndex === 'isEnable') { //是否启用
				column.render = function(text, record) {
					const {
						randomFieldId
					} = record;

					return <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@y3kww8@${column.dataIndex}`} value={text} onChange={val => _this.handleCheckboxChange(val,randomFieldId) }/>
				}
			}
			if (column.dataIndex === 'showOrder') { //显示顺序
				column.render = function(text, record) {
					const {
						randomFieldId
					} = record;

					return <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@9lbws3@${column.dataIndex}`} defaultValue={text} precision={2} onChange={val => _this.handleInputNumberChange(val,randomFieldId) }/>
				}
			}

		})
	}

	handleCheckboxChange = (val, id) => {
		const {
			datas
		} = this.tableListStore.tableStore;

		const result = datas.find(data => data.randomFieldId === id);

		if (result) {
			result.isEnable = val;
		}

	}

	handleInputNumberChange = (val, id) => {
		const {
			datas
		} = this.tableListStore.tableStore;

		const result = datas.find(data => data.randomFieldId === id);

		if (result) {
			result.showOrder = val;
		}

	}

	onOperatesClick = (record, rowIndex, operate) => {
		const {
			randomFieldId: typeId
		} = record, {
			index
		} = operate;

		switch (index) {
			case '0':
				this.doEdit(typeId);
				break;
			case '1':
				this.singleDel(typeId);
				break;
			case '2':
				this.log(typeId);
				break;
		}
	}

	/** 选项名称定义 */
	@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@74xh9j`} 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 = () => {
		const {minimumUnit} = this.formStore.form.getFormParams();
		const params = {leaveruleid: this.typeId, ...queryParams, 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 {minimumUnit} = this.formStore.form.getFormParams();
		const params = {leaveruleid: this.typeId, ...queryParams, 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);
			}
		})
	}

}

export const vacationTypeStore = new VacationTypeStore();