package com.fuzamei.service.serviceImpl;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.fuzamei.constant.OperationType;
import com.fuzamei.entity.Token;
import com.fuzamei.entity.User;
import com.fuzamei.entity.UserDetail;
import com.fuzamei.mapperInterface.LoginMapper;
import com.fuzamei.mapperInterface.UserMapper;
import com.fuzamei.service.LoginService;
import com.fuzamei.util.JSONUtil;
import com.fuzamei.util.blockchain.BlockChainUtil;
import com.fuzamei.util.blockchain.KeyUtils;
import com.fuzamei.util.blockchain.ProtobufBean;
import com.fuzamei.util.blockchain.ProtobufUtils;
@Service
public class LoginServiceImpl implements LoginService{
	@Autowired
	private LoginMapper  loginMapper;
	@Autowired
	private BlockChainUtil blockChainUtil;
	@Autowired
	private UserMapper userMapper;
	@Override
	public User queryUser(String username, String password) {
		return loginMapper.queryUser(username,password);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void updateToken(Integer userId, String token) {
		int num = loginMapper.updateToken(userId,token);
		if(num!=1){
			throw new RuntimeException("更改token失败");
		}
	}
	@Override
	@Transactional(rollbackFor=Exception.class)
	public void insertToken(Integer userId, String token) {
		int num = loginMapper.insertToken(userId,token);
		if(num!=1){
			throw new RuntimeException("插入token失败");
		}
	}

	@Override
	public UserDetail queryAdminExistence() {
		return loginMapper.queryAdminExistence();
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void insertAdmin(UserDetail user) {
		loginMapper.insertAdmin(user);
		loginMapper.insertToken(1,user.getToken());
		String random = user.getRandom();
		String password = user.getPassword();
		long uId = user.getUserId();
		String publicKey = KeyUtils.getPublicKey(KeyUtils.getPrivateKey(password, random));
		ProtobufBean protobufBean = ProtobufUtils.requestUserCreate(uId,publicKey);
		//下面往【操作记录】表插入数据
		Long currentTime = System.currentTimeMillis();//得到当前系统时间
		String hash = String.valueOf(protobufBean.getInstructionId());
		User pp=new User();
		pp.setUserId(user.getUserId());//操作人（管理员）
		pp.setOperationTypeId(OperationType.CREATE);//操作类型 (创建管理员)
		pp.setUserIdb(user.getUserId());//这里是被操作人账号 (还是管理员)
		pp.setOperationTime(currentTime);//操作时间
		pp.setHash(hash);//操作hash
		userMapper.insertOperationHistory(pp);//插入到操作记录表去
		//丢区块链
    	String result = BlockChainUtil.sendPostParam(protobufBean);
    	boolean flag = BlockChainUtil.vilaResult(result);
		if(!flag) throw new RuntimeException("区块链操作失败");
	}
	
	
	
	
}
