package com.fuzamei.service.serviceImpl;

import java.util.List;
import java.util.Map;

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.constant.Roles;
import com.fuzamei.entity.PlannerSupplier;
import com.fuzamei.entity.User;
import com.fuzamei.mapperInterface.PlannerMapper;
import com.fuzamei.mapperInterface.ReceivingClerkMapper;
import com.fuzamei.mapperInterface.UserMapper;
import com.fuzamei.service.PlannerService;
import com.fuzamei.util.blockchain.BlockChainUtil;
import com.fuzamei.util.blockchain.ProtobufBean;
@Service
public class PlannerServiceImpl implements  PlannerService{
  @Autowired
  private PlannerMapper  plannerMapper;
  @Autowired
  private UserMapper userMapper;
  @Autowired
  private BlockChainUtil blockChainUtil;
	@Override
	public List<User> queryPlanner(Map<String, Object> map) {
		 return plannerMapper.queryPlanner(map);
    }

	@Override
	public List<User> queryAllSupplierByPlannerId(int plannerId) {//根据计划员id查询已经有的供应商
		return plannerMapper.queryAllSupplierByPlannerId(plannerId);
	}

	@Override
	public List<User> queryAllNoSupplierByPlannerId(int plannerId) {////根据计划员id查询未添加的供应商
		return plannerMapper.queryAllNoSupplierByPlannerId(plannerId);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void deleteBeforeSupplierByUserId(int plannerId) {//根据计划员id删除之前所有的供应商
	
		plannerMapper.deleteBeforeSupplierByUserId(plannerId);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void insertAgainSupplier(User pp) {//得到前端传来所有得供应商ID 做插入操作
		String supplierIds = pp.getSupplierId();//前端传来的供应商id(格式1111,111,111,111)
		deleteBeforeSupplierByUserId(Integer.parseInt(pp.getPlannerId()));//删除计划员下面的所有供应商
		if(!(supplierIds==null||"".equals(supplierIds))){
			//下面是【循环添加供应商得id】
			pp.setSupplierIds(supplierIds.split(","));
			plannerMapper.insertAgainSupplier(pp);
		}
		//下面往【操作记录】表插入数据
		Long currentTime = System.currentTimeMillis();//得到当前系统时间
		String sign = pp.getSign();
		@SuppressWarnings("unchecked")
		Map<String,Object> map = JSON.parseObject(sign, Map.class);
		String hash = (String) map.get("sid");
		pp.setUserId(pp.getUserId());//操作人（管理员）
		pp.setOperationTypeId(OperationType.MODIFY_SUPPLIER);//操作类型 (编辑配置后在添加)
		pp.setUserIdb(Integer.parseInt(pp.getPlannerId()));//这里是被操作人账号 
		pp.setOperationTime(currentTime);//操作时间
		pp.setHash(hash);//操作hash
		userMapper.insertOperationHistory(pp);//插入到操作记录表去
	/*	ProtobufBean protobufBean = blockChainUtil.getProtobufBean(pp.getSign());
		String result = blockChainUtil.sendPostParam(protobufBean);
		boolean flag = blockChainUtil.vilaResult(result);*/
		boolean flag = blockChainUtil.sendBlockChain(pp.getSign());//发送签名直接转发到区块链
		if(!flag) {
			 throw new RuntimeException("区块链操作失败:");
		}

	}

	
	
}
