import {
	observable,
	action,
	computed,
	extendObservable
} from 'mobx';

import {
	message
} from 'antd'

import {
	WeaHelpfulTip
} from 'ecCom';

import {isEmpty} from "lodash";

import {
	i18n
} from '../public/i18n';

import * as mobx from 'mobx';
import * as Api from '../apis/cardItemSet';
const toJS = mobx.toJS;

export class HrmCardItemSet {
	@observable weaTopTitle = i18n.module.staffCardDisplay();
	@observable btnMenu = [];
	@observable selectedKey = '0';
	@observable authorized = false;
	@observable loading = true;
	@observable tabOneRelatedData = {
		data: [],
		loading: true
	};
	@observable tabTwoRelatedData = {
		datas: [], //datas受控
		columns: [],
		loading: true,
		selectedData: {}, //selectedData受控
		authorized: false,
	};

	@computed get cardItemsLength() {
		let arr = [];
		for (let i = 0; i < this.tabOneRelatedData.data.length; i++) {
			let cardItemsLength = 0;
			this.tabOneRelatedData.data[i].children.map(s => {
				if (s.children.length > 0) {
					cardItemsLength += s.children.length;
				} else {
					cardItemsLength += 1;
				}
			});
			arr.push(cardItemsLength);
		}
		return arr;
	}

	@computed get menu() {
		let topMenu = [];
		let rightMenu = [];
		this.btnMenu.map(item => {
			(item.isTop == '1' || item.isBatch == '1') && topMenu.push(item);
			!item.isBatch && rightMenu.push(item);
		});
		return {
			topMenu,
			rightMenu
		}
	}

	@computed get checkedItems() {
		let arr = [];
		toJS(this.tabOneRelatedData.data).map(f => {
			let fArr = [];
			if (f.value) {
				fArr.push(f.id);
				f.children.map(s => {
					if (s.value) {
						fArr.push(
							s.id,
						)
						s.children.map(t => {
							t.value && fArr.push(
								t.id
							)
						})
					}
				});
				arr.push(fArr.toString());
			}
		});
		return arr.toString();
	}

	@computed get tabTwoSaveParams() {
		let datas = this.tabTwoRelatedData.datas;
		let selectedData = this.tabTwoRelatedData.selectedData.isused;

		let params = this.arrToJson(toJS(datas), toJS(selectedData));
		params.rownum = datas.length;

		return params;
	}

