<template>
	<lj-win-common  title="账套管理" body-class="login-body" show-back>
		<div slot="body" class="login-mng-wrap">
			<van-cell-group
				v-for="(items, index) in isAccountList"
				:key="index"
				:title="items.title"
				class="accounts-wrapper"
			>
				<van-swipe-cell
					:ref="`swipeCell${index}`"
					v-for="(item, idx) in items.accounts"
					:key="idx"
					class="accounts-item"
					:class="{'checked': item.checked}"
					:disabled="item.checked"
				>
					<van-cell
						:label="item.usercode"
						class="lj-cell-left"
						@click="handleClickAccount(item)"
					>
						<template slot="icon">
							<div class="item-icon">
								{{ item.simplename }}
							</div>
						</template>
						<template slot="title">
							<span class="item-title">
								{{ item.username }}
							</span>
							<van-tag :plain="!item.checked" :color="item.checked ? '#2894FF': '#8B8B8B'" v-if="item.connectMode">
								{{ isConnectModeTitle(item.connectMode) }}
							</van-tag>
							<van-tag plain color="#2894FF" v-if="item.checked && item.connectMode == ipAndTransitMode">
								{{ isShowRequestWayText }}
							</van-tag>
						</template>
						<template>
							<div class="item-default" v-if="item.checked">
								<i class="iconfont icon-tongyi" style="color: #2894FF;" v-show="item.checked"></i>
							</div>
							<van-tag plain type="danger" v-else-if="item.failConnect">
								{{ item.failConnect }}
							</van-tag>
							<div class="item-default" v-else>
								<i class="iconfont icon-more" style="color: #8B8B8B;" @click.stop="handleOpenRight(index, idx)"></i>
							</div>
						</template>
					</van-cell>
					<template #right>
						<van-button class="login-btn" type="danger" text="删除" @click="handleDelAccount(item)" />
					</template>
				</van-swipe-cell>
			</van-cell-group>
		</div>

		<div slot="footer">

			<van-row class="login-control">
				<van-col span="12" v-if="usercode">
					<van-button class="login-btn shadow" type="danger" block round @click="handleLogoutConfrim">
						<i slot="icon" class="iconfont icon-logout"></i>
						退出登录
					</van-button>
				</van-col>
				<van-col :span="usercode ? 12 : 24">
					<van-button class="login-btn shadow" plain type="info" block round @click="handleClickAddAccount(true)">
						<i slot="icon" class="iconfont icon-ic_add"></i>
						新增账套
					</van-button>
				</van-col>
			</van-row>
			<mu-dialog title="操作提示" :esc-press-close="false" :overlay-close="false" :open.sync="showLogout">
				<div>
					{{ `是否退出【${currentAccount}】:${usercode}？` }}
					<div style="margin-top:5px;">
						<mu-checkbox v-model="ifClearPW" label="并清除登录记录"></mu-checkbox>
					</div>
				</div>
				
				<div class="dialog-footer" style="text-align: center;margin-top:30px">
					<mu-button @click="showLogout = false">取 消</mu-button>
					<mu-button color="#ee0a24" @click="handleClickLogout">退 出</mu-button>
				</div>
			</mu-dialog>
		</div>
	</lj-win-common>
</template>

