import {
	observable,
	action,
	computed
} from 'mobx';
import {
	Button,
	message
} from 'antd';
import HrmBaseStore from './baseStore';
import * as api from '../apis/browserDisplayField';
import {
	i18n
} from '../public/i18n';
import EnableComs from '../components/browserDisplayFieldSetting/EnableComs';
import has from 'lodash/has';
import findIndex from 'lodash/findIndex';
import filter from 'lodash/filter';
import maxBy from 'lodash/maxBy';

const reqType = ['hrm', 'department', 'subcompany'];

export class HrmBrowserDisplayFieldSetting extends HrmBaseStore {
	/********************* unobservable list *********************/
	topBtnAndMenu = () => {
		let btns = [
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fqd8jd`} type='primary' op="save" onClick={() => this.save()}>{i18n.button.save()}</Button>
		]
		let menus = [];
		btns.map((btn, index) => {
			const {
				props
			} = btn;
			menus.push({
				key: index.toString(),
				content: props.children,
				icon: <i className={this.menuIconCollection[props.op]}/>,
				onClick: props.onClick
			});
		});
		return {
			btns,
			menus: [...menus, ...this.getBasicMenus("HRM_ENGINE_HRM_BROWSER_FIELD_SETTING")]
		}
	}
	/********************* unobservable list *********************/

	/********************* dialog info setting *********************/

	/********************* dialog info setting *********************/

	/********************* observable list *********************/
    @observable spinning = false;
    @observable tab = {
        tabs: [],
        keyParam: 'viewCondition',
        activeTabKey: '1'
	}

	//test
	@observable tableEditProps = {
		draggable: false,
		showTitle: false,
		showAdd: false,
		showDelete: false,
		showCopy: false,
		showMove: false,
		showCollapse: false,
		buttonsType: 'inline',
		validatePass: '',
		addButtonType: 'normal',
		pushTitleIntoHeader: false,
		showRowSelect: false,
		initialDatas: [],
		columns: []
	}

	get max(){
		return (this.tab.activeTabKey == 1 ? 4 : 2);
	}
	
	/********************* computed list *********************/
	/********************* computed list *********************/

    /********************* action list *********************/
    @action init = () => {
        this.containerInitFinished = {init: true, authorized:true};
		this.getTabs();
    }

    @action getTabs = () => {
		api.getTabs().then(data => {
			if(data.status === '1' && data.tabs != null && data.tabs.length > 0){
				this.tab.tabs = data.tabs.map(tab => {
					return {
						color: '#000000',
						groupId: tab.key,
						title: tab.title,
						viewCondition: tab.key
					}
				});
				this.setActiveTab('1');
			}else{

			}
		}, error => {})
    }
    
    @action setActiveTab = (key) => {
        if(this.spinning)
            return;
        this.tab.activeTabKey = key || this.tab.tabs[0].viewCondition;
        const tabIndex = this.getTabIndex(this.tab.tabs, key);
		if (tabIndex < 0) return;
		this.getFields();
	} 

	@action getFields = () => {
		const params = {type: reqType[Number(this.tab.activeTabKey) - 1]};
		api.getFields(params).then(data => {
			if(data.status === '1'){
				const {datas, columns} = data;
				this.tableEditProps = {
					...this.toJS(this.tableEditProps),
					initialDatas: datas,
					datas,
					columns
				}
			}
		}, error => {});
	}

	@action getCellProps = () => {
		const datas = this.toJS(this.tableEditProps.datas) || [];
		const enableCount = filter(datas, v => v.enable == 1).length;
		const max = (this.tab.activeTabKey == 1 ? 4 : 2);
		return datas.map((data, index) => {
			const {id, enable, fullpath, setFullPath} = data;
			if(setFullPath == null || !setFullPath){// || id == 'departmentname' || id == 'subcompanyname'){
				return {
					id,
					enable: {
						com: [
							// { type: 'CHECKBOX', key: 'enable', disabled: data.disabled || (enableCount >= max && data.enable == 0) }
							{ type: 'CHECKBOX', key: 'enable', disabled: data.disabled }
						]
					},
					dspOrder: {
						com: [
							{ type: 'INPUT', key: 'dspOrder', viewAttr: '2' }
						]
					}
				}
			}else{
				const enableComs = [
					{ type: 'CHECKBOX', key: 'enable' }
				];
				if(!!setFullPath && !!enable){
					enableComs.push(<EnableComs ecId={`${this && this.props && this.props.ecId || ''}_EnableComs@kyc11z@${index}`} />);
				}
				// if(data.disabled || (enableCount >= max && data.enable == 0)){
				if(data.disabled){
					enableComs[0].disabled = true;
				}
				return {
					id,
					enable: {
						com: enableComs
					},
					dspOrder: {
						com: [
							// { type: 'INPUT', key: 'dspOrder', viewAttr: !!enable ? '2' : '1' }
							{ type: 'INPUT', key: 'dspOrder', viewAttr: '2' }
						]
					}
				}
			}
		})
	}
	
	@action onChange = (datas, initialDatas) => {
		const enableCount = filter(datas, v => v.enable == 1).length;
		const {editKeys, editDatasDiff, editDatas} = initialDatas;
		const t = datas.map(d => d.dspOrder == '' ? 0 : Number(d.dspOrder));
		editKeys.map((k, i) => {
			const diffData = editDatasDiff[i], record = editDatas[i];
			const idx = findIndex(datas, {id: record.id});

			const enable = (record.enable == 1);
			if(!enable){
				Object.assign(record, {dspOrder: ''});
			}else{
				const {dspOrder} = record;
				(dspOrder == null || dspOrder == '') && Object.assign(record, {dspOrder: maxBy(t) + 1 + ""});
				if(enableCount > this.max && record.dspOrder == (maxBy(t) + 1)){
					Object.assign(record, {enable: 0, dspOrder: ''});
					message.warning(i18n.message['506768']().replace('{param}', this.max));
				}
			}

			if(idx > -1){
				datas[idx] = record;
			}
		})
		this.tableEditProps.datas = datas;
	}

	@action save = () => {
		const params = {fieldtype: Number(this.tab.activeTabKey)};
		let records = filter(this.toJS(this.tableEditProps.datas), v => v.enable == 1);
		records = records.map(r => {
			let obj = {};
			if(r.id == 'supOrgInfo'){
				obj.delimiter = r.delimiter || '/';
				obj.orderType = r.orderType || '0';
			}
			let dspOrder = Number(r.dspOrder);
			dspOrder = Number.isNaN(dspOrder) ? '0' : dspOrder.toString();
			obj.dspOrder = dspOrder;
			return {
				...r,
				...obj
			}
		})
		Object.assign(params, {records});
		api.save({data: JSON.stringify(params)}).then(data => {
			if(data.status === '1'){
				message.success(i18n.message.saveSuccess());
				this.getFields();
			}else{
				message.error(data.message);
			}
		}, error => {});
	}
	/********************* action list *********************/
}

export const hrmBrowserDisplayFieldSetting = new HrmBrowserDisplayFieldSetting();