import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	WeaButtonIcon,
	WeaLocaleProvider,
	WeaFormItem,
} from 'ecCom';
import {
	WeaSwitch
} from 'comsMobx';
import {
	message,
	Button
} from 'antd';
import {
	AuthorityStore,
	TopStore,
	FormStore,
	SearchStore,
	TableListStore,
	DialogStore,
} from '../public/valhalla/stores/index.js';
import {
	isEmpty
} from "lodash";
import {
	bindTokenKey
} from '../util/pulic-func';
import * as api from '../apis/sanyuan.js';
const getLabel = WeaLocaleProvider.getLabel;

class SanYuanStore {
	@observable authorityStore = new AuthorityStore(api.getHasRight);
	@observable topStore = new TopStore(this);
	@observable formStore = new FormStore(this);
	@observable searchStore = new SearchStore(this);
	@observable authSearchStore = new SearchStore(this);
	@observable tableListStore = new TableListStore(this);
	@observable authTableListStore = new TableListStore(this);
	@observable dialogStore = new DialogStore(this);
	@observable authAddDialogStore = new DialogStore(this);

	@observable isStartInit = false;
	@observable isInitFinish = "";
	@observable percent = 0;
	@observable isInitialized = "";
	@observable dialogType = "";
	@observable isSecondaryPwdSetted = false;

	get topConfig() {
		return {
			api: api.getRightMenu,
			title: getLabel(514058, "三员管理员维护"),
		}
	}

	@computed get topLoading() {
		if (this.isInitFinish) { //三员管理员初始化完成后
			return this.tableListStore.tableStore.loading
		} else {
			if (!this.isStartInit) { //初始化前
				return this.formStore.loading
			}
		}
	}

	@computed get rightMenuStates() {
		if (this.isInitFinish) {
			const {
				tableStore
			} = this.tableListStore, {
				loading,
				selectedRowKeys
			} = tableStore;

			const disabled = (selectedRowKeys.length === 0)

			return [loading, disabled];
		} else {
			if (!this.isStartInit) {
				const {
					loading
				} = this.formStore;

				return [loading]
			}
		}
	}

	get formConfig() {
		return {
			api: api.getInitForm,
			isCustomRender: true,
		}
	}

	get safeFormConfig() {
		return {
			api: api.getSecForm,
			isCustomRender: true,
			linkageConfigs: [{
				passiveKey: "mobile", //绑定手机号
				activeKey: "userUsbType", //辅助校验方式
				showValue: "4"
			}, {
				passiveKey: "tokenKey", //令牌序列号
				activeKey: "userUsbType",
				showValue: "3"
			}, {
				passiveKey: "usbstate",
				activeKey: "userUsbType",
				showValue: "3,4,6"
			}, {
				passiveKey: "serial", //用户密钥
				activeKey: "userUsbType",
				showValue: "2"
			}, {
				passiveKey: "needauto", //自动启用
				activeKey: ["usbstate","userUsbType"],
				showValue: ["1","3,4,901"]
			}, {
				passiveKey: "enableUsbType", //启用方式
				activeKey: ["needauto","userUsbType"],
				showValue:[ "1","2,3,4,5,6"]
			},{
				passiveKey: "selectdateselect", //启用时间
				activeKey: "needauto",
				showValue: "1"
			},{
				passiveKey: "selectdate", //启用日期
				activeKey: "needauto",
				showValue: "1"
			}],
			


			customRenderKeyList: ["usbstate"],

		}
	}

	get authAddFormConfig() {
		const {
			selectedKey
		} = this.authSearchStore;

		return {
			api: (selectedKey === "2") ? api.getFuncRightForm : api.getSubComRightForm,
			isCustomRender: true,
			customRenderKeyList: ["rightIds"],
			mark: "authAdd",
		}
	}

	get OtherComponents() {
		return {
			userUsbType: (item, form) => {
				const {
					userUsbType
				} = form.getFormParams();
				if (["3", "4","6","901"].includes(userUsbType)) {
					const customRenderItems = this.getCustomRenderItems(["usbstate"]);
					if (isEmpty(customRenderItems)) {
						return null;
					}
					const fieldConfig = customRenderItems.usbstate;

					return (
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@gw1xxe`} 
							fieldConfig={fieldConfig} 
							form={form} 
							formParams={form.getFormParams()} 
							onChange={this.handleUsbstateChange}
						/>
					)
				}
			},
			tokenKey: () => {
				return (
					<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@owlohg`} type="default" onClick={() => bindTokenKey(this.id)}>{getLabel(514134,"绑定")}</Button>
				)
			}
		}
	}

