package com.goafanti.order.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
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 com.goafanti.business.bo.JtBusinessProjectResult;
import com.goafanti.common.dao.AchievementMapper;
import com.goafanti.common.dao.DemandMapper;
import com.goafanti.common.dao.JtBusinessProjectMapper;
import com.goafanti.common.dao.JtOrderDetailMapper;
import com.goafanti.common.dao.JtOrderMapper;
import com.goafanti.common.model.Achievement;
import com.goafanti.common.model.Demand;
import com.goafanti.common.model.JtBusinessProject;
import com.goafanti.common.model.JtOrder;
import com.goafanti.common.model.JtOrderDetail;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.JDBCIdGenerator;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.order.bo.JtOrderInput.JtSingleOrder;
import com.goafanti.order.bo.JtOrderResultDetail;
import com.goafanti.order.service.JtOrderService;

@Service
public class JtOrderServiceImpl extends BaseMybatisDao<JtOrderMapper> implements JtOrderService{
	@Autowired
	JtOrderMapper jtOrderMapper;
	@Autowired
	JtOrderDetailMapper jtOrderDetailMapper;
	@Autowired
	JtBusinessProjectMapper JtBusinessProjectMapper;
	@Autowired
	AchievementMapper achievementMapper;
	@Autowired
	DemandMapper demandMapper;
	@Override
	public int addOrder(List<JtSingleOrder> orderList) {
		List<JtOrder>jtOrders=new ArrayList<>();
		List<JtOrderDetail>jtOrderDetails=new ArrayList<>();
		for(JtSingleOrder order:orderList)
		{
			JtOrder jtOrder=new JtOrder();
			JtOrderDetail jtOrderDetail=new JtOrderDetail();
			if(order.getCommodityId()==null)return -1;
			if(order.getCommodityType()==null || order.getCommodityType()<0 || order.getCommodityType()>=4)return -2;
			if(order.getOrderChannel()==null)return -3;
			if(order.getPayType()==null)order.setPayType(0);
			switch(order.getCommodityType()) {
			case 0:{
				JtBusinessProjectResult jtBusinessProject=JtBusinessProjectMapper.selectByPrimaryKeyWithModule(order.getCommodityId(),null);
				if(jtBusinessProject==null)return -1;
				else {
					jtOrder.setSellerId(jtBusinessProject.getOwnerId());
					jtOrderDetail.setCommodityName(jtBusinessProject.getName());
					if(jtBusinessProject.getPrice()==null) {
						jtOrder.setOrderAmount(new BigDecimal(0));
						}
					else jtOrder.setOrderAmount(jtBusinessProject.getPrice().multiply(new BigDecimal(order.getCommodityQuantity())));
					jtOrderDetail.setCommodityPrice(jtBusinessProject.getPrice()==null?new BigDecimal(0):jtBusinessProject.getPrice());
				}
				break;}
			case 1:{
				JtBusinessProjectResult jtBusinessProject=JtBusinessProjectMapper.selectByPrimaryKeyWithModule(order.getCommodityId(),null);
				if(jtBusinessProject==null || jtBusinessProject.getModule()!=1)return -1;
				else {
					jtOrder.setSellerId(jtBusinessProject.getOwnerId());
					jtOrderDetail.setCommodityName(jtBusinessProject.getName());
					if(jtBusinessProject.getPrice()==null) {
						jtOrder.setOrderAmount(new BigDecimal(0));
						}
					else jtOrder.setOrderAmount(jtBusinessProject.getPrice().multiply(new BigDecimal(order.getCommodityQuantity())));
					jtOrderDetail.setCommodityPrice(jtBusinessProject.getPrice()==null?new BigDecimal(0):jtBusinessProject.getPrice());
				}
				break;}
			case 2:{
				Achievement achievement=achievementMapper.selectByPrimaryKey(order.getCommodityId());
				if(achievement ==null )return -1;
				else {
					jtOrder.setSellerId(achievement.getOwnerId());
					jtOrderDetail.setCommodityName(achievement.getName());
					if(achievement.getTransferPrice()==null)jtOrder.setOrderAmount(new BigDecimal(0));
					else jtOrder.setOrderAmount(achievement.getTransferPrice().multiply(new BigDecimal(order.getCommodityQuantity())));
					jtOrderDetail.setCommodityPrice(achievement.getTransferPrice()==null?new BigDecimal(0):achievement.getTransferPrice());
				}
				break;}
			case 3:{
				Demand demand=demandMapper.selectByPrimaryKey(order.getCommodityId());
				if(demand==null )return -1;
				else {
					BigDecimal price=new BigDecimal(0);
					jtOrder.setSellerId(demand.getEmployerId());
					jtOrderDetail.setCommodityName(demand.getName());
					if(demand.getDemandType()==3) {price=demand.getCrowdCost()==null?new BigDecimal(0):demand.getCostEscrow().multiply(new BigDecimal(-1));}
					else price=demand.getBudgetCost();
					if(price==null)jtOrder.setOrderAmount(new BigDecimal(0));
					else jtOrder.setOrderAmount(price.multiply(new BigDecimal(order.getCommodityQuantity())));
					jtOrderDetail.setCommodityPrice(price==null?new BigDecimal(0):price);
				}
				break;}
			default:break;
			}
			JDBCIdGenerator jdbcIdGenerator=new JDBCIdGenerator();
			String orderNo=jdbcIdGenerator.generateId()+"";
			jtOrder.setBuyerId(TokenManager.getUserId());
//			jtOrder.setBuyerId("0549c290-5178-4886-8294-5037f1743b0c");
			order.setOrderNo(orderNo);
			jtOrder.setDeleteSign(0);
			jtOrder.setOrderChannel(order.getOrderChannel());
			jtOrder.setOrderNo(orderNo);
			jtOrder.setOrderRemarks(order.getOrderRemarks());
			jtOrder.setOrderStatus(0);
			jtOrder.setOrderTime(new Date());
			jtOrder.setPayType(order.getPayType());
			jtOrder.setRefundAmount(new BigDecimal(0));
			jtOrder.setPayAmount(new BigDecimal(0));
			jtOrder.setUpdateTime(new Date());
	
			
			jtOrderDetail.setCommodityId(order.getCommodityId());
			jtOrderDetail.setCommodityMode(order.getCommodityMode());
			jtOrderDetail.setCommodityQuantity(order.getCommodityQuantity());
			jtOrderDetail.setCommodityType(order.getCommodityType());
			jtOrderDetail.setCreateTime(new Date());
			jtOrderDetail.setDiscountPrice(new BigDecimal(0));
			jtOrderDetail.setId(UUID.randomUUID().toString());
			jtOrderDetail.setMemberPrice(new BigDecimal(0));
			jtOrderDetail.setOrderNo(orderNo);
	
			jtOrders.add(jtOrder);
			jtOrderDetails.add(jtOrderDetail);
		}
		for(int i =0;i<jtOrders.size();i++) {
			jtOrderMapper.insert(jtOrders.get(i));
			jtOrderDetailMapper.insert(jtOrderDetails.get(i));
		}
		return 0;
	}
	
	
	/*
	 * userType-----0-购买者   1-出售者  2-管理员
	 * 
	 * */
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<JtOrderResultDetail> searchOrderList(Integer orderType ,String orderNo, String startCreateDate, String endCreateDate,
			String sellerName, String buyerName, String commodityName, Integer userType,Integer pageNo,Integer pageSize) {
		Map<String, Object>params=new HashMap<>();
		if(pageNo==null ||pageNo<1)pageNo=1;
		if(pageSize==null || pageSize<1)pageSize=10;
		String sellerId=null;
		String buyerId=null;
		if(userType==0) {
			//购买者 将买家姓名置空，购买id为当前id进行搜索
			buyerName=null;
			buyerId=TokenManager.getUserId();
			params.put("buyerId", buyerId);
		}
		else if(userType==1) {
			//出售者  将卖家姓名置空，出售者id为当前id进行搜索
			sellerName=null;
			sellerId=TokenManager.getUserId();
			params.put("sellerId", sellerId);
		}
		else {
			//管理员  买卖id均为空，不额外处理买卖房姓名
		}
		if(buyerName!=null)params.put("buyerName", buyerName);
		if(sellerName!=null)params.put("sellerName", sellerName);
		if(orderNo!=null)params.put("orderNo", orderNo);
		if(startCreateDate!=null)params.put("startCreateDate", startCreateDate);
		if(endCreateDate!=null)params.put("endCreateDate", endCreateDate);
		if(commodityName!=null)params.put("commodityName", commodityName);
		if(orderType!=null  && ((orderType>=0 && orderType<=6)|| orderType==10))params.put("orderType", orderType);
			return (Pagination<JtOrderResultDetail>) findPage("searchJtOrderList", "searchJtOrderListCount", params, pageNo, pageSize);
	}
	
	
	
