import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaDropdown,
	WeaLocaleProvider,
} from 'ecCom';
import {
	WeaForm,
	WeaTableNew
} from 'comsMobx';
import {
	Button,
} from 'antd';
const getLabel = WeaLocaleProvider.getLabel;
const {
	TableStore
} = WeaTableNew;
const {
	ButtonSelect
} = WeaDropdown;
import Base from './base';

export default class Common extends Base {
	constructor(props) {
		super(props);
		const {
			store,
			api,
			excelstore
		} = props;
		this.specific = store;
		this.api = api;
		this.excelImport = excelstore;
	}

	@observable permission = {
		hasRight: false,
		loading: true,
	}

	/**
	 * @DateTime 2019-05-16
	 * @param    {Function} callback 回调函数
	 * @param    {String}   name     接口名称（非必填，默认为getHasRight）
	 */
	@action callPermissionAPI = (callback, name) => {
		if (!this.api) {
			console && console.error && console.error('api is null');
			return;
		}

		const apiName = name ? name : 'getHasRight';

		if (!this.api[apiName]) {
			console && console.error && console.error('请传入正确的权限接口名称！');
			return;
		};

		this.api[apiName]().then(datas => {
			const {
				hasRight
			} = datas;

			this.permission.hasRight = hasRight;
			this.permission.loading = false;
			if (hasRight) {
				callback && callback();
			}
		}).catch(error => {});
	}

	@observable tConf = [];
	@observable rConf = [];

	/**
	 * @DateTime 2019-05-16
	 * @param    {Object}   params   接口参数（不传参的话，默认为空对象）
	 * @param    {Function} callback 回调函数
	 * @param    {String}   name     接口名称（非必填，默认为getRightMenu）
	 */
	@action callRightMenuAPI = (params = {}, callback, name) => {
		const apiName = name ? name : 'getRightMenu';

		if (!this.api[apiName]) {
			console && console.error && console.error('请传入正确的菜单接口名称！');
			return;
		};

		this.api && this.api[apiName](params).then(datas => {
			const {
				btnMenu = []
			} = datas;

			const {
				tConf,
				rConf
			} = this.convertDatasToTopRightConf(btnMenu);

			this.tConf = tConf;
			this.rConf = rConf;

			callback && callback();
		}, error => {})
	}

