package com.hotent.uc.manager.impl;


import java.util.*;

import com.hotent.base.util.*;
import com.hotent.uc.util.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.PageBean;
import com.hotent.base.query.PageList;
import com.hotent.base.query.QueryFilter;
import com.hotent.base.query.QueryOP;
import com.hotent.uc.dao.ElectronicSealDao;
import com.hotent.uc.manager.ElectronicSealManager;
import com.hotent.uc.manager.PwdStrategyManager;
import com.hotent.uc.manager.UserManager;
import com.hotent.uc.model.ElectronicSeal;
import com.hotent.uc.model.PwdStrategy;
import com.hotent.uc.model.User;
import com.hotent.uc.params.seal.ImportSignatureObject;
import com.hotent.uc.params.seal.UserSignature;

import javax.annotation.Resource;

/**
 * 
 * <pre> 
 * 描述：uc_electronic_seal 处理实现类
 * 构建组：x7
 * 作者:lihq
 * 邮箱:lihq@jee-soft.cn
 * 日期:2020-10-19 18:18:31
 * 版权：广州宏天软件股份有限公司
 * </pre>
 */
@Service("electronicSealManager")
public class ElectronicSealManagerImpl extends BaseManagerImpl<ElectronicSealDao, ElectronicSeal> implements ElectronicSealManager {

	@Autowired
	UserManager userManager;
	@Autowired
	PwdStrategyManager pwdStrategyManager;
	@Resource
	ElectronicSealManager electronicSealManager;
	@Autowired
	PasswordEncoder passwordEncoder;
	
    @Override
    public void setIsUse(String id) {
        super.update(new UpdateWrapper<ElectronicSeal>().set("IS_USE_",1).eq("ID_",id));
    }

	@Override
	@Transactional
	public CommonResult<String> importSignature(ImportSignatureObject signatureData) throws Exception {
		if(BeanUtils.isNotEmpty(signatureData) && BeanUtils.isNotEmpty(signatureData.getSignatureList())){
			List<UserSignature> list = signatureData.getSignatureList();
			List<String> accounts = new ArrayList<String>();
			Map<String,String> signatureMap = new HashMap<String,String>();
			PwdStrategy pwdStrategy = pwdStrategyManager.getDefault();
			for (UserSignature userSignature : list) {
				accounts.add(userSignature.getAccount());
				signatureMap.put(userSignature.getAccount(), userSignature.getFileId());
			}
			//根据账号获取所有相关用户
			QueryFilter filter = QueryFilter.build();
			filter.withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
			filter.addFilter("ACCOUNT_", accounts, QueryOP.IN);
			filter.addFilter("IS_DELE_", "1", QueryOP.NOT_EQUAL);
			PageList<User> page = userManager.query(filter);
			List<User> users = page.getRows();
			if(BeanUtils.isNotEmpty(users) && users.size()>0){
				List<ElectronicSeal> newSeals = new ArrayList<ElectronicSeal>();
				for (User user : users) {
					// 判断当前用户是否存在正在使用的签章
					ElectronicSeal seal = this.getOne(new QueryWrapper<ElectronicSeal>().eq("USER_ID_", user.getId()).eq("IS_USE_", 0));
					if(BeanUtils.isNotEmpty(seal) && signatureData.isRepeatConver()){
						this.setIsUse(seal.getId());
						newSeals.add(this.getNewSeal(user.getId(), signatureMap.get(user.getAccount()), pwdStrategy.getInitPwd()));
					}else if(BeanUtils.isEmpty(seal)){
						newSeals.add(this.getNewSeal(user.getId(), signatureMap.get(user.getAccount()), pwdStrategy.getInitPwd()));
					}
				}
				if(BeanUtils.isNotEmpty(newSeals)){
					boolean isSuccess = this.saveBatch(newSeals);
					if(!isSuccess){
						throw new RuntimeException("签章数据批量插入失败！");
					}
				}
			}
		}
		return new CommonResult<String>(true, "处理成功！");
	}

	/**
	 * 新增uc_electronic_seal
	 * 新增签章
	 * @param electronicSeal
	 * @return
	 * @throws Exception
	 */
	@Override
	public CommonResult<String> saveElectronicSeal(ElectronicSeal electronicSeal) throws Exception {
		String msg = "添加签章成功";
		String currentUserId = electronicSeal.getUserId();
		ElectronicSeal seal = this.getOne(new QueryWrapper<ElectronicSeal>().eq("USER_ID_", currentUserId).eq("IS_USE_", 0));
		if(BeanUtils.isEmpty(seal)){
			electronicSeal.setIsUse(0);
			electronicSeal.setPassword(encryptSealPassword(electronicSeal.getPassword())); // 对密码进行加密处理
			this.create(electronicSeal);
		}else{
			// 将之前签章的状态改掉
			this.setIsUse(seal.getId());
			ElectronicSeal electronicSealNew = new ElectronicSeal();
			electronicSealNew.setUserId(electronicSeal.getUserId());
			electronicSealNew.setIsUse(0);
			electronicSealNew.setFileId(electronicSeal.getFileId());
			if (StringUtil.isEmpty(electronicSeal.getPassword())){
				ElectronicSeal electronicSealOld = this.get(electronicSeal.getId());
				electronicSealNew.setPassword(electronicSealOld.getPassword());
			}else {
				electronicSealNew.setPassword(encryptSealPassword(electronicSeal.getPassword()));
			}
			this.create(electronicSealNew);
		}
		return CommonResult.<String>ok().value(msg);
	}

