import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaSelect,
	WeaInputSearch,
	WeaLocaleProvider,
} from 'ecCom';
import {
	WeaForm,
	WeaTableNew
} from 'comsMobx';
import {
	message,
	Button,
} from 'antd';
import {isEmpty} from "lodash";
import Common from './common';
import * as api from '../apis/addressbookPlus';
import * as api2 from '../apis/addressbook';
import classnames from 'classnames';
const getLabel = WeaLocaleProvider.getLabel;
const {
	TableStore
} = WeaTableNew;

export default class HrmAddressBookPlus {
	constructor(props) {
		this.pstore = props;
	}

	//实例化Common类
	@observable share = new Common({
		store: this,
		api
	});

	//***********************左侧页签**************************
	@observable leftTab = {
		selectedKey: '0'
	};

	get leftTabDatas() {
		return {
			datas: [{
				key: '0',
				title: getLabel(25332, '组织结构')
			}, {
				key: '1',
				title: getLabel(81554, '常用组')
			}],
			keyParam: 'key',
			onChange: key => this.clickLeftTab(key),
		}
	}

	@action clickLeftTab = (key) => {
		this.leftTab.selectedKey = key;
		this.pstore && this.pstore.getSearchList();
	}

	handleOrgTreeNodeClick = () => {
		const {
			id
		} = this.share.orgTree;
		const params = {
			groupId: id
		};
		if (parseInt(id) > 0) {
			if (this.pstore) {
				this.pstore.form.resetConditionValue();
				this.pstore.updateShowSearchAd(false);
				this.pstore.tabkey = 'default_3';
				this.pstore.getSearchList(params);
			}
			
		}
	}

	//***********************常用组树**************************
	ORGTREE = {
		...this.share.TREE_ORG,
		dataUrl: '/api/hrm/search/getGroupTree'
	}


	//***********************列表**************************
	synclogDetail = '';

	get TABLE(){
		return {
			...this.share.TABLE,
			scroll:{
				y: 350
			}
		}
	}
	/**
	 * @DateTime 2019-05-15
	 * @param    {Array}   columns 生成列表栏目的数据
	 */
	reRenderColumns = (columns) => {
		const clone = this;
		columns.map(c => {
			if (c.dataIndex === 'operateDesc') {
				c.render = function(text, record) {
					const {
						operateDescspan
					} = record;
					let id, sql;
					if (clone.operateType === 'excel') {
						const arr = operateDescspan.split('--');
						id = arr[0];
						sql = arr[1];
					}
					const label = (clone.operateType === 'sync') ? getLabel(130277, '查看') : id;
					return <a className='hrm-log-query' onClick={()=>clone.viewSyncDetail((clone.operateType === 'sync') ? operateDescspan:sql)}>{label}</a>
				}
			}
		});
	}

	viewSyncDetail = (operateDesc) => {
		this.synclogDetail = operateDesc;
		this.openSyncDetailDialog();
	}

	/**
	 * @DateTime 2019-05-15
	 * @param    {Object}   record  行数据
	 * @param    {String}   rIndex  行索引
	 * @param    {Object}   operate 行功能
	 */
	onOperatesClick = (record, rIndex, operate) => {

	}

	recordExport = (count) => {
		const params = {
			count
		}
		api.recordExport(params).then().catch(err => message.error(err))
	}

	//***********************弹框**************************
	//显示列定制
	DIALOG_COLSET = {
		...this.share.DIALOG_HRM,
		icon: 'icon-coms-Flow-setting',
		onCancel: this.closeColsetDialog,
		style: {
			width: 720,
			height: 500
		}
	}
	//同步日志、导出日志
	DIALOG_SYNCLOG = {
		...this.share.DIALOG_HRM,
		icon: 'icon-coms-Flow-setting',
		onCancel: this.closeSynclogDialog,
		style: {
			width: 700,
			height: 480
		}
	}
	//同步日志详情
	DIALOG_SYNCLOG_DETAIL = {
		...this.share.DIALOG_HRM,
		icon: 'icon-coms-Flow-setting',
		onCancel: this.closeSyncDetailDialog,
		style: {
			width: 650,
			height: 450
		}
	}

