import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaPopoverHrm,
	WeaHelpfulTip,
	WeaLocaleProvider,
	WeaButtonIcon
} from 'ecCom';
import {
	WeaSwitch
} from 'comsMobx';
import {
	Button,
	message, 
	Radio,
} from 'antd';
import {
	AuthorityStore,
	TopStore,
	SearchStore,
	TableListStore,
	FormStore,
	DialogStore,
} from '../public/valhalla/stores/index.js';
import * as api from '../apis/payrollSending.js';
import {addContentPath} from '../util/index.js'
const getLabel = WeaLocaleProvider.getLabel;

class PayrollSendingStore {
	@observable authorityStore = new AuthorityStore(api.getHasRight);
	@observable topStore = new TopStore(this);
	@observable searchStore = new SearchStore(this);
	@observable tableListStore = new TableListStore(this);
	@observable formStore = new FormStore(this);
	@observable dialogStore = new DialogStore(this);
	@observable dispatchImgDialogStore = new DialogStore(this);
	@observable detailSearchStore = new SearchStore(this);
	@observable detailTableListStore = new TableListStore(this);

	@observable isSended = false;
	@observable isProcessing = false;
	@observable dialogType = 'create';
	@observable uploadDispatchImg = '';
	@observable sendResult = {
		failnum:0,
		succnum:0
	};
	@observable payrollSendingDatas = [];
	@observable errorInfo = [];

	get topConfig() {
		return {
			api: api.getRightMenu,
			title: `Excel${getLabel(510036,'工资单发送')}`,
		}
	}

	@computed
	get SearchButtons(){
		return [];
		// const {
		// 	selectedKey
		// } = this.searchStore;
		// if(selectedKey != "3")
		// 	return [];
		// else{
		// 	const disabled = this.tableListSelectedRowKeys.length == 0;
		// 	// if(this.dialogStore.visible)
		// 	// 	return [];
		// 	return [
		// 		<WeaButtonIcon buttonType="del" type="primary" onClick={() => this.deleteRecordList()} disabled={disabled} />
		// 	]
		// }
	}

	@computed get DetailSearchButtons(){
		return [];
	}

	@computed
	get tableListSelectedRowKeys(){
		if(this.tableListStore && this.tableListStore.tableStore)
			return this.tableListStore.tableStore.selectedRowKeys;
		return '';
	}

	@computed get topLoading() {
		const {
			selectedKey
		} = this.searchStore;

		if (selectedKey === '1') {
			const {
				loading
			} = this.formStore;

			return loading;
		} else {
			const {
				loading
			} = this.tableListStore.tableStore;

			return loading;
		}
	}

	@computed get rightMenuStates() {
		const {
			selectedKey
		} = this.searchStore;

		if (selectedKey === '1') {
			const {
				loading
			} = this.formStore;

			return [loading];
		} else if (selectedKey === '2') {
			const {
				loading,
				selectedRowKeys
			} = this.tableListStore.tableStore;

			return [loading, loading, selectedRowKeys.length === 0];
		} else {
			const {
				loading,
				selectedRowKeys
			} = this.tableListStore.tableStore;
			return [selectedRowKeys.length === 0];
		}
	}


	@computed get searchConfig() {
		const {
			selectedKey
		} = this.searchStore;

		const config = {
			hasMask:true,
			tabApi: api.getTabs,
			_handleTabChange: this.handleTabClick,
			_handleSearch: this.handleSearch
		};

		if (selectedKey !== '1') {
			Object.assign(config, {
				api: (selectedKey === '2') ? api.getTemplateCondition : api.getRecordCondition,
				linkageFieldName: (selectedKey === '2') ? 'name' : 'title',
				searchType: ['base', 'advanced'],
			});
		} else { //工资单发送
			Object.assign(config, {
				searchType: [],
			})
		}

		return config;
	}

	get detailSearchConfig() {
		return {
			api: api.getRecordDetailCondition,
			advanceHeight: 170,
			linkageFieldName:'lastname',
			_handleSearch: this.handleDetailSearch
		}
	}

	get formConfig() {
		return {
			api: api.getDispatchForm,
			isCustomRender: true,
			hasOrderNumber: true,
		}
	}

