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.Statuses;
import com.fuzamei.entity.IssueOrder;
import com.fuzamei.entity.Orders;
import com.fuzamei.entity.Params;
import com.fuzamei.entity.SendOrder;
import com.fuzamei.mapperInterface.CargoConsignMapper;
import com.fuzamei.mapperInterface.OperationHistoryMapper;
import com.fuzamei.service.CargoConsignService;
import com.fuzamei.util.PageDTO;
import com.fuzamei.util.blockchain.BlockChainUtil;

@Service
public class CargoConsignServiceImpl implements CargoConsignService {

	@Autowired
	private CargoConsignMapper cargoConsignMapper;
	
	@Autowired
	private OperationHistoryMapper operationHistoryMapper;
	
	@Autowired
	private BlockChainUtil blockChainUtil;

	@Override
	public PageDTO queryOrdersBySupplier(Params params) {
		PageDTO pageDto=new PageDTO();
		List<SendOrder> orderList = cargoConsignMapper.queryOrdersBySupplier(params);
		int count = cargoConsignMapper.findQueryCountBySupplier(params);
		pageDto.setRows(orderList);
		pageDto.setTotal(count);
		return pageDto;
	}

	@Override
	public PageDTO queryOrdersByCarrier(Params params) {
		PageDTO pageDto=new PageDTO();
		List<SendOrder> orderList = cargoConsignMapper.queryOrdersByCarrier(params);
		int count = cargoConsignMapper.findQueryCountByCarrier(params);
		pageDto.setRows(orderList);
		pageDto.setTotal(count);
		return pageDto;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void doCarry(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 = System.currentTimeMillis();
		//更新【订单表】
		params.setTransportTime(currentTime);
		params.setUpdateTime(currentTime);
		params.setStatusId(Statuses.DELIVERING);
		params.setCarNo(params.getCarNo());
		cargoConsignMapper.doCarry(params);
		//插入【操作记录】
		params.setOperationTypeId(OperationType.DELIVER);
		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);
	}
	
	
}