<script>
	import LjWinCommon from "components/lj-win-common";
	import {Cell, CellGroup, Tag, Row, Col, Button, SwipeCell} from 'vant'

	export default {
		components: {
			LjWinCommon,
			"van-cell": Cell,
			"van-cell-group": CellGroup,
			"van-tag": Tag,
			"van-row": Row,
			"van-col": Col,
			"van-button": Button,
			"van-swipe-cell": SwipeCell,
		},
		data() {
			return {
				accountList: [],
				serverConnectParams: {},
				currentAccount: '',
				usercode: '',
				connectMode: '',
				transitMode: "transit",
                ipMode: "ip",
                ipAndTransitMode: "ip&transit",
				showLogout: false,
				ifClearPW: false,
                hasLoading: false,
				serverCurrentRequestWay: '',
			}
		},
		computed: {
			isShowRequestWayText() {
				switch (this.serverCurrentRequestWay) {
					case 'DIRECT':
						return 'IP';
					case 'TRANSIT':
						return '中转';
				}
				return ''
			},
			isAccountList: function() {
				let list = [];
				let hasAccount = [];
				for (let i = 0; i < this.accountList.length; i++) {
					let item_account = this.accountList[i].account;
					let hasIndex = hasAccount.indexOf(item_account);
					if (hasIndex > -1) {
						list[hasIndex].accounts.push(this.accountList[i]);
					} else {
						hasAccount.push(item_account);
						let obj = {};
						obj.title = item_account;
						obj.accounts = [];
						obj.accounts.push(this.accountList[i]);
						list.push(obj);
					}
				}
				return list
			},
			isConnectModeTitle(type) {
				return function(type) {
					let title = '';
					switch (type) {
						case this.ipMode:
							title = 'IP连接';
							break;
						case this.transitMode:
							title = '中转连接';
							break;
						case this.ipAndTransitMode:
							title = '择优连接';
							break;
						default:
							break;
					}
					return title;
				}
			}
		},
		created() {
			let self = this;
			$lj.addEventListener('login_byaccount', function(ret) {
				setTimeout(function () {
                    self.handleLoginSuccess();
                },1000);
			})
			this.accountList = $lj.getStorage('cacheAccount') || [];
			console.log('looooooing mng -----------this.accountList :>> ', JSON.stringify(this.accountList));
			this.serverConnectParams  = $lj.getStorage('serverConnectParams');
			this.usercode = $lj.getStorage('loginRememberUser');
			this.currentAccount = $lj.getStorage("lastLoginAccount");
			console.log('looooooing mng -----------this.usercode :>> ', JSON.stringify(this.usercode));
			if (this.accountList.length > 0) {
				for(let i in this.accountList) {
					let account = this.accountList[i];
					account.simplename = account.username.substring(account.username.length - 1, account.username.length)
				}
			}
			this.serverCurrentRequestWay = $lj.getPrefs('serverCurrentRequestWay');
		},
		methods: {
			_fnLoading(state, loadingTitle = '加载中') {
					if (state) {
							api.showProgress({
									title: loadingTitle,
									text: '请稍候...',
									modal: false
							});
					} else {
							api.hideProgress();
					}
			},
			handleDelAccount(item) {
				for (let i = 0; i < this.accountList.length; i++) {
					let eachAcc = this.accountList[i];
					if (eachAcc.account == item.account && eachAcc.usercode == item.usercode) {
						this.accountList.splice(i, 1);
						$lj.toast("账号记录删除成功", 1500, "top")
						break;
					}
				}
				$lj.setStorage('cacheAccount', this.accountList);
			},
			handleClickAccount(acc) {
				let self = this;
				$lj.confirm('登录', '是否确认登陆【' + acc.usercode + '】', function() {
					// let oldToken = $lj.getStorage("token");
					// let lastServerConnect = $lj.getStorage("serverConnectParams");
					// let newServerConnect = {
					// 	ip: acc.ip,
					// 	port: acc.port,
					// 	cusid: acc.cusid
					// };

					self._autoChangeAccount(acc);
					self.handleLoginSuccess();
					// self._autoChangeConnet(acc, newServerConnect, function(errCode, errMsg) {
					// 	self.$set(acc, "failConnect", errCode)
					// 	self._fnLoading(true, "重连账套");
					// 	$lj.setStorage("serverConnectParams", lastServerConnect);
					// 	$lj.initServerConnect();

					// 	console.log('accountList _____________________ :>> ', JSON.stringify(self.accountList));

					// 	setTimeout(() => {
					// 		$lj.toast(errMsg)
					// 		self._fnLoading(false);
					// 	}, 800);
					// });	
				})
			},
			_autoChangeConnet(acc, newServerConnect, failCallBack) {
				let self = this;
				let oldToken = $lj.getStorage("token");
				self._fnLoading(true, '正在切换');
				console.log('oldToken oldToken oldToken :>> ', JSON.stringify(oldToken));
				// if(oldToken){
				// 	$lj.postLJRequest("NotifyUsersKicked", {tokens: [oldToken], fromClient: 1}, function() {
						
				// 		self._autoGetAccount(acc, newServerConnect, failCallBack);
				// 	}, function () {
				// 		self._autoGetAccount(acc, newServerConnect, failCallBack);
				// 	}, true);
				// } else {
					// 登出账号后
					// this._autoChangeAccount(acc);
					// this.handleLoginSuccess();
					self._autoGetAccount(acc, newServerConnect, failCallBack)
				// }
			},
			_autoGetAccount(acc, newServerConnect, failCallBack) {
				let self = this;
				self._fnLoading(true, '切换账套');

				$lj.setStorage("serverConnectParams", newServerConnect);
				$lj.initServerConnect();
				$lj.postLJRequest("GetToken", {}, function (ret) {
					if (ret.accounts && ret.accounts.length > 0) {
						self._fnLoading(false);
						self._autoChangeAccount(acc);
						self.handleLoginSuccess();
					} else {
						$lj.toast('当前账套0', 1500, 'bottom')
						if (failCallBack) {
							failCallBack('无账套', '账套获取成功[0]');
						} else {
							self._fnLoading(false);
						}
					}
				}, function (err) {
					$lj.toast(err.errCode, 1500, 'bottom')
					if (failCallBack) {
						failCallBack(err.errCode, err.errMsg);
					} else {
						self._fnLoading(false);
					}
				}, true)
			},
			_autoChangeAccount(acc) {
				$lj.setStorage("token", acc.token);
				$lj.setStorage("lastLoginAccount", acc.account);
				$lj.setStorage("user", {
					token: acc.token,
					usercode: acc.usercode,
					username: acc.username,
				});
				$lj.setStorage("loginRememberUser", acc.usercode ? acc.usercode : "");

				this.accountList.forEach((eachAcc) => {
					if (eachAcc.account == acc.account && eachAcc.usercode == acc.usercode) {
						eachAcc.token = acc.token;
						eachAcc.ip = acc.ip;
						eachAcc.port = acc.port;
						eachAcc.cusid = acc.cusid;
						eachAcc.username = acc.username;
						eachAcc.checked = true;
						eachAcc.failConnect = '';
					} else{
						eachAcc.checked = false;
					}
					
				});

				$lj.setStorage('cacheAccount', this.accountList);
			},
			handleClickAddAccount(ifFirstLogin) {
				$lj.openWin('login', {isRelogin: true, ifOpenMng: true, ifFirstLogin: ifFirstLogin});
			},
			handleLogoutConfrim() {
				this.showLogout = true;
			},
			handleClickLogout() {
				this.showLogout = false;
				if (this.ifClearPW) {

					let userHistory = $lj.getStorage("userHistory");
					if (typeof userHistory !== "object") {
						userHistory = {};
					}
					let userHistoryAccount = $lj.getStorage("userHistoryAccount");
					if (userHistoryAccount == undefined) {
						userHistoryAccount = [];
					}
	
					console.log('_setUserHistory this.userHistoryAccount :>> ', JSON.stringify(userHistoryAccount));
					let index = -1;
					if (userHistoryAccount.length > 0) {
						for (let i = 0; i < userHistoryAccount.length; i++) {
							if (userHistoryAccount[i].name == this.currentAccount) {
								index = i;
								break;
							}
						}
						if (index > -1) {
							if (userHistoryAccount[index].account.hasOwnProperty(this.usercode)) {
								delete userHistoryAccount[index].account[this.usercode]
								console.log('删除密码后userHistoryAccount~~~~~~~~ :>> ', JSON.stringify(userHistoryAccount));
								$lj.setStorage("userHistoryAccount", userHistoryAccount);
							}
						}
					}
					if (index == -1) {
						if (userHistory.hasOwnProperty(this.usercode)) {
							delete userHistory[this.usercode]
							console.log('删除密码后userHistory~~~~~~~~ :>> ', JSON.stringify(userHistory));
							$lj.setStorage("userHistory", userHistory);
						}
					}

				}

				for(let i in this.accountList) {
					if (this.accountList[i].checked) {
						if (this.ifClearPW) {
							// 清除登录记录
							this.accountList.splice(i, 1);
						} else {
							this.accountList[i].checked = false;
						}
						break;
					}
				}
				$lj.setStorage('cacheAccount', this.accountList);
				// $lj.setStorage("serverConnectParams", "")
				// $lj.setStorage("lastLoginAccount", "");

				// $lj.postLJRequest("NotifyUsersKicked", {tokens: [$lj.getStorage("token")], fromClient: 1}, (ret) => {
					$lj.setStorage("user", "");
					$lj.setStorage("token", "");
					$lj.setStorage("loginRememberUser", "");
					this.usercode = "";
					$lj.openWin('login', {isRelogin: false, ifOpenMng: true});
				// });
			},
			handleLoginSuccess(){
					$lj.toast("登录成功");
					$lj.sendEvent("login_success", {reload: true});
					$lj.closeWin("login");
					$lj.closeWin();
			},
			handleOpenRight(index, idx) {
				this.$refs[`swipeCell${index}`][idx].open({position: 'right'});
			}
		}
	}