	/*
	 * userType-----0-购买者   1-出售者  2-管理员
	 * 
	 * */
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<JtOrderResultDetail> appSearchOrderList(Integer orderType,Integer userType,Integer pageNo,Integer pageSize){
		Map<String, Object>params=new HashMap<>();
		if(pageNo==null ||pageNo<1)pageNo=1;
		if(pageSize==null || pageSize<1)pageSize=10;
		
		if(userType==0) {
			//购买者 将买家姓名置空，购买id为当前id进行搜索
			params.put("buyerId", TokenManager.getUserId());
//			params.put("buyerId", "1");
		}
		else if(userType==1) {
			//出售者  将卖家姓名置空，出售者id为当前id进行搜索
			params.put("sellerId", TokenManager.getUserId());
		}
		if(orderType!=null && ((orderType>=0 && orderType<=6)|| orderType==10))params.put("orderType", orderType);
		Pagination<JtOrderResultDetail>p = (Pagination<JtOrderResultDetail>) findPage("appSearchJtOrderList", "appSearchJtOrderListCount", params, pageNo, pageSize);
		List<JtOrderResultDetail> l=(List<JtOrderResultDetail>) p.getList();
				for (JtOrderResultDetail j : l) {
					if (null!=j.getCommodityType()) {
						if (j.getCommodityType()==1||j.getCommodityType()==0) {
							JtBusinessProject bp=JtBusinessProjectMapper.selectByPrimaryKey(j.getCommodityId());
							if (null!=bp) {
								j.setImgUrl(bp.getMinImgUrl());
							}
						}else if (j.getCommodityType()==2) {
							Achievement a=achievementMapper.selectByPrimaryKey(j.getCommodityId());
							if (null!=a) {
							j.setImgUrl(a.getTechnicalPictureUrl());
							}
						}else if (j.getCommodityType()==3) {
							Demand d=demandMapper.selectByPrimaryKey(j.getCommodityId());
							if (null!=d) {
							j.setImgUrl(d.getPictureUrl());
							}
						}
					}
				}
		return p;
	}



	

}
