import {
	observable,
	action,
	computed
} from 'mobx';
import {
	WeaForm,
	WeaTableNew
} from 'comsMobx';
import {
	WeaFormItem,
	WeaCheckbox
} from 'ecCom';
import {
	WeaSwitch
} from 'comsMobx';
import {
	Button,
	message
} from 'antd';
import HrmBaseStore from './baseStore';
import * as api from '../apis/authSearch';
import {
	i18n
} from '../public/i18n';
import {
	has,
	indexOf,
	findIndex,
	remove,
	isEmpty,
	dropRight,
	cloneDeep
} from 'lodash';
const {
	TableStore
} = WeaTableNew;

export class HrmAuthSearch extends HrmBaseStore {
	/********************* unobservable list *********************/
	getMenu = () => {
		return [...this.getBasicMenus()]
	}

	tabConfig = {
		tabs: [{
			color: '#000000',
			groupId: 'roleList',
			title: '',
			viewCondition: '1',
			searchType: ['base', 'advanced'],
			searchKey: '',
			doSearch: (params) => this.doSearch(params)
		}],
		tabChangeHandle: this.setActiveTab,
		keyParam: 'viewCondition',
		activeTabKey: '1'
	}

	tableConfig = {
		...this.editTableConfig,
		draggable: false,
		showAdd: false,
		showDelete: false,
		showCopy: false,
		columns: [{
			title: i18n.label.type, //列名
			dataIndex: 'type', //列的id 对应数据
			key: 'type', //前端渲染key值
			colSpan: 1,
			width: '30%',
			com: [{
				label: '',
				type: 'TEXT',
				key: 'type',
				viewAttr: '3',
			}]
		}, {
			title: i18n.label.itemCount,
			dataIndex: 'totalCount',
			key: 'totalCount',
			colSpan: 1,
			width: '30%',
			com: [{
				label: '',
				type: 'TEXT',
				key: 'type',
				viewAttr: '3',
			}]
		}, {
			title: i18n.label.detail,
			dataIndex: 'detail',
			key: 'detail',
			colSpan: 1,
			width: '40%',
			useRecord: true
		}],
		datas: [],
		getRowSelection: (rowSelection) => {
			return null;
		}
	}

	otherListCondition = {};
	fields = [];
	authSearchCondition = {}
	fromid = '';
	selectedTableItem = {
		record: null,
		index: -1
	}
	/********************* unobservable list *********************/

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

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

	/********************* observable list *********************/
	@observable refreshForm = new Date().getTime();
	@observable refreshTable = new Date().getTime();
	@observable refreshDialog = new Date().getTime();
	@observable spinning = false;
	@observable tableList = {}
	@observable showTable = false;
	@observable treeProps = {
		count: 0,
		checkedKeys: []
	}

	@observable height = 650;

	dialogParams = { //override baseStore.dialogParams
		...this.dialogPropsDef,
		style: {
			width: 820,
			// height: 650
		},
		buttons: [],
		onCancel: () => {
			this.dialogParams.visible = false;
		},
		table: new TableStore(),
		treeData:  [],
		cType: 'table'
	}
	/********************* observable list *********************/

	/********************* computed list *********************/

	/********************* computed list *********************/

	/********************* action list *********************/
	initData = () => {
		this.containerInitFinished = {
			...this.containerInitFinished,
			init: true
		}
		this.showTable = false;
		this.clearTableData();
		this.getFormInfo();
	}

	setTableColTitle = () => {
		this.tableConfig.columns.map(c => {
			if (typeof(c.title) == 'function')
				c.title = c.title();
		})
	}

	getFormInfo = () => {
		api.getFormInfo().then(data => {
			if (data.status === '1') {
				if (has(data, 'formField') && data.formField.length > 0) {
					this.fields = data.formField[0].items;
					this.setFormData('searchForm', data.formField);
					this.refreshForm = new Date().getTime();
				}
			}
		}, error => {

		})
	}