	get authAddOtherComponents() {
		return {
			type: (item, form) => {
				const customRenderItems = this.getCustomRenderItems(['rightIds']);
				if (isEmpty(customRenderItems)) {
					return null;
				}
				const fieldConfig = customRenderItems.rightIds;

				const {
					type
				} = form.getFormParams();

				if (type === "1") {
					return null;
				}

				return (
					<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@8ftfaf`}
			            label=""
			            colon={false}
			            labelCol={{span: 0}}
			            wrapperCol={{span: 24}}
			            tipPosition="bottom"
			            error={form.getError(fieldConfig)}
			          >
						<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@7q4hae`} 
							fieldConfig={fieldConfig} 
							form={form} 
							formParams={form.getFormParams()} 
						/>
					</WeaFormItem>
				)
			}
		}
	}

	get adminFormConfig() {
		return {
			api: api.getAdminForm,
			isCustomRender: true,
		}
	}

	//页面高级搜索配置
	get searchConfig() {
		return {
			hasMask: true,
			_handleSearch: this.handleSearch,
			api: api.getSearchCondition,
			linkageFieldName: "lastName",
		}
	}

	//权限设置
	@computed get authSearchConfig() {
		const {
			selectedKey
		} = this.authSearchStore;
		return {
			hasMask: true,
			advanceHeight: 80,
			_handleSearch: this.handleAuthSearch,
			api: (selectedKey === "2") ? api.getFuncSearchCondition : api.getSubComSearchCondition,
			tabApi: api.getTab,
			linkageFieldName: (selectedKey === "2") ? "rightName" : "subcompanyName",
			mark: "auth",
			_handleTabChange: this.handleTabChange
		}
	}


	get tableConfig() {
		return {
			_reRenderColumns: this.reRenderColumns,
			_onOperatesClick: this.onOperatesClick,
			api: api.getSearchList,
		}
	}

	@computed get authTableConfig() {
		return {
			api: (this.authSearchStore.selectedKey === "2") ? api.getFuncRightList : api.getSubComRightList,
			_onOperatesClick: this.onAuthOperatesClick,
			scroll: {
				y: 380
			}
		}
	}

	@computed get dialogConfig() {
		const config = {
			style: {
				width: 600,
				height: 280
			},
			mark: "",
		};
		if (this.dialogType === 'create') {
			Object.assign(config, {
				title: getLabel(387059, '新建管理员')
			});
		} else {
			Object.assign(config, {
				title: getLabel(387060, '编辑管理员')
			});
		}
		return config;
	}

	moreDialogProps = {
	    hasScroll: false
	}
	//【安全设置】弹框配置
	get safeDialogConfig() {
		return {
			style: {
				width: 600,
				height: 280
			},
			mark:"",
			title: getLabel(32496, "安全设置")
		}
	}

	//【功能权限】弹框配置
	get authDialogConfig() {
		return {
			style: {
				width: 820,
				height: 520
			},
			mark: "auth"
		}
	}

	//【添加功能权限】弹框配置
	get authAddDialogConfig() {
		const {
			selectedKey
		} = this.authSearchStore;
		return {
			style: {
				width: 600,
				height: 150
			},
			title: (selectedKey === "2") ? getLabel(383101, "添加功能权限") : getLabel(383942, "添加机构权限"),
			mark: "authAdd",
		}
	}

	get DialogButtons() {
		return [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@aohwvq`} type="primary" onClick={this.save}>{getLabel(30986,"保存")}</Button>]
	}

	get MoreBtn() {
		return {
			datas: []
		}
	}


	get authAddDialogButtons() {
		return [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@2d4piu`} type="primary" onClick={this.saveAuth}>{getLabel(30986,"保存")}</Button>]
	}

	get authAddMoreBtn() {
		return {
			datas: []
		}
	}

	get authDialogButtons() {
		return [];
	}

	get authMoreBtn() {
		return {
			datas: []
		}
	}

	@computed get authSearchButtons() {
		const {
			tableStore
		} = this.authTableListStore, {
			selectedRowKeys
		} = tableStore;
		return (
			[<WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@god9t7`} buttonType="add" type="primary" onClick={this.handleAddIconClick}/>,
				<WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@dhoq6q`} buttonType="del" type="primary" disabled={selectedRowKeys.length === 0} onClick={this.handleDelIconClick} />
			]
		)
	}

	initPage = () => {
		this.isInitFinish = "";//避免页面刷新两次的情况
		this.authorityStore.fetchAuthority().then(() => { //获取页面权限
			this.isStartInit = false;

			this.checkInitial().then(() => {
				if (this.isInitialized) { //是否初始化过三员管理员
					this.afterInit();
				} else {
					this.beforeInit();
				}
			});

		}).catch(() => {
			this.isInitFinish = false;
		})
	}

	//检测是否初始化过
	checkInitial = () => {
		return new Promise((resolve, reject) => {
			api.isInitialized().then(datas => {
				const {
					status,
					initialized
				} = datas;
				if (status === "1") {
					this.isInitialized = initialized;
					this.isInitFinish = initialized;
					resolve();
				} else {
					this.isInitialized = "";
					message.warning(datas.message);
					reject();
				}
			}).catch(() => {
				reject();
			})
		})
	}

	//初始化三员管理员
	init = () => {
		const {
			validateForm,
			form
		} = this.formStore;

		validateForm(form).then(() => { //校验表单
			const params = form.getFormParams();

			this.isLoginNameRepeat().then(() => { //校验账号是否重复
				const formParams = this.formStore.form.getFormParams();
				const passwords = ["systemAdminPwd", "secAdminPwd", "secAuditorPwd"];

				//校验密码复杂度和密码长度
				if (
					passwords.every(val => this.checkPassword(formParams[val], this.passwordComplexity)) &&
					passwords.every(val => this.isPassminlen(formParams[val].length, this.minPasslen))
				) {
					this.startInit(); //开始初始化
					this.startProcessing(); //更新进度条进度

					api.initAdmin(params).then(datas => {
						const {
							status
						} = datas;

						if (this.interval) {
							this.clear(); //清楚interval
						}
						if (status === "1") {
							this.finishInit(); //结束初始化
							this.afterInit(); //初始化完成后
						} else {
							message.warning(datas.message);
						}
					}).catch(() => {
						if (this.interval) {
							this.clear(); //清楚interval
						}
					})
				}

			})


		})
	}

	//新建三员管理员
	new = () => {
		this.openDialog("create");
		this.getAdminForm();
	}

	batchDelete = () => {
		const {
			showConfirm,
			tableStore
		} = this.tableListStore;

		const msg = getLabel(385625, '确定要删除选择的记录吗？');
		showConfirm(msg).then(() => {
			this.del({
				ids: tableStore.selectedRowKeys + ""
			})
		})
	}

	log = (id) => {
		this.tableListStore.showLog("3064", id);
	}

	del = (params) => {
		api.deleteAdmin(params).then(datas => {
			const {
				status
			} = datas;

			if (status === "1") {
				const params = this.searchStore.form.getFormParams();
				message.success(datas.message);
				this.tableListStore.fetchTableList(params);
				this.checkInitial().then(() => {
					if(!this.isInitialized){
						this.isStartInit = false;
						this.beforeInit();
					}
				})
			} else {
				message.warning(datas.message);
			}
		})
	}

	//搜索
	handleSearch = () => {
		const params = this.searchStore.form.getFormParams();
		this.tableListStore.fetchTableList(params);
	}

	//权限设置-高级搜索
	handleAuthSearch = () => {
		this.authTableListStore.fetchTableList({
			...this.authSearchStore.form.getFormParams(),
			roleId: this.roleId
		});
	}

	reRenderColumns = (columns) => {
		columns.map(column => {
			if (column.dataIndex === 'lastName') {
				column.render = (text, record) => {
					const {
						lastName,
						randomFieldId,
					} = record;

					return (
						<a onClick={() => {
							this.id = randomFieldId;
							this.doEdit(randomFieldId);
						}}>{lastName}</a>
					)
				}
			}
			if (column.dataIndex === 'rightCount') {
				column.render = (text, record) => {
					const {
						rightCountspan,
					} = record;

					return (
						<a onClick={() => this.doAuth(record)}>{rightCountspan}</a>
					)
				}
			}
		})
	}

	onOperatesClick = (record, rowIndex, operate) => {
		const {
			index
		} = operate, {
			randomFieldId: id,
			roleId,
		} = record;

		this.id = id;
		this.roleId = roleId;

		switch (index) {
			case '0':
				this.doAuth(record);
				break;
			case '1':
				this.doAuth(record, "3");
				break;
			case '2':
				this.dialogType = "safe";
				this.doSafe(record);
				break;
			case '3':
				this.doEdit(id);
				break;
			case '4':
				this.doDel(id);
				break;
			case '5':
				this.log(id);
				break;
		}
	}

	onAuthOperatesClick = (record, rowIndex, operate) => {
		const {
			index
		} = operate, {
			rightId,
			randomFieldId
		} = record;

		const {
			selectedKey
		} = this.authSearchStore;

		if (index === "0") {
			const msg = getLabel(83877, '确定要删除吗？');
			this.authTableListStore.showConfirm(msg).then(() => {
				const params = {
					roleId: this.roleId,
					id: this.id,
				};
				if (selectedKey === "2") {
					Object.assign(params, {
						rightIds: rightId,
					})
				} else {
					Object.assign(params, {
						ids: randomFieldId,
					})
				}
				this.deleteRight(params).then(() => {
					this.handleAuthSearch();
					this.handleSearch();
				});
			})
		}
	}

	//初始化之前，执行的动作
	beforeInit = () => {
		this.topStore.init(this.topConfig);
		this.topStore.fetchRightMenu();

		this.formStore.init(this.formConfig);
		this.formStore.fetchForm({}, this.exportDatas);
	}

	//初始化完成后，执行的动作。
	afterInit = () => {
		this.topStore.init(this.topConfig);
		this.topStore.fetchRightMenu(); //重新请求右键菜单

		const {
			init,
			fetchSearchForm
		} = this.searchStore;

		init(this.searchConfig); //初始化高级搜索配置
		fetchSearchForm().then(() => { //请求高级搜索表单数据
			const {
				init,
				fetchTableList
			} = this.tableListStore;

			init(this.tableConfig);
			const params = this.searchStore.form.getFormParams();
			fetchTableList(params); //请求列表数据
		})
	}

	startInit = () => {
		this.isStartInit = true;
	}

	finishInit = () => {
		this.percent = 100;
		setTimeout(() => {
			this.isInitFinish = true;
		}, 500)
	}

	startProcessing = () => {
		this.interval = window.setInterval(() => {
			if (this.percent < 99) {
				this.percent += 1;
			}
		}, 100)
	}

	clear = () => {
		window.clearInterval(this.interval);
	}

	resetStoreDatas = () => {
		this.isStartInit = false;
		this.isInitFinish = "";
	}

	save = () => {
		if (["create", "edit"].includes(this.dialogType)) {
			this.saveAdminInfo();
		}
		if (this.dialogType === "safe") {
			this.saveSafeSetting().then(() => {
				this.dialogStore.closeDialog();
				this.tableListStore.fetchTableList(this.searchStore.form.getFormParams());
			});
		}
	}

	saveAdminInfo = () => {
		const {
			validateForm,
			form
		} = this.formStore;

		validateForm(form).then(() => { //校验表单
			const {
				loginId,
				password
			} = form.getFormParams();

			this.checkLoginIdRepeat({ //校验账号是否重复
				loginId,
				id: this.id
			}).then(() => {
				if (
					this.checkPassword(password, this.passwordComplexity) && //校验密码复杂度
					this.isPassminlen(password.length, this.minPasslen) //校验密码长度
				) {
					this.addAdmin().then(() => { //添加三员管理员
						const params = this.searchStore.form.getFormParams();
						this.dialogStore.closeDialog(); //关闭弹框
						this.tableListStore.fetchTableList(params); //刷新列表
					})
				}
			})
		})
	}

	saveSafeSetting = () => {
		return new Promise((resolve, reject) => {
			const {
				validateForm,
				form,
				collectHideFormFieldKeys
			} = this.formStore, {
				userUsbType,
				needauto,
			} = form.getFormParams();

			const needValidateKeys = [];
			if (userUsbType === "4") {
				needValidateKeys.push("mobile");
			}
			if (userUsbType === "3") {
				needValidateKeys.push("tokenKey");
			}
			const hideKeys = collectHideFormFieldKeys(needValidateKeys);
			window.e9HideFormFieldKeys = hideKeys;

			validateForm(form).then(() => {
				api.saveSec({
					id: this.id,
					source: "sanyuan",
					...this.formStore.form.getFormParams()
				}).then(datas => {
					const {
						api_status,
						sign
					} = datas;

					if (api_status) {
						if (sign === "1") {
							resolve();
							message.success(datas.message);
						} else {
							reject();
							message.warning(datas.message)
						}
					}
				}).catch(() => {
					reject();
				})
			})
		})
	}

	//添加三员管理员
	addAdmin = () => {
		return new Promise((resolve, reject) => {
			const params = this.formStore.form.getFormParams();
			let apiName = "addAdmin";
			if (this.dialogType === "edit") {
				Object.assign(params, {
					id: this.id
				});
				apiName = "editAdmin";
			}
			api[apiName](params).then(datas => {
				const {
					status
				} = datas;

				if (status === "1") {
					message.success(datas.message);
					resolve();
				} else {
					message.warning(datas.message);
					reject();
				}
			}).catch(() => {
				reject()
			})
		})
	}

	//打开【新建、编辑管理员】弹窗
	openDialog = (type) => {
		const {
			init,
			openDialog
		} = this.dialogStore;

		this.dialogType = type;

		init(this.dialogConfig);
		openDialog();
	}

	getAdminForm = (id) => {
		const params = {};
		if (id) {
			Object.assign(params, {
				id
			})
		}
		this.formStore = new FormStore(this);
		this.formStore.init(this.adminFormConfig);
		this.formStore.fetchForm(params, this.exportDatas);
	}

	doEdit = (id) => {
		this.dialogType = "edit"
		this.getAdminForm(id);
		this.openDialog("edit");
	}

	//检测账号是否重复
	checkLoginIdRepeat = (params) => {
		return new Promise((resolve, reject) => {
			api.isLoginIdRepeat(params).then(datas => {
				const {
					status,
					isRepeat
				} = datas;

				if (status === '1') {
					if (!isRepeat) { //账号不重复
						resolve(true)
					} else {
						message.warning(getLabel(513993, "管理员账号重复！"));
						reject();
					}
				} else {
					message.warning(datas.message);
					reject();
				}
			}).catch(() => {
				reject();
			})
		})
	}

	//校验密码
	checkPassword = (password, complexity) => {
		const test = (regExps) => {
			return regExps.every(regExp => regExp.test(password))
		}
		if (complexity == '1') {
			const regExps = [/[a-z]+/, /[A-Z]+/, /\d+/];
			if (!test(regExps)) {
				message.warning(getLabel(533396, "新密码不符合要求，必须包含字母大写、字母小写、数字！请重新输入！"));
				return false;
			}
		}
		if (complexity == '2') {
			const regExps = [/[a-zA-Z_]+/, /\W+/, /\d+/];
			if (!test(regExps)) {
				message.warning(getLabel(533374, "新密码不符合要求，必须包含字母、数字、特殊字符！请重新输入！"));
				return false;
			}
		}
		if (complexity == '3') {
			const regExps = [/[a-zA-Z_]+/, /\d+/];
			if (!test(regExps)) {
				message.warning(getLabel(533397, "新密码不符合要求，必须包含字母、数字！请重新输入！"));
				return false;
			}
		}

		return true;
	}

	//校验密码长度
	isPassminlen(passlen, minpasslen) {
		if (passlen < minpasslen) {
			message.warning(`${getLabel('20172', "密码长度不能小于")}${ minpasslen}`);
			return false;
		} else {
			return true;
		}
	}

	exportDatas = (datas) => {
		["passwordComplexity", "minPasslen"].forEach(val => {
			this[val] = datas[val];
		})
	}

	//功能设置
	doAuth = (record, key) => {
		const {
			randomFieldId:id,
			roleId,
			lastNamespan,
		} = record;

		this.roleId = roleId;
		this.id = id;

		this.authSearchStore.init(this.authSearchConfig);
		this.authSearchStore.fetchTabs({id}); //请求页签数据
		this.authSearchStore.setSelectedKey(key ? key : "2"); //重置页签

		this.handleTabChange();

		this.dialogType = "auth";
		this.dialogStore.setTitle(`${lastNamespan}-${getLabel(16526,"权限设置")}`);
		this.dialogStore.init(this.authDialogConfig);
		this.dialogStore.openDialog(); //打开弹框
	}

	//安全设置
	doSafe = (record) => {
		const {
			randomFieldId: id,
			lastNamespan
		} = record;
		//请求表单
		const params = {
			id,
			source: "sanyuan"
		};
		this.formStore = new FormStore(this);
		this.formStore.init(this.safeFormConfig);
		this.formStore.fetchForm(params,datas => {
			this.usestateOption = this.getUsestateOption(datas.conditions)
		},this.handleCondition);

		//打开弹框
		this.dialogStore.setTitle(`${lastNamespan}-${getLabel(16526,"权限设置")}`);
		this.dialogStore.init(this.safeDialogConfig);
		this.dialogStore.openDialog();

		//检测二次验证密码是否开启
		this.checkUseSecondaryPwd(id);
	}

	getUsestateOption = (conditions) => {
		let options;
		 conditions.map(c => c.items.map(item => {
              if (item.domkey[0] == 'usbstate') {
                 options = item.options
              }
          }))
		 return options
	}

	doDel = (id) => {
		const msg = getLabel(83877, '确定要删除吗？');
		this.tableListStore.showConfirm(msg).then(() => {
			this.del({
				ids: id
			});
		})
	}

	checkUseSecondaryPwd = (id) => {
		api.isUseSecondaryPwd({
			id
		}).then(datas => {
			const {
				api_status,
				isSetted,
				isUse
			} = datas;

			if (api_status) {
				this.isSecondaryPwdSetted = isSetted;
			} else {
				message.warning(datas.message);
			}
		})
	}

	//停用【二次验证密码】
	saveUseSecondaryPwd = () => {
		return new Promise((resolve, reject) => {
			api.saveUseSecondaryPwd({
				id: this.id,
				useSecondaryPwd: false
			}).then(datas => {
				const {
					sign
				} = datas;

				if (sign === '1') {
					resolve()
				} else {
					message.warning(datas.message);
					reject();
				}

			}).catch(() => {
				reject();
			});
		})
	}

	setSecondaryPwdStatus = (bool) => {
		this.isSecondaryPwdSetted = bool;
	}

	handleUsbstateChange = () => {
		this.formStore.form.updateFields({
			needauto: "0"
		})
	}

	handleFormChange = (datas) => {
		if (datas.userUsbType ) {
			const{value} = datas.userUsbType;
			if(value === ""){
				this.formStore.form.updateFields({
					usbstate: "0"
				})
			}
			this.handleCondition();
		}
		const {usbstate} = this.formStore.form.getFormParams();

		if(usbstate && usbstate !== "1"){
			this.formStore.form.updateFields({
				needauto: "0"

			})
		}
	}

	handleAddIconClick = () => {
		this.formStore = new FormStore(this);
		this.formStore.init(this.authAddFormConfig);
		this.formStore.fetchForm({roleId: this.roleId});

		this.authAddDialogStore.init(this.authAddDialogConfig);
		this.authAddDialogStore.openDialog();

	}

	handleDelIconClick = () => {
		const msg = getLabel(385625, '确定要删除选择的记录吗？');
		this.authTableListStore.showConfirm(msg).then(() => {
			const {
				selectedKey
			} = this.authSearchStore;

			const params = {
				roleId: this.roleId,
				id: this.id,
			};

			if (selectedKey === "2") {
				Object.assign(params, {
					rightIds: this.authTableListStore.tableStore.selectedRowKeys + "",
				})
			} else {
				Object.assign(params, {
					ids: this.authTableListStore.tableStore.selectedRowKeys + "",
				})
			}
			this.deleteRight(params).then(() => {
				this.handleAuthSearch();
				this.handleSearch();
			});
		})
	}

	getCustomRenderItems = (list) => {
		const {
			conditions
		} = this.formStore;

		const items = {};

		conditions.forEach(condition => {
			condition.items.forEach(item => {
				const {
					domkey
				} = item;
				if (list.includes(domkey[0])) {
					Object.assign(items, {
						[domkey[0]]: item
					})
				}
			})
		})

		return items
	}

	saveAuth = () => {
		const {
			validateForm,
			form
		} = this.formStore, {
			type
		} = form.getFormParams();

		window.e9HideFormFieldKeys = [];

		if (type === "1") {
			window.e9HideFormFieldKeys = ["rightIds"];
		}

		validateForm(form).then(() => {
			this.addRight().then(() => {
				const params = {
					...this.authSearchStore.form.getFormParams(),
					roleId: this.roleId,
				};
				this.authAddDialogStore.closeDialog(); //关闭弹框
				this.authTableListStore.init(this.authTableConfig);
				this.authTableListStore.fetchTableList(params); //刷新功能权限或机构权限列表数据
				this.tableListStore.fetchTableList(this.searchStore.form.getFormParams()); //刷新三员维护列表数据
			})
		})

	}

	addRight = () => {
		return new Promise((resolve, reject) => {
			const params = {
				...this.formStore.form.getFormParams(),
				roleId: this.roleId,
				id: this.id,
			};
			let apiName = "addFuncRight";
			if (this.authSearchStore.selectedKey === "3") {
				apiName = "addSubComRight";
			}
			api[apiName](params).then(datas => {
				const {
					status
				} = datas;
				if (status === "1") {
					message.success(datas.message);
					resolve();
				} else {
					message.warning(datas.message);
					reject()
				}
			}).catch(() => {
				reject()
			})
		})
	}

	deleteRight = (params) => {
		return new Promise((resolve, reject) => {
			let apiName = "deleteFuncRight";
			if (this.authSearchStore.selectedKey === "3") {
				apiName = "deleteSubComRight";
			}
			api[apiName](params).then(datas => {
				const {
					status
				} = datas;
				if (status === "1") {
					message.success(datas.message);
					resolve();
				} else {
					message.warning(datas.message);
					reject();
				}
			}).catch(() => {
				reject()
			})
		})
	}

	handleTabChange = () => {
		//请求高级搜索表单数据
		this.authSearchStore.init(this.authSearchConfig);
		this.authSearchStore.fetchSearchForm().then(() => {
			//请求功能权限或机构权限列表数据
			const params = {
				...this.authSearchStore.form.getFormParams(),
				roleId: this.roleId
			}
			this.authTableListStore = new TableListStore(this);
			this.authTableListStore.init(this.authTableConfig);
			this.authTableListStore.fetchTableList(params);
		});
	}

	isLoginNameRepeat = () => {
		return new Promise((resolve, reject) => {
			const arr = [];
			["systemAdminLoginId", "secAdminLoginId", "secAuditorLoginId"].forEach(val => {
				arr.push(this.formStore.form.getFormParams()[val]);
			});
			if ([...new Set(arr)].length < 3) {
				message.warning(getLabel(513994, "管理员账号不能重复"));
				return true;
			};

			const promises = arr.map(val => {
				return this.checkLoginIdRepeat({
					loginId: val,
					id: this.id,
				})
			});

			Promise.all(promises).then(datas => {
				if (datas.some(data => !data)) {
					message.warning(getLabel(513994, "管理员账号不能重复"));
					reject();
				} else {
					resolve();
				}
			}).catch(() => {
				reject();
			});
		})



	}

	handleCondition = () => {
		const{form}= this.formStore;
		const {userUsbType} =form.getFormParams();
		this.formStore.conditions.map(c => c.items.map(item => {
          if (item.domkey[0] == 'usbstate') {
              item.options = (userUsbType == '6'||userUsbType == '901') ? this.usestateOption.slice(0,2):this.usestateOption
          }
      }))
	}


}

export const sanYuanStore = new SanYuanStore();