import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaInput,
	WeaLocaleProvider,
} from 'ecCom';
import {
	message,
	Button
} from 'antd';
import {
	AuthorityStore,
	TopStore,
	SearchStore,
	RadioGroupStore,
	TableListStore,
	DialogStore,
} from '../public/valhalla/stores/index.js';
import * as api from '../apis/archiveLogView.js';
import {isEmpty} from "lodash";
import moment from "moment";
const getLabel = WeaLocaleProvider.getLabel;

class ArchiveLogViewStore {
	lastName = "";
	loginId = "";

	@observable authorityStore = new AuthorityStore(api.getHasRight);
	@observable topStore = new TopStore(this);
	@observable searchStore = new SearchStore(this);
	@observable radioGroupStore = new RadioGroupStore(api.getSearchCondition, this);
	@observable tableListStore = new TableListStore(this);
	@observable dialogStore = new DialogStore(this);

	@observable isLogDetail = true;
	@observable excelLoading = false;
	@observable columns = [];
	@observable datas = [];
	@observable logDetail = [];

	get topConfig() {
		return {
			api: api.getRightMenu,
			title: getLabel(514128, "归档日志查看"),
		}
	}

	get searchConfig() {
		return {
			searchType: [],
			datas: [{
				key: "0",
				title: getLabel(514109, "登录日志")
			}, {
				key: "1",
				title: getLabel(514110, "操作日志")
			}],
			_handleTabChange: this.handleTabChange
		}
	}

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

