import {
	observable,
	action
} from 'mobx';
import * as mobx from 'mobx'
import * as Api from '../apis/report';
import {
	WeaForm
} from 'comsMobx';
import {
	WeaTableNew
} from 'comsMobx'
import {
	message,
} from 'antd';
import {
	i18n
} from '../public/i18n';
import {
	WeaLocaleProvider
} from 'ecCom';
import AuthorityStore from './domain/authority.js';
const getLabel = WeaLocaleProvider.getLabel;

const {
	TableStore
} = WeaTableNew;

export class HrmPerStatusReport {
	@observable condition1 = [];
	@observable params = {};
	@observable countDatas = [];
	@observable option1 = {};
	@observable option2 = {};
	@observable tabKey = '1';
	@observable interval = '10';
	@observable title = '';
	@observable isIntervalShow = false;
	@observable pathname = 'basicConditionAnalysis';
	@observable deadline = '暂无';
	@observable linkName = '更多';
	chartTitle1 = i18n.label.ranking;
	chartTitle2 = i18n.label.ranking;
	@observable isEchartsShow = true;
	@observable isLeftEchartsShow = true;
	@observable isRightEchartsShow = true;
	@observable visible = false;
	@observable cmd = '';
	@observable tableStore = new TableStore();
	@observable strokeColor = '#FF7F50';
	@observable searchCondition = '';
	@observable href = '';
	@observable ids = [];
	@observable yAxisData = [];
	@observable linkList = '';
	@observable paramsStr = '';
	@observable winWidth = '';
	@observable isApiOneFinished = false;
	@observable isApiTwoFinished = false;

	@observable authorityStore = new AuthorityStore(Api);

	getRight  = ()=>{
		return this.authorityStore.fetchAuthority()
	}

	@action
	getSearchCondition() {
		let params = {
			cmd: 'baseStatus'
		}
		Api.getSearchCondition(params).then((data) => {
			this.condition1 = data.items;
			this.setApiOneFinishedStatus(true);
		});
	}

	setParams(params) {
		this.params = params;
		if (params.dateselect == '6' && (!params.fromdate || !params.enddate)) {
			return false;
		}
		if (params.company == '1' && !params.subcompanyid) {
			return false;
		}
		if (params.company == '2' && !params.departmentid) {
			return false;
		}
		if (params.local == '1' && !params.location) {
			return false;
		}
		this.getData();
	}

