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 com.alibaba.fastjson.JSON;
import com.fuzamei.constant.OperationType;
import com.fuzamei.constant.Statuses;
import com.fuzamei.entity.Orders;
import com.fuzamei.entity.Params;
import com.fuzamei.entity.SendOrder;
import com.fuzamei.entity.TallyOrder;
import com.fuzamei.mapperInterface.CargoTallyMapper;
import com.fuzamei.mapperInterface.OperationHistoryMapper;
import com.fuzamei.service.CargoTallyService;
import com.fuzamei.util.PageDTO;
import com.fuzamei.util.blockchain.BlockChainUtil;

@Service
public class CargoTallyServiceImpl implements CargoTallyService {

	@Autowired
	private CargoTallyMapper cargoTallyMapper;
	
	@Autowired
	private OperationHistoryMapper operationHistoryMapper;
	
	@Autowired
	private BlockChainUtil blockChainUtil;

	@Override
	public PageDTO queryOrdersByReceiver(Params params) {
		PageDTO pageDto=new PageDTO();
		List<TallyOrder> orderList = cargoTallyMapper.queryOrdersByReceiver(params);
		int count = cargoTallyMapper.findQueryCountByReceiver(params);
		pageDto.setRows(orderList);
		pageDto.setTotal(count);
		return pageDto;
	}

	@Override
	public TallyOrder searchNewOrderByOrderId(Params params) {
		Orders order = params.getOrder();
		TallyOrder tallyOrder=new TallyOrder();
		tallyOrder.setOrderId(order.getOrderId());
		tallyOrder.setPartNo(order.getPartNo());
		tallyOrder.setBoxNo(order.getBoxNo());
		tallyOrder.setBoxQty(order.getBoxQty());
		tallyOrder.setCarNo(order.getCarNo());
		return tallyOrder;
	}

	@Override
	public void confirmOrReject(Params params) {
		String sign = params.getSign();
		@SuppressWarnings("unchecked")
		Map<String,Object> map = JSON.parseObject(sign, Map.class);
		String hash = (String) map.get("sid");
		Long currentTime = params.getTallyTime();
		//更新【订单表】
		params.setTallyTime(currentTime);
		params.setUpdateTime(currentTime);
		params.setReceiverId(params.getUserId());
		if(params.getConfirmId()==1)	params.setStatusId(Statuses.TALLIED);
		if(params.getConfirmId()==0)	params.setStatusId(Statuses.REJECTED);
		cargoTallyMapper.confirmOrReject(params);
		//插入【操作记录】
		if(params.getConfirmId()==1) params.setOperationTypeId(OperationType.CONFIRM);
		if(params.getConfirmId()==0) params.setOperationTypeId(OperationType.CONFIRM);
		params.setOperatorId(params.getUserId());
		params.setOperationTime(currentTime);
		params.setHash(hash);
		operationHistoryMapper.addToHistory(params);
		boolean flag = blockChainUtil.sendBlockChain(params.getSign());
		if(!flag) throw new RuntimeException("区块链操作失败");
	}

	@Override
	public List<Object> orderTracking(Params params) {
		Orders order = params.getOrder();
		return OrdersIssueServiceImpl.dispatchOrderInfo(order);
	}
}