	@computed get colsetDialogTitle() {
		if (this.isColsetDialog) {
			return getLabel('32535', '显示列定制');
		} else {
			return getLabel('534085','默认排序设置') ;
		}
	}

	@computed get synclogTitle() {
		if (this.operateType === 'sync') {
			return getLabel('508025', '同步日志');
		} else {
			return getLabel('506976', '日志');
		}
	}

	get syncDetailTitle() {
		return `${getLabel(506968,'同步')}-${getLabel(1515,'通讯录')}: ${getLabel(508022,'显示列')}`
	}

	@observable colsetDialog = {
		visible: false,
		loading: true,
	}

	@observable synclogDialog = {
		visible: false,
	}

	@observable syncDetailDialog = {
		visible: false,
	}

	@observable operateType = '';

	//是否是显示列定制弹框（用来区分显示列定制弹框和默认排序设置弹框）
	@observable isColsetDialog = true;

	/**
	 * @DateTime 2019-06-04
	 * 概述：打开显示列定制或默认排序设置弹框
	 * @param    {[String]}   type [标识]
	 */
	@action openColsetDialog = (type) => {
		this.colsetDialog.visible = true;
		this.isColsetDialog = (type === 'colset');
		if (type === 'colset') {
			
		} else {
			this.callTransferApi();
		}
		this.callSyncRightApi();
	}

	@action closeColsetDialog = () => {
		this.colsetDialog.visible = false;
		this.colsetDialog.loading = true;
	}

	@action openSynclogDialog = (operateType) => {
		this.synclogDialog.visible = true;

		this.operateType = operateType;

		const callback = params => {
			const _params = Object.assign({}, {
				...params,
				operateItem: 507,
				operateType,
			});
			this.share.callSearchListAPI(_params, '', 'getHrmSearchLogList');
		}
		this.share.callSearchConditionAPI(callback, {}, 'getSearchConditionOfLog');
	}

	@action closeSynclogDialog = () => {
		this.synclogDialog.visible = false;
	}

	@action openSyncDetailDialog = () => {
		this.syncDetailDialog.visible = true;
	}

	@action closeSyncDetailDialog = () => {
		this.syncDetailDialog.visible = false;
	}