</script>

<style lang="less">
    @import "~assets/css/lj-style-variable.less";
    @import "~assets/css/lj-pda.less";

	.login-body {
		background-color: @homeModuleTitleBackgroundColor;
	}
	.acc_item {
		padding: 10px 0;
	}
	.footer {
		padding: 10px 10px;
		padding-top: 0;
	}
	.mu-paper {
		background-color: unset!important;
		box-shadow: unset!important;;
	}
	.login-control {
		display: block;

		.van-col {
			display: flex;
		}
		.login-btn {
			margin: 0 5px;
		}
	}
	.login-mng-wrap {
		padding-top: 15px;
		.van-cell-group__title {
			padding-top: 8px;
			padding-bottom: 0;
			color: #666;
		}
		.accounts-wrapper {
			margin: 10px 15px;
			background-color: transparent!important;

			.van-hairline--top-bottom::after, .van-hairline-unset--top-bottom::after {
				border: 0;
			}
			.van-cell::after {
				content: none;
			}
	
			.accounts-item {

				& + .accounts-item {
					margin-top: 10px;
				}
				.lj-cell-left {
					border-radius: 10px;

				}
				.login-btn {
					display: flex;
					border-radius: 10px;
					margin-left: 10px;
					height: 100%;
				}
				.item-title {
					margin-right: 10px;
					font-size: 14px;
					font-weight: 600;
				}
				.item-icon {
					margin-right: 10px;
					border-radius: 8px;
					width: 42px;
					height: 42px;
					line-height: 42px;
					text-align: center;
					font-size: 24px;
					font-weight: 600;
					background-color: #e5e5e5;
				}
				&.checked {
					.item-icon {
						background-color: #2894FF;
						color: #fff;
					}
				}
			}
		}
	}
</style>