	getData(tag) {
		let cmd;
		if (!tag) {
			cmd = this.getWholeCmd(this.pathname, this.tabKey);
		} else {
			if (tag == 'left') cmd = 'JobGroupRpDetail';
			if (tag == 'right') cmd = 'JobActivityRpDetail';
			if (tag == 'departmentStatistics') cmd = 'DepartmentRpAll';
			if (tag == 'postStatistics') cmd = 'JobRpAll';
			if (tag == 'search') cmd = this.cmd;
			this.setVisible(true);
		}

		let p = {
			cmd: cmd,
			...this.params
		};

		if (this.searchCondition) {
			p.keyword = this.searchCondition;
			this.objToStr({ ...this.params,
				keyword: this.searchCondition
			});
		}

		if (this.pathname == 'basicConditionAnalysis' && (this.tabKey == '1' || this.tabKey == '3' || this.tabKey == '7') && !this.nonZeroVerification()) {
			p.agearea = this.interval;
		}

		this.setCmd(cmd);

		this.setHref('/api/hrm/resourceState/downloadExcel?cmd=' + this.getHref() + this.paramsStr);

		this.setStrokeColor(this.getColor());

		this.objToStr(this.params);

		Api.getSearchResult(p).then((data) => {
			if (!data) {
				message.warning(i18n.message.dataNone());
				return false;
			}

			const { status } = data;

			if (status == "-1") {
				const ats = this.authorityStore;
			    ats.hasRight = false;
			    ats.loading = false;
			}

			this.setApiTwoFinishedStatus(true);

			if (data.sessionkey) {
				this.tableStore.getDatas(data.sessionkey, 1);
				return false;
			}

			if (data.countDatas) {
				this.setCountDatas(data.countDatas);
			}

			if (data.linkList) {
				this.linkList = data.linkList;
			}

			if (this.pathname == 'departmentStatistics' && data.option && data.option.yAxis) {
				data.option.yAxis.triggerEvent = true;
				this.setIds(this.getIds(data.option.yAxis.data));
				this.setyAxisData(this.getNewYAxisData(data.option.yAxis.data));
				data.option.yAxis.data = this.yAxisData;
			}

			if (data.option && data.option.series && data.option.series[0].data && data.option.series[0].data.length > 0) {
				if (data.option.xAxis && data.option.yAxis && data.option.series[0].type == 'bar') {
					data.option.series[0].barWidth = this.setBarWidth(data.option.series[0].data);
					data.option.series[0].itemStyle = this.getItemStyle();
					data.option.tooltip = {};
					data.option.xAxis.splitLine = {
						show: false
					};
					data.option.yAxis.axisLabel = this.getAxisLabel();
					data.option.yAxis.axisPointer = this.getAxisPointer();
				}
				if (data.option.series[0].type == 'pie') {
					let datas = data.option.series[0].data;
					for (let i = 0; i < datas.length; i++) {
						data.option.series[0].data[i].label = this.getLabel();
					}
					data.option.tooltip = this.getToolTipForPieChart();
					data.option.series[0].selectedOffset = 0;
					data.option.legend.selectedMode = false;
				}
				this.setOption(data.option, '1');
				this.setEchartsShowStatus(true);
			} else {
				this.setEchartsShowStatus(false);
			}

			if (data.optionX && data.optionX.series && data.optionX.xAxis && data.optionX.yAxis && data.optionX.series[0].data && data.optionX.series[0].data.length > 0) {
				data.optionX.series[0].barWidth = this.setBarWidth(data.optionX.series[0].data);
				data.optionX.series[0].itemStyle = this.getItemStyle();
				data.optionX.tooltip = {};
				data.optionX.xAxis.splitLine = {
					show: false
				};
				data.optionX.yAxis.axisLabel = this.getAxisLabel();
				data.optionX.yAxis.axisPointer = this.getAxisPointer();
				this.setLeftEchartsShowStatus(true);
				this.setOption(data.optionX, '1');
			} else {
				this.setLeftEchartsShowStatus(false);
			}

			if (data.optionY && data.optionY.series && data.optionY.xAxis && data.optionY.yAxis && data.optionY.series[0].data && data.optionY.series[0].data.length > 0) {
				data.optionY.series[0].barWidth = this.setBarWidth(data.optionY.series[0].data);
				data.optionY.series[0].itemStyle = this.getItemStyle();
				data.optionY.tooltip = {};
				data.optionY.xAxis.splitLine = {
					show: false
				};
				data.optionY.yAxis.axisLabel = this.getAxisLabel();
				data.optionY.yAxis.axisPointer = this.getAxisPointer();
				this.setRightEchartsShowStatus(true);
				this.setOption(data.optionY, '2');
			} else {
				this.setRightEchartsShowStatus(false);
			}

			if (data.title && data.title.foottitle) {
				this.setDeadLine(data.title.foottitle);
			}

			if (data.title && data.title.btn) {
				this.setLinkName(data.title.btn);
			}

			if (data.title && data.title.title) {
				this.setChartTitle(data.title.title, '1');
			}

			if (data.title && data.title.leftTitle) {
				this.setChartTitle(data.title.leftTitle, '1');
			}

			if (data.title && data.title.rightTitle) {
				this.setChartTitle(data.title.rightTitle, '2');
			}
		});
	}

	setBarWidth(datas) {
		let len = datas.length;
		switch (len) {
			case 1:
				return '30%';
			case 2:
				return '40%';
			case 3:
				return '50%';
			case 4:
				return '60%';
			default:
				return '80%';
		}
	}

	nonZeroVerification() {
		if (this.tabKey == '1' && this.interval < 0) {
			message.warning(getLabel('386441', "年龄区间不能小于0！"));
			return false;
		}
		if (this.tabKey == '3' && this.interval < 0) {
			message.warning(getLabel('386442', "工龄区间不能小于0！"));
			return false;
		}
		if (this.tabKey == '7' && this.interval < 0) {
			message.warning(getLabel('386443', "职级区间不能小于0！"));
			return false;
		}
	}