	/**
	 * front用户自己添加电子签章
	 * @param electronicSeal
	 * @return
	 * @throws Exception
	 */
	@Override
	public CommonResult<String> userSaveElectronicSeal(ElectronicSeal electronicSeal) throws Exception {
		String msg = "添加签章成功";
		User user = ContextUtil.getCurrentUser();
		if (!user.getPassword().equals(passwordEncoder.encode(electronicSeal.getOldPassWord()))){
			return new CommonResult<String>(false,"您输入的登录密码不正确");
		}
		if(StringUtil.isEmpty(electronicSeal.getId())){
			electronicSeal.setIsUse(0);
			electronicSeal.setUserId(user.getId());
			electronicSeal.setPassword(encryptSealPassword(electronicSeal.getPassword())); // 对密码进行加密处理
			this.create(electronicSeal);
		}else{
			if (StringUtil.isEmpty(electronicSeal.getOldPassWord())){
				return new CommonResult<String>(false,"请输入登录密码");
			}
			// 判断当前用户是否存在正在使用的签章
			ElectronicSeal seal = this.getOne(new QueryWrapper<ElectronicSeal>().eq("USER_ID_", user.getId()).eq("IS_USE_", 0));
			if (BeanUtils.isNotEmpty(seal)){
				// 拿到旧密码与当前密码进行比对，判断输入是否正确
				// 将之前的签章状态修改掉
				this.setIsUse(electronicSeal.getId());
				ElectronicSeal electronicSealNew = new ElectronicSeal();
				electronicSealNew.setUserId(user.getId());
				electronicSealNew.setIsUse(0);
				electronicSealNew.setFileId(electronicSeal.getFileId());
				if (StringUtil.isNotEmpty(electronicSeal.getPassword())){
					// 再用户输入了密码就修改密码。否则不修改密码，直接使用原密码
					electronicSealNew.setPassword(encryptSealPassword(electronicSeal.getPassword()));
				}else{
					electronicSealNew.setPassword(seal.getPassword());
				}
				this.create(electronicSealNew);
			}else{
				return new CommonResult<String>(false,"未获取到正在使用的签章。");
			}
		}
		return new CommonResult<String>(true,msg);
	}

	/**
	 * 手机端更新签章
	 * @param electronicSeal
	 * @return
	 * @throws Exception
	 */
	@Override
	public CommonResult<String> mobileUpdateElectronicSeal(ElectronicSeal electronicSeal) throws Exception {
		if (StringUtil.isEmpty(electronicSeal.getPassword())){
			return new CommonResult<>(false,"请输入签章密码");
		}
		User user = ContextUtil.getCurrentUser();
		ElectronicSeal electronicSealOld = this.getOne(new QueryWrapper<ElectronicSeal>().eq("IS_USE_", 0).eq("USER_ID_", user.getId()));
		if (BeanUtils.isNotEmpty(electronicSealOld)){
			if (!user.getPassword().equals(passwordEncoder.encode(electronicSeal.getOldPassWord()))){
				return new CommonResult<>(false,"您输入的登录密码不正确，不可更新签章");
			}
			electronicSealOld.setIsUse(1);
			this.update(electronicSealOld);
			electronicSeal.setUserId(user.getId());
			electronicSeal.setIsUse(0);
			electronicSeal.setPassword(encryptSealPassword(electronicSeal.getPassword()));
			this.create(electronicSeal);
		}else{
			return new CommonResult<>(false,"您没有签章，请在应用端添加签章后，方可使用");
		}
		return new CommonResult<>(true,"更新签章成功");
	}

    @Override
    public ElectronicSeal getCurrentUserSeal() {
		// 获取当前登录用户ID
		String currentUserId = AuthenticationUtil.getCurrentUserId();
		ElectronicSeal electronicSeal = getOne(new QueryWrapper<ElectronicSeal>().eq("IS_USE_", 0).eq("USER_ID_", currentUserId));
		// 把密码制空，不返回给前端
		if (BeanUtils.isEmpty(electronicSeal)){
			return null;
		}
		electronicSeal.setPassword("");
		return electronicSeal;
    }

    @Override
    public CommonResult<String> getUser(Optional<String> password, Optional<Boolean> secretFree) throws Exception {
		boolean isSecretFree = secretFree.orElse(false);
		if (!isSecretFree && StringUtil.isEmpty(password.get())){
			return new CommonResult<>(false,"请输入签章使用密码");
		}
		String currentUserId = AuthenticationUtil.getCurrentUserId();
		ElectronicSeal electronicSeal = electronicSealManager.getOne(new QueryWrapper<ElectronicSeal>().eq("IS_USE_", 0).eq("USER_ID_", currentUserId));
		if (BeanUtils.isEmpty(electronicSeal)){
			return new CommonResult<>(false,"您还未设置签章，请在个人信息中设置您的签章");
		}else if (!isSecretFree && !electronicSeal.getPassword().equals(encryptSealPassword(password.get()))){
			return new CommonResult<>(false,"签章使用密码错误，请重新输入");
		}else{
			return new CommonResult<>(true,"获取成功！",electronicSeal.getFileId());
		}
    }

    /**
	 * 初始化一条用户签章记录
	 * @param userId
	 * @param fileId
	 * @param pwd
	 * @return
	 * @throws Exception
	 */
	private ElectronicSeal getNewSeal(String userId,String fileId,String pwd) throws Exception{
		ElectronicSeal newSeal = new ElectronicSeal();
		newSeal.setId(UniqueIdUtil.getSuid());
		newSeal.setIsUse(0);
		newSeal.setUserId(userId);
		newSeal.setFileId(fileId);
		newSeal.setPassword(EncryptUtil.encrypt(pwd)); // 对密码进行加密处理
		return newSeal;
	}

	/**
	 * 对签章密码进行加密
	 * @param blankPswd
	 * @return
	 * @throws Exception
	 */
	private String encryptSealPassword(String blankPswd) throws Exception {
		return EncryptUtil.encrypt(blankPswd);
	}
}