	@computed get colsetDialogButtons() {
		const disabled = this.colsetDialog.loading;

		const buttons = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@eamjp8@1`} type='primary' disabled={disabled} onClick={this.isColsetDialog? this.saveColset:this.saveDefaultSortSetting}>{getLabel(86,'保存')}</Button>];

		if (this.hasSyncRight) {
			buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@erdymv@2`} type='primary' disabled={disabled} onClick={this.showConfirm}>{getLabel('534086','同步到所有人') }</Button>);
		}

		return buttons;
	}

	@computed get colsetDialogMoreBtn() {
		const datas = [];
		const disabled = this.colsetDialog.loading;
		datas.push({
			key: "0",
			disabled,
			icon: <i className="icon-coms-Save-as" />,
			content: getLabel(86, '保存'),
			onClick: this.saveColset
		});

		if (this.hasSyncRight) {
			const syncMenus = [{
				key: "1",
				disabled,
				icon: <i className="icon-coms-synchronization" />,
				content: getLabel('534086','同步到所有人') ,
				onClick: this.showConfirm
			}];
			if (this.isColsetDialog) {
				syncMenus.push({
					key: "2",
					disabled,
					icon: <i className="icon-coms-Print-log" />,
					content: getLabel(508025, '同步日志'),
					onClick: this.syncLog
				})
			}
			syncMenus.forEach(menu => datas.push(menu));
		}

		return {
			datas
		};
	}

	@computed get sortSettingParams() {
		const {
			selectedKeys,
			data
		} = this.transfer;

		const params = [];
		selectedKeys.forEach(id => {
			const item = data.find(item => item.id === id);
			const {
				dataIndex,
				ascOrDesc
			} = item;
			params.push({
				dataIndex,
				ascOrDesc,
			});
		});
		return {
			destdatas: JSON.stringify(params)
		};
	}


	/**
	 * @DateTime 2019-06-03
	 * 概述：保存列定制数据
	 */
	saveColset = () => {
		const params = {
			dataKey: this.dataKey,
			systemIds: this.transfer.selectedKeys.toString()
		};
		this.colsetDialog.loading = true;
		api.saveColset(params).then(datas => {
			const {
				status
			} = datas;
			if (status) {
				this.closeColsetDialog();
				this.pstore.getSearchList();
				this.colsetDialog.loading = false;
			}
		}).catch(err => message.error(err))
	}

	/**
	 * @DateTime 2019-06-05
	 * 概述：保存默认排序设置数据
	 */
	saveDefaultSortSetting = () => {
		api.saveOrderBy4Search(this.sortSettingParams).then(datas => {
			const {
				status
			} = datas;
			if (status) {
				this.closeColsetDialog();
				this.pstore.getSearchList();
			}
		}).catch(err => message.error(err))
	}

	showConfirm = () => {
		if (this.isColsetDialog) {
			this.share.showConfirm(getLabel(-1, '只能同步基本信息字段，且同步将影响所有人查询人员列表的显示，确定继续吗？'), this.syncColset);
		}else{
			this.share.showConfirm(getLabel(-1, '同步将影响所有人通讯录列表的显示，确定继续吗？'), this.syncSortset);
		}
	}

	/**
	 * @DateTime 2019-06-03
	 * 概述：同步列定制数据
	 */
	syncColset = () => {
		const params = {
			dataKey: this.dataKey,
			systemIds: this.transfer.selectedKeys.toString()
		}
		this.colsetDialog.loading = true;
		api.syncColset(params).then(datas => {
			const {
				status
			} = datas;
			if (status) {
				this.closeColsetDialog();
				this.pstore.getSearchList();
			} else {
				message.error(datas.message);
			}
			this.colsetDialog.loading = false;
		}).catch(err => message.error(err))
	}

	//同步默认排序设置
	syncSortset = () => {
		api.syncOrderBy2All(this.sortSettingParams).then(datas => {
			const {
				status
			} = datas;
			if (status) {
				this.closeColsetDialog();
				this.pstore.getSearchList();
			} else {
				message.error(datas.message);
			}
			this.colsetDialog.loading = false;
		})
	}

	/**
	 * @DateTime 2019-06-04
	 * 概述：同步日志事件回调
	 */
	syncLog = () => {
		this.openSynclogDialog('sync');
	}


	//***********************穿梭框**************************
	get TRANSFER() {
		return {
			className: 'hrm-col-set-transfer',
			leftHeader: this.renderHeader('left'),
			rightHeader: this.renderHeader('right'),
			filterLeft: datas => this.filter(datas, 'left'),
			filterRight: datas => this.filter(datas, 'right'),
			renderItem: item => this.renderItem(item),
			renderRight: this.isColsetDialog ? '' : item => this.renderRight(item),
			onChange: keys => this.onTransferChange(keys),
		}
	}

	@observable transfer = {
		data: [],
		selectedKeys: [],
	}

	@observable select = {
		value: 'all',
		options: []
	}

	@action onSelectChange = (value) => {
		this.select.value = value;
	}

	@observable leftSearchValue = '';

	@observable rightSearchValue = '';

	//是否有同步所有人的权限
	@observable hasSyncRight = false;

	/**
	 * @DateTime 2019-06-01
	 * 概述：渲染transfer组件的头部
	 * 有同步定制列权限的人才会有类别下拉框
	 * @param    {[String]}   type [区别穿梭框的左边还是右边]
	 * @return   {[React.element]}        
	 */
	renderHeader(type) {
		const hasSelect = (type === 'left' && this.isColsetDialog&& this.hasSyncRight);
		const cls = classnames({
			'header-left': true,
			'colset': hasSelect,
		});
		return (
			<div className='header'>
				<span className={cls} >
					{type === 'left' ? getLabel('385971', "待选列名") : getLabel('385972', "已选列名")}
				</span>
				{
					hasSelect && 
					<WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@mx3aea`} 
						{...this.select} 
						onChange={val=>this.onSelectChange(val)}
						style={{width:90,marginLeft:10}}
					/>
				}
				<WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@k28us4`} 
					style={{width: 100, float: 'right', margin: '5px 10px 5px 0px'}}
                    value={type === 'left'?this.leftSearchValue:this.rightSearchValue}
                    onSearchChange={val=>this.onInputSearchChange(val,type)}
                />
			</div>
		)
	}

	/**
	 * @DateTime 2019-06-01
	 * 概述：transfer搜索框事件回调函数
	 * @param    {[String]}   val  [搜索框内输入的值]
	 * @param    {[String]}   type [区别穿梭框的左边还是右边]
	 */
	@action onInputSearchChange = (val, type) => {
		if (type === 'left') {
			this.leftSearchValue = val
		} else {
			this.rightSearchValue = val;
		}
	}

	/**
	 * @DateTime 2019-06-01
	 * 概述：过滤transfer左右侧的数据
	 * @param    {[Array]}   datas [transfer左右侧的数据（过滤前）]
	 * @param    {[String]}   type  [区分左右侧]
	 * @return   {[Array]}         [过滤后的数据]
	 */
	filter = (datas, type) => {
		if (type === 'left') {
			const {
				value
			} = this.select;

			const searchVal = this.leftSearchValue.trim();
			//根据搜索条件过滤
			const searchFilter = datas.filter(data => data.name.indexOf(searchVal) > -1);

			if (!this.isColsetDialog) {
				return searchFilter;
			}

			if (value === 'all') {
				return searchFilter;
			} else { //下拉框选项不为【全部】时，根据下拉选项再进行一轮过滤
				return searchFilter.filter(data => data.group === value);
			}
		} else {
			//只根据搜索条件过滤
			const searchVal = this.rightSearchValue.trim();
			return datas.filter(data => data.name.indexOf(searchVal) > -1);
		}
	}

	/**
	 * @DateTime 2019-06-01
	 * 概述：渲染transfer栏目
	 * @param    {[Object]}   item [栏目数据]
	 * @return   {[Element]}        
	 */
	renderItem = (item) => {
		const {options} = this.select;
		const option =options && options.find(option => option.key === item.group);

		return (
			<div className='hrm-transfer-item'>
				<div>
					{item.name}
				</div>
				<div className="transfer-item-type">{option && option.showname}</div>
			</div>
		)
	}

	/**
	 * @DateTime 2019-06-04
	 * 概述：渲染transfer右侧栏目
	 * @param    {[Object]}   item [栏目数据]
	 * @return   {[Element]}    
	 */
	renderRight = (item) => {
		const {
			name,
			sort,
			ascOrDesc,
			id,
		} = item;
		const lbl = (ascOrDesc === 'ASC') ? getLabel('534084','正序')  : getLabel('21604','倒序');
		return (
			<div className='hrm-transfer-item'>
				<span className='name'>{name}</span>
				<span className='ascOrDesc' onDoubleClick={e=>this.share.stopBubble(e)} onClick={event=>this.onAscDescClick(event,id)}>{lbl}</span>
			</div>
		)
	}

	/**
	 * @DateTime 2019-06-05
	 * 概述：点击正序、倒序的事件回调
	 * @param    {[Object]}   event 
	 * @param    {[String]}   id    [当前栏目的标识]
	 */
	@action onAscDescClick = (event, id) => {
		this.share.stopBubble(event);

		const {
			data
		} = this.transfer;
		data.forEach(item => {
			if (item.id === id) {
				item.ascOrDesc = (item.ascOrDesc === 'ASC') ? 'DESC' : 'ASC';
			}
		});
	}

	/**
	 * @DateTime 2019-06-01
	 * 概述：transfer栏目事件回调函数
	 * @param    {[Array]}   keys [选中栏目标识]
	 */
	@action onTransferChange = (keys) => {
		this.transfer.selectedKeys = keys
	}

	/**
	 * @DateTime 2019-06-03
	 * 概述：获取显示列定制或默认排序设置的数据
	 */
	@action callTransferApi = () => {
		let params, name;
		if (this.isColsetDialog) {
			params = {
				dataKey: this.dataKey,
			}
			name = 'getShowCol';
		} else {
			name = 'getOrderBy4Search'
		}

		this.reset();

		api[name](params).then(datas => {
			const {
				srcdatas,
				destdatas,
				options,
				groupInfo,
			} = datas;

			this.transfer.data = this.convertSrcDatas([...srcdatas, ...destdatas]);

			this.transfer.selectedKeys = this.convertDestdatas(destdatas);

			this.select.options = !isEmpty(options) ? options : groupInfo  ;

			this.colsetDialog.loading = false;

		});
	}

	/**
	 * @DateTime 2019-06-04
	 * 概述：过滤列数据
	 * @param    {[Array]}   datas [列数据]
	 * @return   {[Array]}         [过滤后的数据]
	 */
	convertSrcDatas = (datas) => {
		const transferDatas = [];
		if (this.isColsetDialog) {
			datas.forEach(data => {
				const {
					dataIndex,
					title,
					group
				} = data;
				transferDatas.push({
					id: dataIndex,
					name: title,
					group
				});
			})
		} else {
			datas.forEach(data => {
				const {
					labelId,
					title,
					sort,
					ascOrDesc,
					dataIndex,
				} = data;
				transferDatas.push({
					id: labelId,
					name: title,
					sort,
					ascOrDesc,
					dataIndex,
				});
			})
		}
		return transferDatas;

	}
	/**
	 * @DateTime 2019-06-04
	 * 概述：获取已选列名dataIndex值的集合
	 * @param    {[Array]}   datas [已选列的数据]
	 * @return   {[Array]}         [dataIndex值的集合]
	 */
	convertDestdatas = (datas) => {
		const transferKeys = [];
		if (this.isColsetDialog) {
			datas.forEach(data => {
				const {
					dataIndex
				} = data;
				transferKeys.push(dataIndex);
			});
		} else {
			datas.forEach(data => {
				const {
					labelId
				} = data;
				transferKeys.push(labelId);
			});
		}
		return transferKeys;
	}


	/**
	 * @DateTime 2019-06-03
	 * 概述：获取是否有同步权限
	 */
	@action callSyncRightApi = () => {
		api.getSyncRight().then(datas => {
			const {
				canEditBasicInfo
			} = datas;
			this.hasSyncRight = canEditBasicInfo;
			this.callTransferApi();
		});
	}

	reset() {
		this.leftSearchValue = '';
		this.rightSearchValue = '';
	}

	//***********************高级搜索**************************
	get SEARCH_SYNCLOG() {
		return {
			...this.share.SEARCH,
			advanceHeight: 165,
			searchType: ['advanced'],
		}
	}

	getSearchListParams = () => {
		return {
			...this.share.tab.form.getFormParams(),
			operateItem: 507,
			operateType: this.operateType
		};
	}

	getSearchListCallback = () => {
		return '';
	}

	getSearchListName = () => {
		return 'getHrmSearchLogList';
	}



	dataKey = '';

	/**
	 * @DateTime 2019-06-03
	 * 概述：设置dataKey
	 * @param    {[String]}   dataKey 
	 */
	setDataKey = (dataKey) => {
		this.dataKey = dataKey;
	}

	@observable form = new WeaForm();

	initColset = () => {
		const getDataKey = async (thisObj)=>{
			const commonParams = {mouldid: "default_3"};
			const {defaultcondition} =await api2.getSearchCondition(commonParams);
			thisObj.form.initFormFields(defaultcondition);
			const formParams =  thisObj.form.getFormParams();
			const datas = await api2.getSearchList({...formParams,...commonParams});
			return datas.sessionkey;
		}
		getDataKey(this).then(dataKey => {
			this.isColsetDialog = true;
			this.dataKey = dataKey;
			this.callTransferApi();
			this.callSyncRightApi();
		})
	}

}