import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaInputLocale,
	WeaHelpfulTip,
	WeaLocaleProvider,
} from 'ecCom';
import {
	message
} from 'antd';
import {
	fetch,
	getMenusCreationConfig,
	getTopButtons,
	getDropMenuDatas,
	confirmation,
} from '../util/save-time-util.js';
import * as asyncFetch from '../apis/levelProtection.js';
import has from 'lodash/has';
import cloneDeep from 'lodash/cloneDeep';
import {i18n} from '../public/i18n.js'
const getLabel = WeaLocaleProvider.getLabel;
const getCurrentLabel = WeaInputLocale.getCurrentLabel;

export class HrmLevelProtection {
	//************权限*************
	@observable pageAccessPermission = {
		hasRight: false,
		loading: true,
	}

	@action getPermissionInfo = () => {
		fetch({
			asyncFetch,
			name: 'getHasRight',
			logic: (cb) => {
				const {
					hasRight
				} = cb;

				if (hasRight) {
					this.pageAccessPermission.hasRight = true;
				}
				this.pageAccessPermission.loading = false;
			}
		});
	}

	//*************头部**************
	get topProps() {
		return {
			showDropIcon: true,
			iconBgcolor: '#217346',
			icon: <i className='icon-coms-hrm'/>,
			title: getLabel('507090', "分级保护设置"),
		}
	}

	@observable btnMenu = [];

	@computed get toploading() {
		const {
			selectedKey
		} = this.tab;

		return (selectedKey === '0') ? this.basicInfo.loading : this.table.loading;

	}

	@computed get menusCreationConfig() {
		return getMenusCreationConfig(this.btnMenu);
	}

	@computed get topButtons() {
		const {
			topMenu
		} = this.menusCreationConfig;

		const topButtons = getTopButtons.call(this, {
			datas: topMenu,
			disabled: this.menuState,
		});

		return topButtons;
	}


	@computed get dropMenuDatas() {
		const {
			rightMenu
		} = this.menusCreationConfig;

		return getDropMenuDatas.call(this, {
			datas: rightMenu,
			disabled: this.menuState,
		});
	}

	@computed get menuState() {
		const {
			selectedKey
		} = this.tab;

		const loading = (selectedKey === '0') ? this.basicInfo.loading : this.table.loading;

		return [loading];
	}


	@action getRightMenu = () => {
		fetch({
			asyncFetch,
			name: 'getRightMenu',
			fetchParams: {
				tabKey: this.tab.selectedKey
			},
			logic: (cb) => {
				const {
					btnMenu,
				} = cb;

				this.btnMenu = btnMenu;
			}
		});
	}

	save = () => {
		const {
			selectedKey
		} = this.tab;

		const name = (selectedKey === '1') ? 'saveUserClassification' : 'saveResourceClassification';

		this.saveClassification({
			name,
			success: (cb) => {
				message.success(cb.message);
			},
			fail: (cb) => {
				message.warning(cb.message);
			}
		})
	}

	//************页签*************
	get TABCONFIG() {
		return {
			datas: [{
				key: '0',
				title: getLabel('505832', '基本信息')
			}, {
				key: '1',
				title: getLabel('507091', '人员密级')
			}, {
				key: '2',
				title: getLabel('507092', '资源密级')
			}],
			keyParam: 'key',
			onChange: (key) => this.handleTabChange(key),
		}
	}

	@observable tab = {
		selectedKey: '0'
	}

	@action handleTabChange = (key) => {
		this.tab.selectedKey = key;

		this.getRightMenu();

		if (key === '0')
			return;

		const name = (key === '1') ? 'getUserClassification' : 'getResourceClassification';

		this.getClassification(name)
	}

	//************基本信息*************
	IMGURL = '/hrm/hrm_e9/image/levelProtection.png';

	@observable basicInfo = {
		loading: false,
		description: [],
		isOpenClassification: false
	}

	@action getBasicInfo = () => {
		this.basicInfo.loading = true;

		fetch({
			asyncFetch,
			name: 'getBasicInfo',
			logic: (cb) => {
				['description', 'isOpenClassification'].forEach(v => {
					this.basicInfo[v] = cb[v];
				});
				let{crcDescription,isCrc} = cb;
				crcDescription = crcDescription.map( (d,i) => `${i+1}. ${d}`)
				this.crcDescription = [...this.tmpcrcDescription,...crcDescription] 
				this.isCrc = isCrc

				this.basicInfo.loading = false;
			}
		});
	}

	saveBasicInfo = (params) => {
		const {
			success,
			fail,
			type,
		} = params;
		
		let p;
		if (type == '1') {
			p = {
				isOpenClassification: 1,
				isCrc: Number(this.isCrc)
			}
		}else{
			p = {
				isOpenClassification: Number(this.basicInfo.isOpenClassification),
				isCrc:1
			}
		}

		fetch({
			asyncFetch,
			name: 'saveBasicInfo',
			fetchParams: p,
			logic: (cb) => {
				const {
					sign
				} = cb;

				if (sign === '1') {
					success(cb);
				} else {
					fail(cb);
				}
			}
		});
	}