	getSearchGroupItem = () => {
		let items = [];
		if (this.formTarget.searchForm != null && this.formTarget.searchForm.isFormInit) {
			const formParams = this.formTarget.searchForm.getFormParams();
			items.push({
				com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@8urmcb`}
	                labelCol={{span: 0}}
	                wrapperCol={{span: 24}}>
                      <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@8qg9fa`} fieldConfig={this.fields[0]} form={this.formTarget.searchForm} onChange={this.onChangeTransferType}/>
				</WeaFormItem>),
				col: 2
			})
			const browserFieldDomKey = `${formParams.transferType}id`;
			const index = findIndex(this.fields, {
				domkey: [browserFieldDomKey]
			})
			if (index >= 0) {
				let field = this.fields[index];
				items.push({
					com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@h5yssm`}
		                labelCol={{span: 0}}
		                wrapperCol={{span: 24}}>
                      <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@vjreaw`} fieldConfig={field} form={this.formTarget.searchForm} onChange={this.onBrowserChangeHandle}/>
                	</WeaFormItem>),
					col: 2
				})
			}
		}
		return items;
	}

	onBrowserChangeHandle = (obj) => {
		const keys = Object.keys(obj);
		const fk = keys[0];
		this.fromid = obj[fk].value;

		const formParams = this.formTarget.searchForm.getFormParams();
		this.clearTableData();
		if (this.fromid != '')
			this.initTable({
				fromid: this.fromid,
				transferType: formParams.transferType
			});
		else
			this.showTable = false;
	}

	@action onChangeTransferType = (obj) => {
		this.clearFormData();
		this.clearTableData();
		this.showTable = false;
		this.refreshForm = new Date().getTime();
	}

	clearTableData = () => {
		this.tableConfig.datas.length = 0;
		this.refreshTable = new Date().getTime();
	}

	clearFormData = () => {
		const d = {
			resourceid: {
				value: ''
			},
			departmentid: {
				value: ''
			},
			subcompanyid: {
				value: ''
			},
			jobtitleid: {
				value: ''
			},
			roleid: {
				value: ''
			}
		}
		this.formTarget.searchForm.updateFields(d, false);
	}

	initTable = (params) => {
		this.spinning = true;
		this.setTableColTitle();
		api.getTableData(params).then(data => {
			if (data.status === '1') {
				let source = [];
				data.datas.map((d, index) => {
					let obj = {
						...d,
						id: this.tableConfig.datas.length + 1,
						com: {
							detail: [
								<a onClick={() => this.onSelectHandle(obj, index)}>{i18n.label.detail()}</a>
							]
						}
					}
					source.push(obj);
				})
				this.tableConfig.datas = source;
				this.refreshTable = new Date().getTime();
			}
			this.showTable = true;
			this.spinning = false;
		}, error => {
			this.showTable = true;
			this.spinning = false;
		})
	}

	convertTreeData = (datas, pid = 0) => {
		let newDatas = [];
		datas && !isEmpty(datas) && datas.map((item, index) => {
		for (let key in datas[index]) {
			let v = datas[index][key];
			try{
				newDatas.push({
				childs: this.convertTreeData(v.submenus, String(v.categoryid)),
				domid: String(v.categoryid),
				haschild: v.hasChildren,
				isopen: v.isOpen,
				key: String(v.categoryid),
				name: v.name,
				pid: pid,
				canClick: true,
				})
			}catch(e){
			}
		}
		})
		return newDatas;
	}

	onCheckBoxChange = (val, key) => {
		this.otherListCondition[key] = val;
		const formParams = this.formTarget.conditionForm.getFormParams();
		this.doSearch({...formParams});
	}

	@action onSelectHandle = (record, index) => {
		this.selectedTableItem = {
			record,
			index
		};
		delete this.formTarget.conditionForm;
		delete this.formTarget.conditionFormFields;
		const params = {
			fromid: this.fromid,
			isHidden: true
		}
		if(record.codeName === 'Temail001'){
			Object.assign(params, {
				folderid: 0
			})
		}else if(record.codeName === 'Temail002'){
			Object.assign(params, {
				folderid: -1
			})
		}
		const formParams = this.formTarget.searchForm.getFormParams();
		params.transferType = formParams.transferType;
		api.initModuleData(record.codeName, params).then(rs => {
			try {
				rs.map((result, index) => {
					if (result.status === '1') {
						switch (index) {
							case 0:
								if(this.tabConfig.tabs.length > 1)
									this.tabConfig.tabs = dropRight(this.tabConfig.tabs, this.tabConfig.tabs.length - 1);
								this.tabConfig.tabs[0].groupId = '1';
								this.tabConfig.tabs[0].title = '';
								this.tabConfig.activeTabKey = '1';
								this.tabConfig.tabSearchKey = '';
								this.tabConfig.buttons = [];
								this.setFormData('conditionForm', result.condition);
								if(Array.isArray(result.condition) && result.condition[0].items != null){
									this.tabConfig.tabs[0].searchType = ['base', 'advanced']
									this.tabConfig.tabs[0].searchKey = result.condition[0].items[0].domkey[0];
								}else{
									this.tabConfig.tabs[0].searchType = ['base'];
									this.tabConfig.tabs[0].searchKey = 'categoryname'
								}
								if(has(result, 'dialogProps')){
									this.dialogParams = {...this.dialogParams, title: `${i18n.label.select()}${record.type}`, ...result.dialogProps}
								}else{
									this.dialogParams = {...this.dialogParams, ...this.dialogPropsDef, title: `${i18n.label.select()}${record.type}`}
								}
								if(has(result, 'tab')){
									result.tab.map((tab, i) => {
										if(i === 0){
											Object.assign(this.tabConfig.tabs[0], {
												title: tab.title,
												viewCondition: tab.key,
												groupId: tab.key
											})
										}else{
											const t = cloneDeep(this.tabConfig.tabs[0]);
											Object.assign(t, {
												title: tab.title,
												viewCondition: tab.key,
												groupId: tab.key
											})
											this.tabConfig.tabs.push(t);
										}
									})
									this.tabConfig.tabSearchKey = result.tabSearchKey;
								}
								if(has(result, 'tabBtns')){
									let btns = [];
									result.tabBtns.map((def, index) => {
										btns.push(<WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@c43500@${index}`} {...def} onChange={(val) => this.onCheckBoxChange(val, def.id)} />);
									})
									this.tabConfig.buttons = btns;
								}
								break;
							case 1:
								if (has(result, 'sessionkey')) {
									const tableName = record.codeName;
									this.tableList[tableName] = new TableStore();
									this.tableList[tableName].getDatas(result.sessionkey, 1);
									this.dialogParams.table = this.tableList[tableName];
									this.dialogParams.cType = 'table';
								} else {
									this.dialogParams.cType = 'tree';
									try{
										this.dialogParams.treeData = this.convertTreeData(JSON.parse(result.treeDataJson));
									}catch(e){
										this.dialogParams.treeData = [];
									}
								}
								this.dialogParams.visible = true;
								break;
							default:
								break;
						}
					}
				});
			} catch (e) {}
		}, error => {

		})
	}

	setTreeCheckedKeys = (ids) => {
		this.treeProps.checkedKeys = ids;
	}

	@action setActiveTab = (key) => {
		this.tabConfig.activeTabKey = key || this.tabConfig.tabs[0].viewCondition;
		const tabIndex = this.getTabIndex(this.tabConfig.tabs, key);
		if (tabIndex < 0) return;
		this.refreshDialog = new Date().getTime();
		const formParams = this.formTarget.conditionForm.getFormParams();
		this.doSearch({...formParams});
	}

	@action doSearch = (params) => {
		params = params || {};
		if(this.tabConfig.tabSearchKey != '')
			Object.assign(params, {[this.tabConfig.tabSearchKey]: this.tabConfig.activeTabKey});
		[...Object.keys(this.otherListCondition)].map(k => {
			Object.assign(params, {[k]: this.otherListCondition[k]});
		});
		const formParams = this.formTarget.searchForm.getFormParams();
		api.getList(this.selectedTableItem.record.codeName, { ...params,
			fromid: this.fromid,
			isHidden: true,
			transferType:formParams.transferType
		}).then(data => {
			if (data.status === '1'){
				// this.dialogParams.table.getDatas(data.sessionkey, 1);
				if (has(data, 'sessionkey')) {
					this.dialogParams.table.getDatas(data.sessionkey, 1);
				} else {
					try{
						this.dialogParams.treeData = this.convertTreeData(JSON.parse(data.treeDataJson));
					}catch(e){
						this.dialogParams.treeData = [];
					}
				}
			}
				
		}, error => {

		})
	}
	/********************* action list *********************/
}