import {
	observable,
	action,
	computed,
	toJS,
} from 'mobx';
import {
	WeaLocaleProvider,
	WeaHelpfulTip,
	WeaFormItem,
	WeaTable,
} from 'ecCom';
import {
	WeaSwitch
} from 'comsMobx';
import {
	Button,
	message,
	Radio,
} from 'antd';
import {
	AuthorityStore,
	TopStore,
	SearchStore,
	TableListStore,
	DialogStore,
	FormStore,
} from '../public/valhalla/stores/index.js';
import * as api from '../apis/vacationRule.js';
import Rules23th from '../components/vacationRule/Rules23th.js';
import Rules6thPanel from '../components/vacationRule/Rules6thPanel.js';
import { i18n } from '../public/i18n.js';
import unionBy from 'lodash/unionBy';
import cloneDeep from 'lodash/cloneDeep';
const getLabel = WeaLocaleProvider.getLabel;
const RadioGroup = Radio.Group;

class VacationRuleStore {
	@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 provinceDialogStore = new DialogStore(this);
	@observable formStore = new FormStore(api.getLeaveRulesForm, this);
	@observable provinceFormStore = new FormStore(api.getParentalForm, this);

	@observable sectionValue = 1;
	@observable detailRule = [];

	@observable legalRule = [];
	@observable welfareRule = [];
	@observable legalKey = '0';
	@observable welfareKey = '1';

	@observable unitName = '';
	@observable isEnable = '1';

	get workTimeType() {
		const {
			distributionMode
		} = this.formStore.form.getFormParams();

		if ([ '2','7'].includes(distributionMode)) {
			return getLabel(505548, '司龄');
		}
		if (distributionMode === '3') {
			return getLabel(505549, '工龄');
		}
	}

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