	@computed get topButtons() {
		return this.tConf && this.tConf.map((item, index) => {
			const {
				menuFun,
				menuName
			} = item;

			const status = this.specific && this.specific.getButtonStatus && this.specific.getButtonStatus()[index];

			return (
				<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6xqp99@${index}`} 
					type="primary" 
					disabled={status} 
					onClick={() => this.specific && this.specific[menuFun]()}
				>
					{menuName}
				</Button>
			)
		});
	}

	@computed get dropMenuDatas() {
		return this.rConf && this.rConf.map((item, index) => {
			const {
				menuFun,
				menuName,
				menuIcon
			} = item;

			const status = this.specific && this.specific.getButtonStatus && this.specific.getButtonStatus()[index];

			return {
				key: menuFun,
				disabled: status,
				icon: <i className={`${menuIcon}`} />,
				content: menuName,
				onClick: () => this.specific && this.specific[menuFun]()
			}
		});
	}

	/**
	 * @DateTime 2019-05-21
	 * 概述：导入Excel
	 * @param    {String}   name    模版名称
	 * @param    {String}   title   弹框名称
	 * @param    {String}   type    导出类型
	 * @param    {Boolean}   visible 弹框是否可视
	 */
	importExcel = (name, title, type, visible) => {
		const params = [name, title, type, visible];
		const queue = ['setTempletName', 'setImportDialogTitle', 'setImportType', 'setImportDialogVisible'];

		queue.forEach((f, i) => {
			const param = params[i];
			this.excelImport && this.excelImport[f](param);
		});
	}

	//头部中的下拉按钮
	@observable buttonSelect = {
		selectedKey: '0',
		datas: [],
	}

	@action setButtonSelectDatas = (datas) => {
		this.buttonSelect.datas = datas;
	}

	//衍生出头部下拉菜单按钮
	@computed get topButtonSelect() {
		const {
			selectedKey,
			datas
		} = this.buttonSelect;

		if (datas.length === 0) {
			return
		}

		const disabled = this.specific.getButtonSelectStatus();

		return (
			<ButtonSelect ecId={`${this && this.props && this.props.ecId || ''}_ButtonSelect@xvr81v`} 
				datas={datas}
				selectedKey={selectedKey}
				btnProps={{disabled}}
				btnOnClick={key=> this.handleBtnClick(key)}
				menuOnClick={key=>this.handleMenuClick(key)}
			/>
		)
	}

	handleBtnClick = (key) => {
		if (!this.specific) {
			console && console.error && console.error('specific is null');
			return
		}
		if (!this.specific.handleBtnClick) {
			console && console.error && console.error('handleBtnClick is not defined');
			return
		}
		this.specific.handleBtnClick(key);
	}

	handleMenuClick = (datas) => {
		if (!this.specific) {
			console && console.error && console.error('specific is null');
			return
		}
		if (!this.specific.handleBtnClick) {
			console && console.error && console.error('handleMenuClick is not defined');
			return
		}
		this.specific.handleMenuClick(datas);
	}

	//高级搜索中需要联动的字段名称
	linkageFieldName = '';

	//Tab组件的动态物料
	@observable tab = {
		showSearchAd: false,
		form: new WeaForm(),
		selectedKey: '1',
		datas: [],
	}

	/**
	 * @DateTime 2019-05-22
	 * 概述：获取渲染高级搜索内表单所需的数据。
	 * @param    {Object}   params   参数
	 * @param    {Function} callback 回调函数
	 * @param    {String}   name     接口名称（默认为getCondition）
	 */
	@action callSearchConditionAPI = (callback, params = {}, name) => {
		const apiName = name ? name : 'getCondition';

		if (!this.api[apiName]) {
			console && console.error && console.error('请传入正确的高级搜索接口名称！');
			return;
		};

		this.tab.form = new WeaForm();
		this.api[apiName]().then(datas => {
			const {
				condition
			} = datas;

			if (condition.length === 1) {
				condition[0].title = '';
			}

			const {
				form
			} = this.tab;

			form.setCondition(condition);
			callback && callback(form.getFormParams());
		}, error => {})
	}

	//根据高级搜索内linkageFieldName字段的值衍生出基本搜索输入框内的值
	@computed get searchsBaseValue() {
		const {
			form
		} = this.tab;

		return form.getFormParams()[this.linkageFieldName];
	}

	//控制弹框显隐
	@action setShowSearchAd = (bool) => {
		this.tab.showSearchAd = bool;
	}

	//搜索
	@action onSearch = (callback) => {
		if (callback) {
			callback();
		} else {
			const {
				getSearchListParams,
				getSearchListCallback,
				getSearchListName
			} = this.specific;
			this.callSearchListAPI(getSearchListParams(), getSearchListCallback(), getSearchListName());
		}
		this.setShowSearchAd(false);
	}

	//基本输入框触发的事件
	@action onSearchChange = (val) => {
		const {
			form
		} = this.tab;

		this.linkageFieldName && form.updateFields({
			[this.linkageFieldName]: val
		});
	}

	//设置生成页签的数据
	@action setTabDatas = (datas) => {
		this.tab.datas = datas;
	}

	//设置选中页签的KEY值
	@action setSelectedKey = (key, callback) => {
		this.tab.selectedKey = key;
		callback && callback();
	}

	//根据form衍生出高级搜索表单
	@computed get searchsAd() {
		const {
			form
		} = this.tab;
		return <div
			onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.onSearch()}
		>{form.render()}</div>;
	}

	//设置高级搜索中需要联动的字段名称
	setSearchlinkageFieldName = (name) => {
		this.linkageFieldName = name;
	}


	@observable table = {
		comsWeaTableStore: new TableStore(),
	}

	/**
	 * @DateTime 2019-05-15
	 * @param    {Object}   params   接口参数
	 * @param    {Function} callback 回调函数
	 * @param    {String}   name     接口名称（非必填，默认为getRecords）
	 */
	@action callSearchListAPI = (params, callback, name) => {
		const apiName = name ? name : 'getRecords';

		if (!this.api[apiName]) {
			console && console.error && console.error('请传入正确的列表接口名称！');
			return;
		};

		this.api[apiName](params).then(datas => {
			const {
				sessionkey,
			} = datas;
			this.table.comsWeaTableStore = new TableStore();
			this.table.comsWeaTableStore.getDatas(sessionkey, 1);
			callback && callback();
		}, error => {})
	}

	reRenderColumns = (columns) => {
		this.specific && this.specific.reRenderColumns && this.specific.reRenderColumns(columns);
	}

	onOperatesClick = (record, rIndex, operate) => {
		this.specific && this.specific.onOperatesClick && this.specific.onOperatesClick(record, rIndex, operate);
	}

	@observable dialog = {
		visible: false,
		title: '',
	};

	@action openDialog = (title, callback) => {
		this.dialog.visible = true;
		this.dialog.title = title;
		callback && callback();
	}

	@action closeDialog = (callback) => {
		this.dialog.visible = false;
		callback && callback();
	}

	orgTree = {
		id: '',
		type: '',
		pid: '',
		name: ''
	}

	handleOrgTreeNodeClick = (event, ids, nodeids, nodes) => {
		this.convertDatasToIdType(nodes);

		this.specific.handleOrgTreeNodeClick && this.specific.handleOrgTreeNodeClick(event, ids, nodeids, nodes);
	}

	convertDatasToIdType = (nodes) => {
		if (nodes) {
			['id', 'type', 'pid', 'name'].forEach(v => {
				this.orgTree[v] = nodes[0][v];
			});
		}
	}

	@observable triggerRefresh = false;

	@action trigger = (callback) => {
		this.triggerRefresh = !this.triggerRefresh;
		callback && callback();
	}


	@observable monthYear = {
		cKey: '1',
		date: new Date()
	}

	/**
	 * @DateTime 2019-05-22
	 * 概述：切换年月  默认筛选列表数据
	 * @param    {String}   key 点击项的key值
	 */
	@action handleMonthYearClick = (key) => {
		this.monthYear.cKey = key;
		if (!this.specific) {
			return;
		}
		if (this.specific.handleMonthYearClick) {
			this.specific.handleMonthYearClick();
		} else {
			this.callSearchListAPI(this.specific.getSearchListParams());
		}
	}

	/**
	 * @DateTime 2019-05-22
	 * 概述：选择日期 默认筛选列表数据
	 * @param    {Date}   date  日期
	 */
	@action handleDatePickerChange = (date) => {
		this.monthYear.date = date;
		if (!this.specific) {
			return;
		}
		if (this.specific.handleDatePickerChange) {
			this.specific.handleDatePickerChange();
		} else {
			this.callSearchListAPI(this.specific.getSearchListParams());
		}
	}

	//重置年月
	@action resetMonthYear = () => {
		this.monthYear.date = new Date();
		this.handleMonthYearClick('1');
	}

	/**
	 * @DateTime 2019-05-23
	 * 概述：校验表单
	 * @param    {Object}   pack     盛放form的容器
	 * @param    {Function} callback 校验通过的回调函数
	 */
	validateForm = (pack, callback) => {
		this[pack].form.validateForm().then(f => {
			if (f.isValid) {
				callback && callback();
			} else {
				f.showErrors();
				callback && callback();
			}
		})
	}


}