		return {
			_reRenderColumns: this.reRenderColumns,
			_onOperatesClick: this.onOperatesClick,
			api: (selectedKey === "0") ? api.getLoginLogList : api.getOperateLogList,
		}
	}

	get dialogConfig() {
		return {
			style: {
				width: 600,
				height: 380
			},
			_closeDialog: this.closeDialog
		}
	}

	get DialogButtons() {
		return this.isLogDetail ?
			[<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@zdxeqb`} type="primary" onClick={this.viewOriginParams}>{getLabel(385866,"查看原始参数")}</Button>] :
			[<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@288vya`} onClick={this.back}>{getLabel(1290,"返回")}</Button>]
	}

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

	get rightMenuStates() {
		return [this.excelLoading]
	}

	initPage = () => {
		this.authorityStore.fetchAuthority().then(() => { //获取页面权限
			this.resetStoreDatas();

			this.topStore.init(this.topConfig);
			this.topStore.fetchRightMenu(); //获取右键菜单

			this.searchStore.init(this.searchConfig); //初始化tab

			this.radioGroupStore.fetchRadioGroupConfig().then(() => { //获取搜索条件
				this.search(); //搜索
			})
		})
	}

	processRadioGroupConfig = (items) => {
		return [{
			label: getLabel(25034, "姓名"),
			com: (<WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@z3f2dv`} 
				onChange={name=>{
				this.lastName=name;
			}}/>),
			labelcol: 5,
			fieldcol: 19,
		}, {
			label: getLabel(514111, "登录名"),
			com: (<WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@34l5jq`} onChange={id=>{
				this.loginId = id;
			}}/>),
			labelcol: 5,
			fieldcol: 19,
		}, ...items.map(item => {
			item.labelcol = 5;
			item.fieldcol = 19;
			return item;
		}), {
			com: (
				<div>
					<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@hzuywp`} type="primary" onClick={this.search}>{getLabel(82529,"搜索")}</Button>
					<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0lu4n7`} onClick={this.reset}>{getLabel(27088,"重置")}</Button>
				</div>
			),
			labelcol: 0,
			fieldcol: 24,
		}]
	}

	reRenderColumns = (columns) => {
		columns.map(column => {
			if (['description', 'newValues'].includes(column.dataIndex)) {
				column.render = (text, record) => {
					const {
						operateType
					} = record;
					return (
						<a onClick={() => this.view(record)}>{(operateType !== "DELETE") ? getLabel(33564,"查看"): ""}</a>
					)
				}
			}
		})
	}

	onOperatesClick = () => {

	}

	search = () => {
		const rgParams = this.radioGroupStore.radioGroupParams;
		if (rgParams.dateScope === "6") {
			if (["startDate", "endDate"].some(key => !rgParams[key])) {
				message.warning(getLabel(514075,"请指定日期范围"));
				return;
			}
		}
		const params = {
			...this.radioGroupStore.radioGroupParams,
			lastName: this.lastName,
			loginId: this.loginId
		};
		if (!params.dateScope) {
			Object.assign(params, {
				dateScope: "1",
				operateType: "1",
			})
		}
		this.tableListStore.init(this.tableConfig);
		this.tableListStore.fetchTableList(params);
	}

	reset = () => {
		this.lastName = "";
		this.loginId = "";

		this.radioGroupStore.fetchRadioGroupConfig().then(() => { //获取搜索条件
			this.search(); //搜索
		})
	}

	handleTabChange = () => {
		this.reset();
		this.isLogDetail = true;
	}

	resetStoreDatas = () => {
		this.searchStore.setSelectedKey("0");
	}

	view = (record) => {
		const {
			operateType,
			operateTypespan,
			logsmalltypelabelnamespan,
			descriptionspan,
			mainId,

			targetNamespan,
			paramsspan
		} = record;

		if (operateType === "DELETE") {//操作类型为删除
			return
		}

		const {
			selectedKey
		} = this.searchStore;

		this.originParamsStr = paramsspan;

		let title = `${operateTypespan} - ${logsmalltypelabelnamespan}`;
		if (targetNamespan) {
			title = `${title}: ${targetNamespan}`;
		}

		if (selectedKey === "0") {
			this.logDetail = [descriptionspan]
		} else {
			this.trans(record.id).then(datas => {
				this.logDetail = this.getOperateLogDetail(record, datas);//操作日志
			})
		}

		mainId && this.viewdetail(mainId,record.id);

		this.dialogStore.init(this.dialogConfig);
		this.dialogStore.setTitle(title);
		this.dialogStore.openDialog();
	}

	getOperateLogDetail = (record, datas) => {
		const {
			oldValuesspan,
			newValuesspan,
			operateType,
			logsmalltypelabelnamespan,
			logtype,
			logsmalltype,
			descriptionspan,
		} = record;

		const detail = [];

		if (operateType === "SELECT") {
			detail.push(logsmalltypelabelnamespan);
		}

		const oldValues = datas.oldValues || oldValuesspan && !isEmpty(JSON.parse(oldValuesspan)) && JSON.parse(oldValuesspan),
			newValues = datas.newValues || newValuesspan && !isEmpty(JSON.parse(newValuesspan)) && JSON.parse(newValuesspan);

		newValues && Object.keys(newValues).forEach((key, index) => {
			let item;
			if (oldValues) {
				item = `${index+1}. ${key ? `[${key}]: ` : ""} ${getLabel(513995,"由 {params1} 修改为 {params2} ").replace("{params1}",oldValues[key]).replace("{params2}",newValues[key])}`;
			} else {
				item = `${index+1}. ${key ? `[${key}]: ` : ""} ${newValues[key]}`;
			}
			detail.push(item)
		});

		if (logtype === "19" && logsmalltype === "11") {
			detail.push(descriptionspan);
		}

		return detail;
	}
	viewOriginParams = () => {
		this.isLogDetail = false;

		const obj = this.originParamsStr && JSON.parse(this.originParamsStr);

		const arr = [];
		obj && Object.keys(obj).forEach(key => {
			const item = `"${key}": "${obj[key]}"`;
			arr.push(item);
		})

		this.originParams = arr;

	}

	back = () => {
		this.isLogDetail = true;
	}

	closeDialog = () => {
		this.isLogDetail = true;
		this.datas = [];
	}

	excel = () => {
		const params = {
			...this.radioGroupStore.radioGroupParams,
			lastName: this.lastName,
			loginId: this.loginId,
			tab: parseInt(this.searchStore.selectedKey) + 1,
		};

		this.excelLoading = true;

		api.exportExcelLog(params).then(datas => {
			const {
				status
			} = datas;
			if (status === "1") {
				const index = parseInt(this.searchStore.selectedKey);
				const title = `${this.topConfig.title}-${this.searchConfig.datas[index].title}-${this.getDate()}`;
				this.tableListStore.tableStore.exportAll("", title);
			} else {
				message.warning(datas.message);
			}
			this.excelLoading = false;
		}).catch(() => {
			this.excelLoading = false;
		})
	}

	viewdetail = (belongMainId,id) => {
		const params = {
			belongMainId,
			id,
		};
		api.viewdetail(params).then(datas => {
			if (datas) {
				const {
					columns,
					data
				} = datas;

				this.columns = columns.map(c => c.map(item => {
					item.width = 80;
					return item;
				}));
				this.datas = data;
			}
		})
	}

	getDate = () => {
		return moment().format('YYYYMMDDHHmmss');
	}

	trans = (id) => {
		return new Promise( (resolve,reject) => {
			const params = {id,isArchiveLog:1};

			api.trans(params).then(datas => {
				const {info, status} = datas;

				if (status === "1") {
					resolve(info)
				}else{
					message.warning(datas.message);
					reject();
				}
			}).catch(()=>{
				reject();
			})
		} )
	}
}

export const archiveLogViewStore = new ArchiveLogViewStore();