		return loading;
	}

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

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

	get topConfig() {
		return {
			title: getLabel('505561', "假期规则")
		}
	}

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

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

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

	get formConfig() {
		return {
			linkageConfigs: this.linkageConfigs,
			groupShowConfigs:this.groupShowConfigs,
			customRenderKeyList: this.customRenderKeyList,
			isCustomRender: true,
		}
	}

	//法定年假列名
	get legalCols() {
		const unit = this.unitName ? this.unitName : getLabel(505553, '天');

		const legalCol = `${getLabel('505556', "法定年假")}(${unit})`;
		const workYearCol = `${getLabel('505549',"工龄")}(${getLabel('505552',"年")})`;
		const entryTimeCol = `${getLabel('505548',"司龄")}(${getLabel('505552',"年")})`;

		const cols = [legalCol];

		if (this.legalKey === '0') {
			cols.unshift(workYearCol);
		} else if (this.legalKey === '1') {
			cols.unshift(entryTimeCol);
		} else {
			[entryTimeCol, workYearCol].forEach(col => {
				cols.unshift(col);
			})
		}

		return cols;
	}

	//福利年假列名
	get welfareCols() {
		const unit = this.unitName ? this.unitName : getLabel(505553, '天');

		const welfareCol = `${getLabel('505557', "福利年假")}(${unit})`;
		const workYearCol = `${getLabel('505549',"工龄")}(${getLabel('505552',"年")})`;
		const entryTimeCol = `${getLabel('505548',"司龄")}(${getLabel('505552',"年")})`;

		const cols = [welfareCol];

		if (this.welfareKey === '0') {
			cols.unshift(workYearCol);
		} else if (this.welfareKey === '1') {
			cols.unshift(entryTimeCol);
		} else {
			[entryTimeCol, workYearCol].forEach(col => {
				cols.unshift(col);
			})
		}
		return cols;
	}

	//法定年假、福利年假规则选择框options
	get ruleOptions() {
		return [{
			key: "0",
			showname: getLabel('505549', "工龄")
		}, {
			key: "1",
			showname: getLabel('505548', "司龄")
		}, {
			key: "2",
			showname: `${getLabel('505549', "工龄")} + ${getLabel('505548', "司龄")}`
		}]
	}

	get linkageConfigs() {
		return [
			//应用范围
			{
				passiveKey: 'scopeValue', //分部
				activeKey: 'scopeType',
				showValue: '1'
			},
			{
				passiveKey: 'scopeValueDepartment', //分部
				activeKey: 'scopeType', //应用范围
				showValue: '2'
			},
			{
				passiveKey: 'scopeValueMember', //分部
				activeKey: 'scopeType', //应用范围
				showValue: '3'
			},
			//余额发放方式
			{
				passiveKey: 'annualAmount', //每人发放余额
				activeKey: 'distributionMode',
				showValue: '4'
			}, {
				passiveKey: 'priority', //优先级别
				activeKey: 'distributionMode',
				showValue: '6'
			}, {
				passiveKey: 'calcMethod', //假期基数计算方式
				activeKey: 'distributionMode',
				showValue: '2,3,6'
			}, {
				passiveKey: 'convertMode', //是否折算
				activeKey: 'distributionMode',
				showValue: '2,3,4,6'
			},{
				passiveKey: 'releaseRule', //释放规则
				activeKey: 'distributionMode',
				showValue: '1,2,3,4,6'
			},
			{
				passiveKey: 'severalChildren', 
				activeKey: 'distributionMode',
				showValue: '8'
			},
			{
				passiveKey: 'isprovince',
				activeKey: 'distributionMode',
				showValue: '8'
			},
			{
				passiveKey: 'carryOver',
				activeKey: 'distributionMode',
				showValue: '1,2,3,4,6,7'
			},
			{
				passiveKey: 'carryOverDays',
				activeKey: 'distributionMode',
				showValue: '1,2,3,4,6,7'
			},
			{
				passiveKey: 'carryOverDays',
				activeKey: 'carryOver',
				showValue: '1'
			},
			{
				passiveKey: 'excludeSubAccount',
				activeKey: 'distributionMode',
				showValue: '1,2,3,4,6,7,8'
			},
			{
				passiveKey: 'beforeFormal',
				activeKey: 'distributionMode',
				showValue: '1,2,3,4,6,7,8'
			},
			{
				passiveKey: 'deductorder',
				activeKey: 'distributionMode',
				showValue: '5'
			},
			//有效期规则
			{
				passiveKey: 'expirationMonth', //次年失效日期
				activeKey: 'validityRule',
				showValue: '3'
			}, {
				passiveKey: 'extensionEnable', //允许延长有效期
				activeKey: 'validityRule',
				showValue: '1,2,3,5'
			}, {
				passiveKey: 'effectiveDays', //有效天数
				activeKey: 'validityRule',
				showValue: '4,8'
			}, {
				passiveKey: 'effectiveMonths', //有效月数
				activeKey: 'validityRule',
				showValue: '6'
			}
		]
	}

	get groupShowConfigs() {
		return [{
			passiveIndex: 3,
			activeKey: 'distributionMode',
			showValue: '1,2,3,4,5,6,7,8'
		}]
	}

	get OtherComponents() {
		return {
			distributionMode: (item, form) => { //余额发放方式
				const {
					distributionMode
				} = form.getFormParams();

				let balancePaymentRule;

				if (['2', '3',"7"].includes(distributionMode)) { //司龄、工龄
					balancePaymentRule = <Rules23th ecId={`${this && this.props && this.props.ecId || ''}_Rules23th@4gyz2s`} store={this}/>
				}
				if (distributionMode === '6') { //司龄+工龄
					balancePaymentRule = <Rules6thPanel ecId={`${this && this.props && this.props.ecId || ''}_Rules6thPanel@zwbc1n`} store={this}/>
				}

				return (
					<div>
						<p>
							<i className='icon-coms-content-o'/>
							<span dangerouslySetInnerHTML={{__html: this.distributionMode[parseInt(distributionMode)-1 ]}} style={{marginLeft: 5}}/>
						</p>
						{balancePaymentRule}
					</div>
				)
			},
			annualAmount: () => { //每人发放余额
				return <span style={{marginLeft: 15}}>{this.unitName?this.unitName:getLabel(1925, '天')}</span>
			},
			calcMethod: (item, form) => { //假期基数计算方式
				const {
					calcMethod
				} = form.getFormParams();

				return (
					<p>
						<i className='icon-coms-content-o'/>
						<span dangerouslySetInnerHTML={{__html: this.calcMethod[parseInt(calcMethod)]}} style={{marginLeft: 5}}/>
					</p>
				)
			},
			convertMode:(item, form) => {//是否折算
				const {
					convertMode
				} = form.getFormParams();

				return (
					<p>
						<i className='icon-coms-content-o'/>
						<span dangerouslySetInnerHTML={{__html: this.convertModeTips[parseInt(convertMode)]}} style={{marginLeft: 5}}/>
					</p>
				)
			},
			extensionEnable: (item, form) => { //允许延长有效期
				const {
					extensionEnable
				} = form.getFormParams();

				if (parseInt(extensionEnable) === 1) {
					const fieldConfig = this.customRenderItems['extendedDays'];

					return (
						<p>
							<span>{getLabel(505558,'超过有效期')}</span>
							<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@zb17bs`}
								label={""}
								labelCol={{span: 0}}
								wrapperCol={{span:24}}
								error={form.getError(fieldConfig)} 
								// errorStyle={{width: window.e9_locale.userLanguage == '7' ? 180 : 310}}
								errorStyle={{whiteSpace: 'nowrap'}}
								tipPosition='bottom'
								className={"extendedDays"}
							>
								<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@whftdo`} 
									fieldConfig={fieldConfig} 
									form={form} 
									formParams={form.getFormParams()} 
								/>
							</WeaFormItem>
							<span style={{marginLeft: 10}}>{`${getLabel(1925, '天')}`}</span>
						</p>
					)
				}
			},
			expirationMonth: (item, form) => { //次年失效日期
				const fieldConfig = this.customRenderItems['expirationDay'];

				return (
					<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@oj08us`} 
						fieldConfig={fieldConfig} 
						form={form} 
						formParams={form.getFormParams()} 
					/>
				)
			},
			effectiveDays: () => { //有效天数
				return <span style={{marginLeft: 15}}>{getLabel(1925, '天')}</span>
			},
			effectiveMonths: () => { //有效月数
				return (
					<React.Fragment ecId={`${this && this.props && this.props.ecId || ''}_undefined@jrounh`}>
						<span style={{marginLeft: 15,marginRight: 10}}>{getLabel(6076, '月')}</span>
						<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@yy1mag`} title={getLabel(515184,"最小为1，等于1时表示失效日期为当月月底，等于2时表示失效日期为下个月月底，依此类推")}/>
					</React.Fragment>
				)
			},
			carryOverDays: () => {
				return <span style={{marginLeft: 15}}>{this.unitName?this.unitName:getLabel(1925, '天')}</span>
			}
		};

	}

	get customRenderedElements() {
		return {
			isprovince: (field, textAreaProps, form, formParams) => {
				const radioStyle = {
					display: 'block',
					height: '30px',
					lineHeight: '30px',
				};
				const columns = [
					{
						title: getLabel('546837','省份'),
						dataIndex: "provincename",
						key: "provincename",
						width: "20%",
					},
					{
						title: getLabel('546838',"子女年龄上限（周岁）"),
						dataIndex: "yearsOld",
						key: "yearsOld",
						width: "20%",
					},
					{
						title: getLabel('547727',"发放{param}数").replace('{param}',this.unitName || getLabel(505553, '天')),
						dataIndex: "amount",
						key: "amount",
						width: "20%",
					},
					{
						title: getLabel('546856','操作'),
						key: 'operation',
						width: "20%",
						render: (text, record) => (
							<span>
								<a  onClick={this.editProvince(record)}>{getLabel('93','编辑')}</a>
								<a  onClick={this.deleteProvince(record)} style={{marginLeft: 8}}>{getLabel(131966, '删除')}</a>
							</span>
						),
					  },
				];


				return (
					<div className="cust">
						<div className="basic">
							<RadioGroup ecId={`${this && this.props && this.props.ecId || ''}_RadioGroup@lsqvqm`} disabled={field.viewAttr === 1} onChange={e => form.updateFields({ isprovince: { value: e.target.value } })} value={formParams.isprovince}>
								{
									field.options.map((option, index) => {
										return (
											<Radio ecId={`${this && this.props && this.props.ecId || ''}_Radio@b10cnh@${index}`} style={radioStyle} key={option.key} value={option.key}>
												<span className="isprovince">
													{(option.key == '1') ? (
														<span>
															<span>{getLabel('546843','孩子')}</span>
															<WeaSwitch
																fieldConfig={{
																	...form.fieldMap["yearsOld"],
																	style:{
																		width:60
																	},
																	viewAttr: formParams.isprovince == '2' ? '1' : '2',
																	hasBorder: true
																}}
																form={form}
																formParams={formParams}
																onChange={
																	(v) => {
																		form.updateFields(v)
																	}
																}
															/>
															<span>{getLabel('546846','周岁前，')}</span>
															<span>{getLabel('546975','发放固定{param}数').replace('{param}',this.unitName || getLabel('391',"小时"))}</span>
															<WeaSwitch
																fieldConfig={{
																	...form.fieldMap["annualAmount"],
																	style:{
																		width:60
																	},
																	viewAttr: formParams.isprovince == '2' ? '1' : '2',
																	hasBorder: true
																}}
																form={form}
																formParams={formParams}
																onChange={
																	(v) => {
																		form.updateFields(v)
																	}
																}
															/>
															<span>{this.unitName || getLabel('391',"小时")}</span>
														</span>
													) : option.showname}
												</span>
											</Radio>
										)
									})
								}
							</RadioGroup>
							{formParams.isprovince == '2' && (
								<div className="isprovince-table">
									<div>
										<Button onClick={this.addProvince}>{i18n.label.add()}</Button>
										<Button onClick={this.batchDeleteProvinces} disabled={this.selectedRowKeys.length == 0} style={{marginLeft: 8}}>{i18n.label.multiDelete()}</Button>
									</div>
									<WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@9jz6k1`}  
										columns = {columns}
										dataSource = {this.dataSource}
										pagination={false}
										rowSelection={{
											selectedRowKeys:this.selectedRowKeys,
											onChange: this.onSelectChange,
										}}
										/>
								</div>
							)}
						</div>
					</div>
				);
			}
		}
	}

	get provinceDialogButtons() {
		return (
			[
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@shhsxw`} type='primary'  onClick={this.logicallyAddNewProvince}>{getLabel(33703, '确定')}</Button>,
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@shhsxw`}   onClick={this.closeProvincDialog}>{getLabel(32694, '取消')}</Button>,

		]
		)
	}

	@observable selectedRowKeys = [];

	@observable dataSource = [];
	provinceInfo = [];
	provinceOp = 'add';

	onSelectChange = (selectedRowKeys) => {
		this.selectedRowKeys = selectedRowKeys;
	}

	addProvince = () => {
		const {
			setDialogConfig,
			openDialog,
		} = this.provinceDialogStore;

		this.provinceOp = 'add';
		this.provinceFormStore.form.resetForm();
		this.provinceFormStore.conditions[0].items[0].viewAttr = 3;
		setDialogConfig(this.provinceDialogNewConfig);
		openDialog();
	}

	@action batchDeleteProvinces  = () => {
		this.dataSource = this.dataSource.filter((data,index) => !this.selectedRowKeys.includes(index));
		this.selectedRowKeys = [];	
	}

	editProvince = (record) => {
		return ()=>{
			const {
				setDialogConfig,
				openDialog,
			} = this.provinceDialogStore;
	
			setDialogConfig(this.provinceDialogEditDialogConfig);
			openDialog();

			this.provinceOp = 'edit';
			this.fetchRowDataAndUpdateForm(record);
		}

	}

	fetchRowDataAndUpdateForm = (record) => {
		//1、获取当前行数据
		const { id, yearsOld, amount } = record;

		//2、更新表单
		this.provinceFormStore.form.updateFields({
			multiselectprovinceValue: id,
			yearsOld:{
				value: yearsOld
			},
			amount:{
				value: amount
			}
		});

		//3、省份只读
		this.provinceFormStore.conditions[0].items[0].viewAttr = 1;
		
	}

	@action deleteProvince = (record) => {
		return () => {
			this.dataSource = this.dataSource.filter(data => data.id !== record.id);
		}
	}

	getProvinceForm  = (id) => {
		const {
			setFormConfig,
			fetchForm,
		} = this.provinceFormStore;

		const params = {
			typeId: id
		};
		setFormConfig({isCustomRender: true});
		fetchForm(params,this.getProvinceInfo);
	}

	getProvinceInfo = (data) => {
		this.provinceInfo = data.condition[0].items[0].options;
	}

	logicallyAddNewProvince = () => {
		// 1、校验
		const {
			form,
			validateForm,
		} = this.provinceFormStore;
		validateForm(form).then(() => {
			if(this.provinceOp == 'add'){
				// 2、将表单数据转换成table需要的数据
				this.convertFormDataToTableData();
			}else{
				this.updateTableData();
			}
			this.closeProvincDialog();
		})
		
	}

	@action convertFormDataToTableData = () => {
		const {
			form,
		} = this.provinceFormStore;
		const { multiselectprovinceValue, yearsOld, amount } = form.getFormParams();
		const newData = multiselectprovinceValue.split(',').map(val => {
			const provincename = this.provinceInfo.find(info => info.key === val).showname;
			return {
				id: val,
				provincename,
				yearsOld,
				amount,
			}
		})
		this.dataSource = unionBy(newData, toJS(this.dataSource), 'id');
	}

	@action updateTableData = () => {
		const {
			form,
		} = this.provinceFormStore;
		const { multiselectprovinceValue, yearsOld, amount } = form.getFormParams();

		this.dataSource = this.dataSource.map(data => {
			if( data.id === multiselectprovinceValue){
				data.yearsOld = yearsOld;
				data.amount = amount;
			}
			return data;
		})

	}

	closeProvincDialog = () => {
		const {
			closeDialog
		} = this.provinceDialogStore;
		closeDialog();
	}

	@action closeDialog = () => {
		this.selectedRowKeys = [];
		this.dataSource = [];
	}


	get newDialogConfig() {
		return {
			title: getLabel(505562, '新建假期规则'),
			style: {
				width: 775,
				height: 650
			}
		}
	}

	get editDialogConfig() {
		return {
			title: getLabel(505563, '编辑假期规则'),
			style: {
				width: 775,
				height: 650
			}
		}
	}

	get provinceDialogNewConfig() {
		return {
			title: getLabel(546862,'新增规则') ,
			dialogMark:'province',
			style: {
				width: 550,
				height: 300
			}
		}
	}

	get provinceDialogEditDialogConfig() {
		return {
			title: getLabel(546863,'编辑规则'),
			dialogMark:'province',
			style: {
				width: 550,
				height: 300
			}
		}
	}


	//自定义渲染表单元素的key值
	get customRenderKeyList() {
		return ['extendedDays', 'expirationDay','yearsOld']
	}

	//根据customRenderKeyList得出item的集合
	get customRenderItems() {
		const {
			conditions
		} = this.formStore;

		let items = {};

		conditions.forEach(condition => {
			condition.items.forEach(item => {
				const {
					domkey
				} = item;
				if (this.customRenderKeyList.includes(domkey[0])) {
					Object.assign(items, {
						[domkey[0]]: item
					})
				}
			})
		})

		return items
	}

	@computed get isDistributeModeDisabled() {
		return this.isEnable === '0';
	}

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

	//页面初始化
	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.resetDistributeModeRule();

		this.dialogType = 'new';

		setDialogConfig(this.newDialogConfig);

		openDialog();

		this.getForm();

		
	}

	resetDistributeModeRule = () => {
		['detailRule', 'legalRule', 'welfareRule'].forEach(val => {
			this[val] = [];
		})
	}

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

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

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

			this.del(params);

		})
	}

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

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

			this.del(params);
		});
	}

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

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

	doEdit = (ruleId) => {
		const {
			setDialogConfig,
			openDialog,
		} = this.dialogStore;

		this.resetDistributeModeRule();

		this.dialogType = 'edit';

		this.ruleId = ruleId;

		setDialogConfig(this.editDialogConfig);
		openDialog();

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

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

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

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

		this.setHideFormFieldKeys();

		validateForm(form).then(() => {
			if(!this.validateHolidayDaysSettings())return;
			this.isNameRepeat().then(() => {
				const params = form.getFormParams();

				if (['2', '3','7'].includes(distributionMode)) {
					Object.assign(params, {
						detailRule: JSON.stringify(this.detailRule)
					})
				}
				if (distributionMode === '6') {
					Object.assign(params, {
						legalRule: JSON.stringify(this.legalRule),
						welfareRule: JSON.stringify(this.welfareRule),
						legalKey: this.legalKey,
						welfareKey: this.welfareKey,
					})
				}

				if(distributionMode === '8' && isprovince === '2'){
					Object.assign(params, {
						detailRule: JSON.stringify(cloneDeep(toJS(this.dataSource)).map(data => {
							data.provinceid = data.id;
							delete data.id;
							delete data.provincename;
							return data
						})),
					})
				}

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

				const apiName = (this.dialogType === 'new') ? 'addLeaveRules' : 'editLeaveRules';

				this.formStore.loading = true;

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

					if ( api_status && status !== '-1') {
						message.success(datas.message || i18n.message.saveSuccess());
						this.handleSearch();
						this.dialogStore.closeDialog();
					} else {
						message.warning(datas.message);
					}

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


	}

	validateHolidayDaysSettings = () => {
		const {
			form,
		} = this.formStore, {
			distributionMode,
			isprovince,
			yearsOld,
			annualAmount,
		} = form.getFormParams();

		if(distributionMode == '8' && isprovince == '1'){
			if(!yearsOld && yearsOld !== 0){
				message.warning(getLabel(546860,'请填写孩子周岁') );
				return false
			}

			if(!annualAmount && annualAmount !== 0){
				message.warning(getLabel(546861,'请填写发放固定小时数') );
				return false
			}
		}

		return true
	}

	setHideFormFieldKeys = () => {
		const {
			form,
			conditions,
			collectHideFormFieldKeys
		} = this.formStore, {
			scopeType, //应用范围
			distributionMode, //余额发放方式
			extensionEnable, //允许延长有效期
			validityRule, //有效期规则
			carryOver,
		} = form.getFormParams();

		//默认两项：假期类型、规则名称
		const needValidation = ['typeId', 'ruleName'];

		if (scopeType === '1') { //分部
			needValidation.push('scopeValue');
		}
		if (distributionMode === '4') { //每年自动发放固定余额
			needValidation.push('annualAmount');
		}
		if (parseInt(extensionEnable) === 1) { //允许延长有效期
			needValidation.push('extendedDays');
		}
		if (validityRule === '4') {//有效期规则
			needValidation.push('effectiveDays');
		}
		if (validityRule === '6') {
			needValidation.push('effectiveMonths');
		}

		if(['1','2','3','4','6','7'].includes(distributionMode) &&  carryOver === '1'){
			needValidation.push('carryOverDays');
		}

		window.e9HideFormFieldKeys = collectHideFormFieldKeys(needValidation);
	}

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

			const params = {
				ruleName
			}

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

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

				if (isRepeat) {
					form.showError('ruleName', getLabel(84543, '规则名称已存在！'))
				} else {
					resolve();
				}
			})
		})
	}

	//表单事件回调
	handleFormChange = (datas) => {
		const {
			typeId,
			distributionMode,
			calcMethod,
		} = datas;

		if (typeId) { //切换假期类型
			const {
				value
			} = typeId;

			this.getUnitName(value);
			this.getProvinceForm(value);
		}

		if (distributionMode) { //切换余额发放方式
			const {
				value
			} = distributionMode;

			if (['2', '3','7'].includes(value)) {
				this.sectionValue = 1; //重置区间
				this.detailRule = [{ //重置工龄、司龄规则
					timePoint: 0,
					amount: 0
				}, {
					timePoint: 1,
					amount: 5
				}];
			};
			if (value === '6') {
				this.legalKey = '0'; //默认选中工龄
				this.welfareKey = '1'; //默认选中司龄
				this.legalRule = [{
					workYear: 0,
					legalAmount: 0
				}];
				this.welfareRule = [{
					entryTime: 0,
					welfareAmount: 0
				}];
			};

			this.setValidityRuleDisabled(value);

			//【余额发放方式】从第5项切换到其他项时，重置【有效期规则】
			if (this.lastDistributionMode === '5' && value !== '5') {
				this.formStore.form.updateFields({
					validityRule: '0'
				})
			}
			//【余额发放方式】从第8项切换到其他项时，重置【有效期规则】
			if (this.lastDistributionMode === '8' && value !== '8') {
				this.formStore.form.updateFields({
					validityRule: '0'
				})
			}
			//【余额发放方式】从其他项第切换到8项时，重置【有效期规则】
			if (this.lastDistributionMode !== '8' && value == '8') {
				this.formStore.form.updateFields({
					validityRule: '7'
				})
			}

			//重置【假期基数计算方式】，避免【是否折算】第一项被禁用
			if (['2','3','6'].includes(this.lastDistributionMode) && !['2','3','6'].includes(value)) {
				this.formStore.form.updateFields({
					calcMethod: '1'
				});
				this.setConvertModeDisabled('1');
			}

			this.lastDistributionMode = value;


		}

		if (calcMethod) { //假期基数计算方式
			const {
				value
			} = calcMethod;

			this.setConvertModeDisabled(value);

			if (value === '0') {
				this.formStore.form.updateFields({
					convertMode: '1'
				})
			}
		}
	}

	setValidityRuleDisabled = (value) => {
		const {
			conditions
		} = this.formStore;
		//【余额发放方式】选中项不为'加班时长自动计入余额'时，禁用【有效期规则】最后一项。
		conditions.map(c => c.items.map(item => {
			if (item.domkey[0] === 'validityRule') {
				[4, 5, 6].map(val => {
					item.options[val].disabled = (value !== '5') ? true : false;
				}),
				[1,2,3].map(val => {
					item.options[val].disabled = (value == '8') ? true : false;
				}),
				[7].map(val => {
					item.options[val].disabled = (value !== '8') ? true : false;
				})
				
			}
		}));
	}

	setConvertModeDisabled = (value) => {
		const {
			conditions
		} = this.formStore;

		//【假期基数计算方式】选中项为'精确计算'时，是否折算第一项禁用。
		conditions.map(c => c.items.map(item => {
			if (item.domkey[0] === 'convertMode') {
				item.options[0].disabled = (value === '0') ? true : false;
			}
		}))
	}

	//获取假期余额发放单位
	@action getUnitName = (id) => {
		const params = {
			typeId: id
		};
		api.getUnitName(params).then(data => {
			const {
				unitName
			} = data;

			this.unitName = unitName;
		})
	}

	//区间回调
	@action handleSectionChange = (value) => {
		this.sectionValue = (value !== undefined) ? value : 1;
	}

	//余额数字框事件回调(工龄、司龄)
	@action handleRule23thTimeChange = (value, index) => {
		this.detailRule[index].amount = (value !== undefined) ? value : 0;
	}

	//添加规则(司龄、工龄)
	@action handle23thAddButtonClick = (type) => {
		//正常情况下，不会执行if语句块内的代码；
		//此段代码是为了避免误删数据库，导致前端添加规则出现数据异常的问题。
		if (this.detailRule.length === 0) {
			this.detailRule.push({
				timePoint: 0,
				amount: 0,
			});
			return;
		}

		const {
			timePoint,
			amount
		} = this.detailRule.slice(-1)[0];

		this.detailRule.push({
			timePoint: timePoint + this.sectionValue,
			amount: amount + 1,
		});
	}

	//删除规则(司龄、工龄)
	@action handle23thDelClick = () => {
		this.detailRule.pop();
	}

	//余额数字框事件回调（工龄+司龄）
	@action handleRule6thTimeChange = (val, index, prop, type) => {
		if (type === 'legal') {
			this.legalRule[index][prop] = (val !== undefined) ? val : 0;
		} else {
			this.welfareRule[index][prop] = (val !== undefined) ? val : 0;
		}
	}

	//添加规则(司龄+工龄)
	@action handle6thAddButtonClick = (type) => {
		//规则异常
		if (
			this.legalRule.length === 0 ||
			this.welfareRule.length === 0
		) {
			this.handle6thRuleError(type);
			return;
		}

		if (type === 'legal') {
			const {
				workYear,
				entryTime,
				legalAmount
			} = this.legalRule.slice(-1)[0];

			if (this.legalKey === '0') { //工龄
				this.legalRule.push({
					workYear: workYear + 1,
					legalAmount: legalAmount + 1
				});
			} else if (this.legalKey === '1') { //司龄
				this.legalRule.push({
					entryTime: entryTime + 1,
					legalAmount: legalAmount + 1,
				});
			} else {
				this.legalRule.push({ //工龄+司龄
					workYear: workYear + 1,
					entryTime: entryTime + 1,
					legalAmount: legalAmount + 1,
				});
			}
		} else {
			const {
				workYear,
				entryTime,
				welfareAmount
			} = this.welfareRule.slice(-1)[0];

			if (this.welfareKey === '0') {
				this.welfareRule.push({ //工龄
					workYear: workYear + 1,
					welfareAmount: welfareAmount + 1
				});
			} else if (this.welfareKey === '1') {
				this.welfareRule.push({ //司龄
					entryTime: entryTime + 1,
					welfareAmount: welfareAmount + 1
				});
			} else {
				this.welfareRule.push({ //工龄+司龄
					workYear: workYear + 1,
					entryTime: entryTime + 1,
					welfareAmount: welfareAmount + 1,
				});
			}
		}
	}

	handle6thRuleError = (type) => {
		if (type === 'legal') {
			if (this.legalKey === '0') { //工龄
				this.legalRule.push({
					workYear: 0,
					legalAmount: 0
				});
			} else if (this.legalKey === '1') { //司龄
				this.legalRule.push({
					entryTime: 0,
					legalAmount: 0,
				});
			} else {
				this.legalRule.push({ //工龄+司龄
					workYear: 0,
					entryTime: 0,
					legalAmount: 0,
				});
			}
		} else {
			if (this.welfareKey === '0') {
				this.welfareRule.push({ //工龄
					workYear: 0,
					welfareAmount: 0
				});
			} else if (this.welfareKey === '1') {
				this.welfareRule.push({ //司龄
					entryTime: 0,
					welfareAmount: 0
				});
			} else {
				this.welfareRule.push({ //工龄+司龄
					workYear: 0,
					entryTime: 0,
					welfareAmount: 0,
				});
			}
		}
	}

	//删除规则(司龄+工龄)
	@action handle6thDelClick = (type) => {
		if (type === 'legal') {
			this.legalRule.pop();
		} else {
			this.welfareRule.pop();
		}
	}

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

		setFormConfig(this.formConfig);
		fetchForm(params, this.exportFormDatas, this.afterFormInit);
	}

	@action exportFormDatas = (datas) => {
		['distributionMode', 'calcMethod', 'convertModeTips', 'isEnable', 'detailRule', 'unitName', 'legalRule', 'welfareRule', 'legalKey', 'welfareKey'].forEach(val => {
			this[val] = datas[val];
		});

		if(datas.detailRule && datas.detailRule.length > 0 && datas.detailRule[0].provincename !== undefined){
			this.dataSource = datas.detailRule.map(data => ({ ...data, id: data.provinceid+'' }));
		}
	}

	afterFormInit = () => {
		//将表单默认的【余额发放方式】选项挂载到当前对象上
		const {
			distributionMode,
			calcMethod,
			typeId
		} = this.formStore.form.getFormParams();

		this.setValidityRuleDisabled(distributionMode);
		this.setConvertModeDisabled(calcMethod);

		this.lastDistributionMode = distributionMode;

		this.getProvinceForm(typeId);
	}

	

	//法定年假、福利年假规则选择框事件回调
	@action handleRuleSelectChange = (key, type) => {
		if (type === 'legal') {
			this.legalKey = key;
		} else {
			this.welfareKey = key;
		}

		this.changeRuleCol(type)
	}

	changeRuleCol = (type) => {
		this[`${type}Rule`] = toJS(this[`${type}Rule`]).map(rule => {
			const {
				workYear,
				entryTime
			} = rule;

			const key = this[`${type}Key`];

			if (key === '0') { //规则：工龄
				if (!workYear) {
					rule.workYear = 0;
				}
				if (entryTime + '') { //0 => '0'
					delete rule.entryTime
				}
			} else if (key === '1') { //规则：司龄
				if (workYear + '') {
					delete rule.workYear
				}
				if (!entryTime) {
					rule.entryTime = 0;
				}
			} else { //规则：工龄+司龄
				if (!workYear) {
					rule.workYear = 0;
				}
				if (!entryTime) {
					rule.entryTime = 0;
				}
			}

			return rule;
		})

	}

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

	reRenderColumns = (columns) => {
		columns.map(column => {
			if (column.dataIndex === 'ruleName') {
				column.render = (text, record) => {
					const {
						ruleName,
						randomFieldId: ruleId
					} = record;

					return <a onClick={()=>this.doEdit(ruleId)}>{ruleName}</a>
				}
			}
		})
	}

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

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

}

export const vacationRuleStore = new VacationRuleStore();