	@action
	getRight() {
		this.loading = true;
		Api.getRight().then(res => {
			let {
				api_status,
				btnMenu,
				hasRight
			} = res;
			if (api_status) {
				if (hasRight) {
					this.setRight(true);
					btnMenu !== undefined && this.setBtnMenu(btnMenu);
				}
				this.loading = false;
			} else {
				message.error(res.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	loadTabOneRelatedData() {
		this.tabOneRelatedData.loading = true;
		Promise.all(
			[
				Api.getCardItemsData(),
			]
		).then(res => {
			res.map((rs, index) => {
				if (index == 0) {
					let {
						api_status,
						data
					} = rs;

					if (api_status) {
						data !== undefined && extendObservable(this.tabOneRelatedData, {
							data: data
						});
						extendObservable(this.tabOneRelatedData, {
							loading: false
						});
					} else {
						message.error(rs.message);
					}
				}
			});
		}).catch(error => {
			message.error(error);
		});
	}

	loadTabTwoRelatedData() {
		this.tabTwoRelatedData.loading = true;
		Promise.all(
			[
				Api.getTableEdit(),
			]
		).then(res => {
			res.map((rs, index) => {
				if (index == 0) {
					let {
						api_status,
						datas,
						columns,
						selectedData
					} = rs;

					if (api_status) {
						if (!columns || !datas) {
							this.tabTwoRelatedData.authorized = false;
							return;
						}
						this.tabTwoRelatedData.authorized = true;
						columns.map((c, index) => {
							if (c.key === 'itemurl') {
								c.title = <span>
					                        <span>{c.title}</span>
					                        <span style={{marginLeft: 10}}>
						                        <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@4vdvfp@${index}`} title='自定义页面链接地址可以为外网地址，如：http://www.baidu.com
								            		也可以是内部地址，如：/test.jsp，可以带上参数传参，像这样：/test.jsp?a=1&b=2
								            		也可以写占位符{#id}传人员id，像这样：/test.jsp?a=1&b={#id}&mypara2={#id}
								            		即使不写占位符，默认也会收到1个固定的参数：hrmResourceID=人员id'/>
								            </span>
							            </span>
							} else if (c.key === 'itemnum') {
								c.title = <span>
					                        <span>{c.title}</span>
					                        <span style={{marginLeft: 10}}>
						                        <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@wotuuk@${index}`} title='填写类的全路径例如：com.engine.hrm.cmd.hrmcarditem.GetTabNumDemoCmd,类中包含execute方法返回int型数据。
								            		填写不正确的路径并启用，对应tab页title将会出现（error）字样。'/>
								            </span>
							           </span>
							}
						});

						extendObservable(this.tabTwoRelatedData, {
							datas: datas,
							columns: columns
						});

						selectedData && extendObservable(this.tabTwoRelatedData, {
							selectedData: selectedData
						});
						extendObservable(this.tabTwoRelatedData, {
							loading: false
						});
					} else {
						message.error(rs.message);
					}
				}
			});
		}).catch(error => {
			message.error(error);
		});
	}

	cardItemsSettingSave() {
		let params = {
			data: toJS(this.checkedItems)
		}
		Api.cardItemsSettingSave(params).then(res => {
			let {
				api_status,
				sign,
			} = res;

			if (api_status) {
				if (sign == '1') {
					res.message && message.success(res.message);
				} else {
					res.message && message.warning(res.message);
				}
			} else {
				message.error(res.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	userDefineCardItemSave() {
		if (!this.verify(toJS(this.tabTwoRelatedData.datas))) return;
		let params = this.tabTwoSaveParams;

		Api.userDefineCardItemSave(params).then(res => {
			let {
				api_status,
				sign,
			} = res;

			if (api_status) {
				if (sign == '1') {
					res.message && message.success(res.message);
				} else {
					res.message && message.warning(res.message);
				}
			} else {
				message.error(res.message);
			}
		}).catch(error => {
			message.error(error);
		});
	}

	arrToJson(arr, rows) {
		let json = {};

		const _rows = isEmpty(arr) ? [] : rows;

		_rows && _rows.map(index => {
			arr[index].isused = '1';
		});
		arr.map((item, index) => {
			if (!item.isused) item.isused = '0';
			for (let key in item) {
				json[key + '_' + index] = item[key];
			}
		})

		return json;
	}

	verify(arr) {
		for (let i = 0; i < arr.length; i++) {
			if (!arr[i].itemname || !arr[i].itemurl) {
				const temp = i18n.message.requiredInfoIsNotFull().replace('{param}', i + 1);
				message.warning(temp);
				return false;
			}
		}
		return true;
	}

	setRight(right) {
		this.authorized = right;
	}

	setBtnMenu(btnMenu) {
		this.btnMenu = btnMenu;
	}

	setSelectedKey(key) {
		this.selectedKey = key;
	}

	setCardItemsData(data) {
		this.data = data;
	}

	setEnableRows(e) {
		extendObservable(this.tabTwoRelatedData, {
			selectedData: {
				isused: e
			}
		});
	}

	setTableEditDatas(e) {
		e.map(item => {
			for (let key in item) {
				if (key == 'undefined') {
					delete item[key];
				}
				if (!item['isused']) {
					item['isused'] = '';
				}
			}
		});
		extendObservable(this.tabTwoRelatedData, {
			datas: e
		});
	}

	mobxDataReset() {
		this.selectedKey = '0';
		extendObservable(this.tabOneRelatedData, {
			loading: true
		});
	}
}