	handleOpenBtnClick = () => {
		confirmation.showConfirm({
			content: getLabel('507111', '确定启用分级保护吗，启用后将不能再关闭！'),
			logic: () => {
				this.saveBasicInfo({
					success: (cb) => {
						message.success(cb.message);
						this.basicInfo.isOpenClassification = true;
					},
					fail: (cb) => {
						message.warn(cb.message);
					},
					type:'1'
				});
			}
		});

	}

	//************可编辑列表*************
	TABLECONFIG = {
		showTitle: false,
		getRowSelection: (rowSelection) => {
			return null
		},
		onChange: (datas) => this.handleTableChange(datas)
	}

	@observable table = {
		columns: [],
		datas: [],
		loading: false
	}

	@computed get cells(){
		const cells = [];
		this.tab.selectedKey == '2' && this.table.datas.map(data => {
			const validityEnable = data.validityEnable == '1';
			const cell = {id: data.id};
			if(!validityEnable){
				Object.assign(cell, {
					validity: {
						com: []
					}
				})
			}
			const com = [];
			has(this.columnMap, 'validityDefault') && com.push(...cloneDeep(this.columnMap['validityDefault']));

			const validity = data.validity && getCurrentLabel(data.validity) &&`★${getCurrentLabel(data.validity) || ''}`;
			com.push((<span style={{paddingLeft: 10}}>{data.showName}{validity}</span>));
			if(!validityEnable && com.length > 1){
				com[0].style.visibility = 'hidden';
			}
			Object.assign(cell, {
				validityDefault: {
					com
				}
			})
			cells.push(cell);
		});
		return cells;
	}

	get validator(){
		return {
                rules: {
                    validity: 'stringvalue',
                },
                customRegister: [
                    {
                        name: 'stringvalue',
                        rules: (value, requirement, attribute) => {
							return !/^\d+(\.\d+)?$/.test(value);
                        },
                        errorMessage: getLabel('528353','不能为纯数字')
                    }
                ]
		}
	}

	tableRef;
    setTableRef = dom => this.tableRef = dom;

	@computed get saveParams() {
		const {
			datas
		} = this.table;

		const params = {
			rowLen: datas.length
		};

		datas.forEach((data, index) => {
			const {
				customShowName,
				secLevel
			} = data;

			Object.assign(params, {
				[`customShowName_${index}`]: customShowName,
				[`secLevel_${index}`]: secLevel
			});
			if(this.tab.selectedKey == '2'){
				const {isDefault, validity, validityDefault} = data;
				Object.assign(params, {
					[`isDefault_${index}`]: isDefault,
					[`validity_${index}`]: validity,
					[`validityDefault_${index}`]: validityDefault
				});
			}
		})

		return params;
	}

	@action handleTableChange = (datas) => {
		this.table.datas = datas;
	}

	@action getClassification = (name) => {
		this.table.loading = true;

		fetch({
			asyncFetch,
			name,
			logic: (cb) => {
				const {
					columns
				} = cb;

				this.processColumns(columns);

				['columns', 'datas'].forEach(v => {
					this.table[v] = cb[v];
				});

				this.table.loading = false;
			}
		});
	}

	columnMap = {};

	processColumns = (columns) => {
		this.columnMap = {};

		columns.forEach((c, i) => {
			const {
				dataIndex,
				title,
				helpfulTip,
				com
			} = c;

			this.columnMap[dataIndex] = com;

			if(dataIndex == 'validityDefault'){
				Object.assign(com[0], {
					style: {width: 120}
				})
			}

			if(helpfulTip){
				c.title = (
					<span>
						<span>{title}</span>
						<span style={{marginLeft:10}}>
							<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@gm41ww@${i}`}
							  width={176}
					          title={helpfulTip}
					        />
						</span>
					</span>
				)
			}
		});
	}

	saveClassification = (params) => {
		let flag = false;
		if(this.tableRef && this.tableRef.doValidate){
            const result = this.tableRef.doValidate();
            // console && console.debug(result);
            flag = result.pass;
        }
        if(!flag)
			return;
			
		const {
			name,
			success,
			fail
		} = params;

		fetch({
			asyncFetch,
			name,
			fetchParams: this.saveParams,
			logic: (cb) => {
				const {
					sign
				} = cb;

				if (sign === '1') {
					success(cb);
				} else {
					fail(cb);
				}
			}
		});
	}

	//************其他*************
	reset = () => {
		this.tab.selectedKey = '0';
	}

	refresh = () => {
		this.handleTabChange('0');
	}


	//#1000857 概述：满足涉密系统分级保护功能完善-人力资源（公共设置）-前端
	@observable isCrc = false;
	@observable crcDescription = [];
	get tmpcrcDescription() {
		return  [`• ${i18n.label['529915']()}`];
	}

	handleTamper = () => {
		confirmation.showConfirm({
			content: i18n.label['529920'](),
			logic: () => {
				this.saveBasicInfo({
					success: (cb) => {
						message.success(cb.message);
						this.isCrc = true;
					},
					fail: (cb) => {
						message.warn(cb.message);
					},
					type:'2'
				});
			}
		});
	}


}