package com.ssj.service.sys.role.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.sys.fx.domain.MerchantArea;
import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.bean.sys.role.domain.AdminRole;
import com.ssj.bean.sys.role.domain.Role;
import com.ssj.dao.sys.role.dao.AdminDao;
import com.ssj.dao.sys.role.dao.AdminRoleDao;
import com.ssj.dao.sys.role.dao.RoleQueryDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.basic.utils.MD5;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.persistence.DynamicSpecifications;
import com.ssj.framework.core.persistence.SearchFilter;
import com.ssj.framework.core.util.RedisUtil;
import com.ssj.service.sys.fx.service.MerchantAreaService;
import com.ssj.service.sys.fx.service.MerchantService;
import com.ssj.service.sys.role.service.AdminService;
import com.ssj.service.sys.role.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
@Service(version = "1.0")
@Transactional
public class AdminServiceImpl extends BaseServiceImpl<Admin, String> implements AdminService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
    private AdminDao adminDao;
	
	@Autowired
    private RoleService roleService;
	
	@Autowired
    private MerchantService merchantService;
	
	@Autowired
	private RoleQueryDao roleQueryDao;

	@Autowired
	private AdminRoleDao adminRoleDao;
	
	@Autowired
	private MerchantAreaService merchantAreaService;
	
	@Autowired
	private RedisUtil redisUtil;
	
	@Override
	public PagingAndSortingRepository<Admin, String> getDao() {
		return adminDao;
	}
	@Override
	public Page<Admin> findByPage(Map<String, Object> params, Pageable sp)
			throws Exception {
		 Map<String, SearchFilter> filters = SearchFilter.parse(params);
	     Specification<Admin> specification = DynamicSpecifications.bySearchFilter(filters.values(), Admin.class);
	     return adminDao.findAll(specification, sp);
	}
	@Override
	public boolean validateLoginName(String loginName, String id) {
		Integer i=adminDao.validateLoginName(loginName, id);
		if(i>0){
			return false;
		}
		return true;
	}
	@Override
	public Admin longin(String loginName, String password) {
		password = MD5.getMD5(password.getBytes());
		Admin admin =	adminDao.longin(loginName, password);
		if(admin!=null){
			List<String> authorities = new ArrayList<>();
			List<AdminRole> adminRoleList=adminRoleDao.findByAdminId(admin.getId());
			for (AdminRole adminRole : adminRoleList) {
				Role role = roleService.getById(adminRole.getRoleId());
				authorities.add(role.getName());
			}
			admin.setAuthorities(authorities);
			
			//清空前面登录错误的记录
			try {
				Set<String> loginKeys =  redisUtil.keys("LOGIN_"+loginName+"_*");
				if(loginKeys!=null && loginKeys.size()>=1) {
					String[] delKeys=new String[loginKeys.size()];
					redisUtil.del(loginKeys.toArray(delKeys));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else {
			//记录一次登录错误的信息
			redisUtil.set("LOGIN_"+loginName+"_"+System.currentTimeMillis(), "1",30*60);
		}
		return admin;
	}
	@Override
	public Page<Map<String, Object>> findByPageMap(Map<String, Object> params,
			Pageable sp) throws Exception {
		return roleQueryDao.findByPageMap(params, sp);
	}
	@Override
	public Admin getByLoginName(String loginName) {
		return adminDao.getByLoginName(loginName);
	}
	@Override
	public Admin saveFXAdmin(Merchant merchant, String password,String sessionUserName,
			String province,String city,String area,String schoollist,String ip){
		Admin admin=new Admin();
		admin.setLoginName(merchant.getPosCode());
		admin.setNickName(merchant.getPosCode());
		admin.setCreateTime(new Date());
		admin.setPassword(MD5.getMD5(password.getBytes()));
		admin.setStatus(1);
		admin=this.save(admin);
		
		roleService.saveAdminRole(admin.getId(), "eadc6389-6a29-4864-bce6-a18b30e0a998");
		
		Merchant newMerchant =merchantService.getMerchantByPosCode(merchant.getPosCode());
		if(newMerchant==null){
			String code="SSJ-FX";
			if(StringUtils.isNotEmpty(merchant.getParentPosCode())){
				Merchant pMerchant =merchantService.getMerchantByPosCode(merchant.getParentPosCode());
				code=pMerchant.getOrgCode()+"-"+merchant.getPosCode();
			}else{
				code=code+"-"+merchant.getPosCode(); 
			}
			merchant.setCreateTime(new Date());
			merchant.setSaleLoginName(sessionUserName);
			merchant.setOrgCode(code);
			merchant.setCurIsSummary(0);
			merchant=merchantService.save(merchant);
			
			if(StringUtils.isNotEmpty(schoollist)) {
				List<MerchantArea> merchantAreas=new ArrayList<MerchantArea>();
				String[] areaIds=schoollist.split(";");
				for (String areaId : areaIds) {
					MerchantArea merchantArea=new MerchantArea();
					merchantArea.setCnAreaId(areaId);
					merchantArea.setCreateTime(new Date());
					merchantArea.setMerchantId(merchant.getId());
					merchantAreas.add(merchantArea);
				}
				merchantAreaService.save(merchantAreas);
			}
			merchantService.save(merchant);
			//计算结算日期。
			merchantService.computeMerchantSummaryTime(merchant);
			merchantService.syncRecordByMerchant(sessionUserName, merchant.getId(),ip, "新增商户");
		}
		return admin;
	}


	@Override
	public boolean loginLocking(String loginName, String clientType) {
		boolean isLock = false;
		try {
			Set<String> lockLoginKeys = redisUtil.keys("LOGIN_LOCK_" + loginName + "_" + clientType + "_*");
			if (lockLoginKeys != null && lockLoginKeys.size() >= 1) {
				isLock = true;
			} else {
				Set<String> loginKeys = redisUtil.keys("LOGIN_" + loginName + "_" + clientType + "_*");
				if (loginKeys != null && loginKeys.size() >= 5) {
					redisUtil.set("LOGIN_LOCK_" + loginName + "_" + clientType + "_" + System.currentTimeMillis(),
							String.valueOf(System.currentTimeMillis()), 30 * 60);
					String[] delKeys = new String[loginKeys.size()];
					redisUtil.del(loginKeys.toArray(delKeys));
					isLock = true;
				}
			}
		} catch (Exception e) {
			logger.error("校验账号是否锁定异常", e);
		}
		return isLock;
	}

}