	get templateFormConfig() {
		return {
			api: api.getTemplateForm,
			isCustomRender: true,
			mark: 'template',
		}
	}

	get OtherComponents() {
		return {
			excelFile: (item, form) => {
				const {
					excelFile
				} = form.getFormParams();

				if (!excelFile) {
					return (
						<span className='noFile'>{getLabel(384040,'未选择任何文件')}</span>
					)
				} else {
					return (
						<span className='noFile'>{this.uploadList[0] && this.uploadList[0].filename}</span>
					)
				}
			}
		}
	}

	get templateOtherComponents() {
		return {
			dispatchImg: (item, form) => {
				const {
					dispatchImg
				} = form.getFormParams();

				return (
					<span>
							{
								(dispatchImg === '1') && (
									<span className='setting' onClick={this.setDispatchImg}>{getLabel(68,'设置')}</span>
								)
							}
							<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@fp3322`} 
								width={185}
								style={{marginLeft:15}}
								title={getLabel('519673','启用后将在消息中推送图片，默认取设置的推送图片；未设置推送图片时，取系统默认图片。')}
							/>
						</span>
				)
			}
		}
	}


	@computed get tableConfig() {
		const {
			selectedKey
		} = this.searchStore;

		const config = {
			_reRenderColumns: this.reRenderColumns,
			_onOperatesClick: this.onOperatesClick
		};

		if (selectedKey === '2') {
			Object.assign(config, {
				api: api.getTemplateList,
			});
		}
		if (selectedKey === '3') {
			Object.assign(config, {
				api: api.getRecordList,
			});
		};

		return config;
	}

	get detailTableConfig() {
		return {
			api: api.getRecordDetailList
		}
	}

	@computed get dialogConfig() {
		const config = {
			style: {
				width: 600,
				height: 183
			},
			_closeDialog: this.closeDialog,
		};
		if (this.dialogType === 'create') {
			Object.assign(config, {
				title: getLabel(512419, '新建推送模板')
			});
		} else {
			Object.assign(config, {
				title: getLabel(512420, '编辑推送模板')
			});
		}
		return config
	}

	get dispatchImgDialogConfig() {
		return {
			style: {
				width: 600,
				height: 152
			},
			mark: 'dispatchImg',
			title: getLabel(512424, '设置推送图片'),
			_closeDialog: this.closeDispatchImgDialog,
		}
	}

	get payrollSendDetailDialogConfig() {
		return {
			style: {
				width: 850,
				height: 540
			},
			mark: 'payrollSendDetail',
			title: getLabel(512428, '工资单发送详情'),
			_closeDialog: this.closePayrollSendDetailDialog
		}
	}

	get DialogButtons() {
		return [
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@s9fwm8`} type='primary' disabled={this.formStore.loading} onClick={this.saveTemplate}>{getLabel(505564, '保存')}</Button>
		]
	}

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

	get dispatchImgDialogButtons() {
		return [
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@n0y83r`} type='primary' onClick={this.saveDispatchImg}>{getLabel(505564, '保存')}</Button>
		]
	}

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

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

	@computed get isPayrollSendSuccess() {
		const {
			succnum,
			failnum
		} = this.sendResult;

		return (succnum > 0) && (failnum === 0)
	}

	@computed get uploadDispatchImgId() {
		if (this.uploadDispatchImg) {
			const params = {};
			this.uploadDispatchImg.split("?")[1].split("&").map(param => {
				const [key, value] = param.split("=");
				Object.assign(params, {
					[key]: value
				})
			});
			return params.fileid;
		}
	}

	@computed get isPayrollImportSuccess(){
		return (this.errorInfo.length === 0);
	}

	@computed get errorDatas() {
		return this.errorInfo.map((info, index) => {
			return {
				num: (index + 1),
				msg: info.message
			}
		})
	}

	init = () => {
		this.authorityStore.fetchAuthority().then(() => {
			this.resetStoreDatas();

			this.searchStore.setSelectedKey('1');

			this.topStore.init(this.topConfig);
			this.topStore.fetchRightMenu({
				tabIndex: 1
			});

			this.searchStore.init(this.searchConfig);
			this.searchStore.fetchTabs().then(() => {
				this.formStore.init(this.formConfig);
				this.formStore.fetchForm({}, this.handleExcelForm);
			})

		})
	}

	resetStoreDatas = () => {
		this.searchStore.setShowSearchAd(false);
		this.searchStore.setSelectedKey('1');

		this.isProcessing = false;
		this.isSended = false;
	}

	handleExcelForm = (datas) => {
		const {
			condition
		} = datas;

		condition && condition.map((c, i) => c.items.map((item, index) => {
			if (item.domkey[0] === 'excelFile') {
				item.otherParams = {
					...item.otherParams,
					limitType:"xls,xlsx",
					showClearAll: false,
					title: getLabel(125333, '选择文件'),
					showListTop: false,
					getShowListDatas: this.getShowListDatas,
				}
			}

			if (i === 0) {
				item.fieldcol = 18;
			} else {
				item.colon = false;
				Object.assign(item, {
					labelcol: 1,
					fieldcol: 23
				});
			}
		}))

	}

	handleTemplateForm = (datas) => {
		const {
			condition,
			imgId
		} = datas;

		condition && condition.forEach(c => {
			c.items.forEach(item => {
				item.fieldcol = (24 - item.labelcol)

			})
		});
		if (imgId) {
			//变量existDispatchImg存储已经保存的图片地址
			this.existDispatchImg = `/weaver/weaver.file.FileDownload?fileid=${imgId}`; 
			//变量uploadDispatchImg用于图片设置
			this.uploadDispatchImg = `/weaver/weaver.file.FileDownload?fileid=${imgId}`;
		}
	}

	getShowListDatas = (datas) => {
		this.uploadList = datas;
	}

	handleTabClick = () => {
		const {
			selectedKey
		} = this.searchStore;

		this.topStore.fetchRightMenu({
			tabIndex: selectedKey
		});

		this.isSended = false;

		this.searchStore.init(this.searchConfig);

		if (selectedKey === '1') {
			this.formStore = new FormStore(this);
			this.formStore.init(this.formConfig);
			this.formStore.fetchForm({}, this.handleExcelForm);
		}else {
			this.searchStore.fetchSearchForm().then(() => {
				const params = this.searchStore.form.getFormParams();
				this.tableListStore.init(this.tableConfig);
				this.tableListStore.fetchTableList(params);
			})
		}
	}

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

	handleDetailSearch = () => {
		this.detailTableListStore.fetchTableList({
			targetId: this.sendedRecordId,
			...this.detailSearchStore.form.getFormParams()
		});
	}

	doSend = () => {
		const {
			form
		} = this.formStore;

		this.formStore.validateForm(form).then(() => {
			this.errorInfo = [];
			this.isSended = true;
			this.isProcessing = true;
			this.payrollSendingDatas = [];
			this.dataIndex = 1;

			this.topStore.fetchRightMenu({
				tabIndex: '1',
				type: 'executed'
			});

			this.dispatch();
			this.getImportProcessInfo();
		})
	}

	doCreate = () => {
		this.dialogType = 'create';
		this.openTemplateDialog();
	}

	doEdit = (id) => {
		this.dialogType = 'edit';
		this.templateId = id;
		this.openTemplateDialog(id);
	}

	doSave = () => {
		this.saveDefaultTemplate().then(() => {
			this.handleSearch();
		})
	}

	saveDefaultTemplate = () => {
		return new Promise( (resolve, reject) => {
			const checkedId = this.tableListStore.tableStore.datas.find(data => data.isDefaultspan === '1').id

			api.saveDefaultTemplate({
				id: checkedId
			}).then(datas => {
				const {
					status
				} = datas;
				if (status === '1') {
					message.success(getLabel(506152, '保存成功'));
					resolve();
				} else {
					message.warning(datas.message);
					reject();
				}
			})
		} )
	}

	doReturn = () => {
		this.formStore = new FormStore(this);
		this.formStore.init(this.formConfig);
		this.formStore.fetchForm({}, this.handleExcelForm);
		
		this.isSended = false;

		this.topStore.fetchRightMenu({
			tabIndex: '1'
		});
	}

	showLog = () => {
		const {
			selectedKey
		} = this.searchStore;
		this.tableListStore.showLog(selectedKey == '2' ? '20066' : '20078');
	}

	openTemplateDialog = (id) => {
		const params = {};
		if (id) {
			Object.assign(params, {
				id
			});
		}
		this.dialogStore = new DialogStore(this);
		this.dialogStore.init(this.dialogConfig);
		this.dialogStore.openDialog();

		this.formStore = new FormStore(this);
		this.formStore.init(this.templateFormConfig);
		this.formStore.fetchForm(params, this.handleTemplateForm);
	}

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

		this.tableListStore.showConfirm(msg).then(() => {
			this.del({
				ids: id
			});
		})
	}

	doDelete = () => {
		const {
			selectedKey
		} = this.searchStore;

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

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

				this.del({
					ids: selectedRowKeys + ''
				});
			})
		}else if(selectedKey == '3'){
			this.deleteRecordList();
		}
	}

	del = (params) => {
		api.deleteTemplate(params).then(datas => {
			const {
				status
			} = datas;

			if (status === '1') {
				message.success(getLabel(506026, '删除成功！'));
				this.handleSearch();
			} else {
				message.warning(datas.message);
			}
		})
	}

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

			api.dispatch({ 
				importType:'payroll',
				operateType:'add',
				...form.getFormParams()
			}).then(datas => {
				const {status, errorInfo} = datas;

				if (status === '1') {
					if(errorInfo.length > 0) {
						this.errorInfo = errorInfo;
						this.isProcessing = false;

						if (this.interval) {
							clearInterval(this.interval);
							this.interval = '';
						}

						reject();
					}else{
						resolve();
					}
				}else{
					message.warning(datas.message);
					reject();
				}
			})
		} )
	}

	getImportProcessInfo = () => {
		return new Promise( (resolve,reject) => {
			const params = {
				importType:'payroll'
			}

			Object.assign(params, {
				index: this.dataIndex,
			})

			api.getImportProcessLog(params).then(_datas => {
				const {
					datas,
					importStatus,
					index,
					pId,
					status
				} = _datas;

				if (index) {
					this.dataIndex = index;
				}

				if (status === '1') {
					this.payrollSendingDatas = [...this.payrollSendingDatas,...datas];

					this.scrollRef && this.scrollRef.scrollToLast();

					if (['error','over'].includes(importStatus)) {
						this.pId = pId;
						this.isProcessing = false;

						this.getImportResult();
						
						if (this.interval) {
							clearInterval(this.interval);
							this.interval = '';
						}

						resolve();
					}else{
						if (!this.interval) {
							this.interval = setInterval(() => this.getImportProcessInfo(this.dataIndex), 5000);
						}
					}
				}else{
					message.warning(datas.message);
					reject();
				}
			});
		} )
	}

	getImportResult = () => {
		api.getImportResult({
			pId: this.pId
		}).then(_datas => {
			const {
				datas
			} = _datas;

			['succnum', 'failnum'].forEach(val => {
				this.sendResult[val] = datas[val];
			})

			if (datas.sessionkey) {
				this.tableListStore = new TableListStore(this);
				this.tableListStore.tableStore.getDatas(sessionkey, 1);
			}
		})
	}

	reRenderColumns = (columns) => {
		const {
			selectedKey
		} = this.searchStore;

		if (selectedKey === '2') {
			const DEFAULT_TEMPLATE_IMG = "/hrm/hrm_e9/images/payroll.jpg";

			columns.map((column, index) => {
				if (column.dataIndex === 'name') {
					column.render = (text, record) => {
						const {
							name,
							id,
						} = record;

						return (
							<a onClick={() => this.doEdit(id)}>{name}</a>
						)
					}
				}
				if (column.dataIndex === 'imgId') {
					column.render = (text, record) => {
						const {
							imgId
						} = record;

						return (
							<img 
								src={addContentPath(imgId ? `/weaver/weaver.file.FileDownload?fileid=${imgId}` : DEFAULT_TEMPLATE_IMG)} 
								style={{width:127,height:54}}
							/>
						)
					}
				}
				if (column.dataIndex === 'isDefault') {
					column.render = (text, record) => {
						const {
							isDefaultspan
						} = record;

						return <Radio ecId={`${this && this.props && this.props.ecId || ''}_Radio@20r20s@${index}`} checked={isDefaultspan === '1'} />
					}
				}
			})
		} else {
			columns.map(column => {
				if (column.dataIndex === 'creator') {
					column.render = (text, record) => {
						const {
							creator,
							creatorspan
						} = record;

						return (
							<div>
								<WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@tmyipb@${column.dataIndex}`} />
								<a href={`javaScript:openhrm(${creator})`} onClick={e => window.pointerXY(e)} title={creatorspan}>{creatorspan}</a>
							</div>
						)
					}
				}
				if (column.dataIndex === 'detail') {
					column.render = (text, record) => {
						const {
							detail
						} = record;

						return (
							<a  onClick={()=>this.showDetail(detail)} >{getLabel(512427,'查看')}</a>
						)
					}
				}
			})
		}


	}

	handleRadioChange = (event) => {
		if ($(event.target).attr('class') === 'ant-radio-input') {
			const targetIndex = $('.ant-table-tbody .ant-radio-input').index(event.target);

			const {
				datas
			} = this.tableListStore.tableStore;

			datas.map((data, index) => {
				if (targetIndex === index) {
					data.isDefaultspan = '1';
				} else {
					data.isDefaultspan = '0';
				}
			})
		}
	}

	onOperatesClick = (record, rowIndex, operate) => {
		const {
			index
		} = operate, {
			id
		} = record;

		switch (index) {
			case '0':
				this.doEdit(id);
				break;
			case '1':
				this.singleDel(id);
				break;
			case '2':
				this.tableListStore.showLog('20066', id);
				break;
		}
	}

	closeDialog = () => {
		this.existDispatchImg = '';
		this.uploadDispatchImg = '';
	}

	closeDispatchImgDialog = () => {}

	closePayrollSendDetailDialog = () => {

	}

	saveTemplate = () => {
		const {
			form
		} = this.formStore;

		this.formStore.validateForm(form).then(() => {
			const params = {
				imgId: this.uploadDispatchImgId,
				...form.getFormParams()
			};

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

			api.saveTemplateForm(params).then(datas => {
				const {
					status
				} = datas;
				if (status === '1') {
					const {
						form
					} = this.searchStore;

					this.dialogStore.closeDialog();
					this.tableListStore.fetchTableList(form.getFormParams());
				} else {
					message.warning(datas.message);
				}
			})
		})
	}

	saveDispatchImg = () => {
		this.dispatchImgDialogStore.closeDialog();
	}

	setDispatchImg = () => {
		this.uploadDispatchImg = this.uploadDispatchImg ? this.uploadDispatchImg : this.existDispatchImg;
		this.dispatchImgDialogStore.init(this.dispatchImgDialogConfig);
		this.dispatchImgDialogStore.openDialog();
	}

	handleDispatchImgChange = (...args) => {
		this.uploadDispatchImg = args[1] && args[1][0] && args[1][0].imgSrc;
	}

	closeDispatchImg = () => {
		this.uploadDispatchImg = '';
	}

	showDetail = (id) => {
		this.dialogStore = new DialogStore(this);
		
		this.detailSearchStore = new SearchStore(this);
		this.detailSearchStore.init({...this.detailSearchConfig, mark: 'Detail'});

		this.detailTableListStore.init(this.detailTableConfig);
		this.dialogStore.init(this.payrollSendDetailDialogConfig);

		this.detailSearchStore.fetchSearchForm().then(() => {
			this.detailTableListStore.fetchTableList({
				targetId: id,
				...this.detailSearchStore.form.getFormParams()
			});
		});

		this.dialogStore.openDialog();

		this.sendedRecordId = id;
	}

	setScrollRef = (ref) => {
		this.scrollRef = ref;
	}

	@action deleteRecordList = () => {
		const msg = getLabel(83877, '确定要删除吗？');
		this.tableListStore.showConfirm(msg).then(() => {
			api.delRecordList({ids: this.tableListSelectedRowKeys}).then(data => {
				if(data.status == 1){
					this.handleSearch();
				}else{
					message.error(data.message);
				}
			})
		})
	}
}

export const payrollSendingStore = new PayrollSendingStore();