	getBasicCmd(key) {
		switch (key) {
			case '1':
				return 'AgeRp';
			case '2':
				return 'SexRp';
			case '3':
				return 'SeniorityRp';
			case '4':
				return 'EduRp';
			case '5':
				return 'WedlockRp';
			case '6':
				return 'JobCallRp';
			case '7':
				return 'JobLevelRp';
			case '10':
				return 'UserKindRp';
			case '11':
				return 'StatusRp';
			case '12':
				return 'SecLevelRp';
		}
	}

	getWholeCmd(pathname, key) {
		switch (pathname) {
			case 'basicConditionAnalysis':
				return this.getBasicCmd(key);
			case 'departmentStatistics':
				return 'DepartmentRp';
			case 'postStatistics':
				return 'JobRp';
			case 'jobStatusStatistics':
				return 'JobActivityAndGroupRp';
		}
	}

	getChartTitle() {
		switch (this.cmd) {
			case 'DepartmentRpAll':
				return getLabel('386444', "人数最多的部门排名");
			case 'JobRpAll':
				return getLabel('386445', "人数最多的岗位排名");
			case 'JobGroupRpDetail':
				return getLabel('386446', "人数最多的职务类别排名");
			case 'JobActivityRpDetail':
				return getLabel('386447', "人数最多的职务排名");
		}
	}

	getTabName() {
		switch (this.tabKey) {
			case '1':
				return getLabel('386388', "年龄状况");
			case '2':
				return getLabel('386389', "性别状况");
			case '3':
				return getLabel('386390', "工龄状况");
			case '4':
				return getLabel('386391', "学历状况");
			case '5':
				return getLabel('469', "婚姻状况");
			case '6':
				return getLabel('386392', "职称统计");
			case '7':
				return getLabel('386393', "职级统计");
			case '10':
				return getLabel('804', "用工性质");
			case '11':
				return getLabel('386394', "状态统计");
			case '12':
				return getLabel('683', "安全级别");
		}
	}

	setKey(key) {
		this.tabKey = key;
		if (key == '1' || key == '3' || key == '7') {
			this.setIntervalShow(true);
		} else {
			this.setIntervalShow(false);
		}
		if (key == '1') this.setGap('10');
		if (key == '3') this.setGap('2');
		if (key == '7') this.setGap('5');
	}


	getLabel() {
		return ({
			normal: {
				formatter: [
					'{b} | {c} | {d}%',
				].join('\n'),
			}
		})
	}

	getItemStyle() {
		return ({
			normal: {
				color: '#6FBCEA'
			}
		})
	}

	getAxisPointer() {
		return ({
			formatter: function(params) {
				return params.value;
			}
		})
	}

	getAxisLabel() {
		var that = this;
		return ({
			formatter: function(value) {
				let len = that.getByteLen(value);
				if (len > 12) {
					return that.getCutStr(value, 12) + '...';
				} else {
					return value;
				}

			}
		})
	}

	getToolTipForPieChart() {
		return ({
			trigger: 'item',
			formatter: "{b} : {c} ({d}%)"
		})
	}

	getByteLen(val) {
		var len = 0;
		for (var i = 0; i < val.length; i++) {
			var a = val.charAt(i);
			if (a.match(/[^\x00-\xff]/ig) != null) {
				len += 2;
			} else {
				len += 1;
			}
		}
		return len;
	}

	getCutStr(value, len) {
		let arr = value.split('');
		let cutArr = [];
		let count = 0;
		for (let i = 0; i < arr.length; i++) {
			if (this.checkIsChinese(arr[i]) && count < len) {
				cutArr.push(arr[i]);
				count += 2;
			}
			if (!this.checkIsChinese(arr[i]) && count < len) {
				cutArr.push(arr[i]);
				count += 1;
			}
		}
		return cutArr.join('');
	}

	checkIsChinese(val) {　　
		let reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");　　
		if (reg.test(val)) return true
	}

	pathToTitle() {
		switch (this.pathname) {
			case 'basicConditionAnalysis':
				this.setTitle(getLabel('382087', "基本状况分析"));
				break;
			case 'departmentStatistics':
				this.setTitle(getLabel('382094', "部门人数统计"));
				break;
			case 'postStatistics':
				this.setTitle(getLabel('382095', "岗位人数统计"));
				break;
			case 'jobStatusStatistics':
				this.setTitle(getLabel('382096', "职务状况统计"));
				break;
			default:
				this.setTitle(getLabel('386448', "数据统计与分析"));
		}
	}

	getColor() {
		switch (this.cmd) {
			case 'DepartmentRpAll':
				return '#7DC756';
			case 'JobRpAll':
				return '#AC7CFF';
			default:
				return '#FF7F50';
		}
	}

	getHref() {
		switch (this.cmd) {
			case 'DepartmentRpAll':
				return 'DepartmentRp';
			case 'JobRpAll':
				return 'JobRp';
			case 'JobGroupRpDetail':
				return 'JobGroupRp';
			case 'JobActivityRpDetail':
				return 'JobActivityRp';
		}
	}

	isEmptyObject(obj) {
		for (let key in obj) {
			return false;
		}
		return true;
	}

	objToStr(obj) {
		let str = '';
		if (!this.isEmptyObject(obj)) {
			for (let key in obj) {
				str = str + '&' + key + '=' + obj[key];
			}
		}

		this.setParamsStr(str);
	}

	getIds(datas) {
		let arr = [];
		if (!(datas instanceof Array)) {
			return false;
		}
		for (let i = 0; i < datas.length; i++) {
			let id = datas[i].substring(datas[i].indexOf('{') + 1, datas[i].indexOf('}')).split(':')[1];
			arr.push(id);
		}

		return arr;
	}

	getNewYAxisData(datas) {
		let arr = [];
		if (!(datas instanceof Array)) {
			return false;
		}
		for (let i = 0; i < datas.length; i++) {
			let data = datas[i].split('{')[0].replace(/\s+/g, "");
			arr.push(data);
		}

		return arr;
	}

	getCurWindowWidth() {
		let that = this;

		window.onresize = function() {
			if (window.innerWidth) {
				that.setWinWidth(window.innerWidth);
			} else if ((document.body) && (document.body.clientWidth)) {
				that.setWinWidth(document.body.clientWidth);
			}
		}
	}

	setIntervalShow(bool) {
		this.isIntervalShow = bool;
	}

	setCountDatas(countDatas) {
		this.countDatas = countDatas;
	}

	setOption(option, arg) {
		if (arg == '1') this.option1 = option;
		if (arg == '2') this.option2 = option;
	}

	setGap(interval) {
		this.interval = interval;
	}

	setTitle(title) {
		this.title = title;
	}

	setDeadLine(deadline) {
		this.deadline = deadline;
	}

	setLinkName(linkName) {
		this.linkName = linkName;
	}

	setChartTitle(chartTitle, arg) {
		if (arg == '1') this.chartTitle1 = chartTitle;
		if (arg == '2') this.chartTitle2 = chartTitle;
	}

	setEchartsShowStatus(bool) {
		this.isEchartsShow = bool;
	}

	setLeftEchartsShowStatus(bool) {
		this.isLeftEchartsShow = bool;
	}

	setRightEchartsShowStatus(bool) {
		this.isRightEchartsShow = bool;
	}

	setPathName(pathname) {
		this.pathname = pathname;
	}

	setVisible(bool) {
		this.visible = bool;
		if (!bool) {
			this.searchConditionReset();
		}
	}

	setCmd(cmd) {
		this.cmd = cmd;
	}

	setStrokeColor(color) {
		this.strokeColor = color;
	}

	setSearchCondition(condition) {
		this.searchCondition = condition;
	}

	searchConditionReset() {
		this.searchCondition = '';
	}

	setHref(href) {
		this.href = href;
	}

	setIds(ids) {
		this.ids = ids;
	}

	setyAxisData(yAxisData) {
		this.yAxisData = yAxisData;
	}

	setParamsStr(str) {
		this.paramsStr = str;
	}

	setApiOneFinishedStatus(bool) {
		this.isApiOneFinished = bool;
	}

	setApiTwoFinishedStatus(bool) {
		this.isApiTwoFinished = bool;
	}

	setWinWidth(winWidth) {
		this.winWidth = winWidth;
	}

	optionReset() {
		this.option1 = {};
	}

	conditionReset() {
		this.condition1 = [];
	}

	paramReset() {
		this.params = {};
	}

	apiFinishedStatusReset() {
		this.isApiOneFinished = false;
		this.isApiTwoFinished = false;
	}

	tabKeyReset() {
		this.tabKey = '1';
	}

}