package com.iamberry.rent.service.order;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.iamberry.rent.face.pay.RentPayService;
import com.iamberry.rent.service.order.mapper.RentExchangeMapper;
import com.iamberry.rent.service.rebate.mapper.OrderRebateMapper;
import com.iamberry.wechat.core.entity.rent.*;
import com.iamberry.wechat.tools.ResponseJson;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.rent.face.order.RentOrderService;
import com.iamberry.rent.service.order.mapper.RentOrderMapper;
import com.iamberry.rent.service.order.mapper.ServiceCouponMapper;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.HttpClient431Util;
import com.iamberry.wechat.tools.NameUtils;
/**
 * 租赁订单业务实现
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2017年3月10日
 */
@Service
public class RentOrderServiceImpl implements RentOrderService{
	@Autowired
	private RentOrderMapper rentOrderMapper;
	@Autowired
	private ServiceCouponMapper serviceCouponMapper;
	@Autowired
	private RentExchangeMapper rentExchangeMapper;
	@Autowired
    private RatFWLogger logger;
	@Autowired
	private RentPayService rentPayService;
	@Autowired
	private OrderRebateMapper orderRebateMapper;
	@Autowired
	private RentOrderService rentOrderService;

	@Override
	public List<RentOrderItem> listInitCode(String openId) {
		// TODO Auto-generated method stub
		return rentOrderMapper.listInitCode(openId);
	}

    @Override
    public Map<String, Object> listRentOrder(RentOrderDTO rentOrderDTO) {
        // TODO Auto-generated method stub
        rentOrderDTO.getPage().initRecordBegin();
        List<RentOrderDTO> dtoList = rentOrderMapper.listRentOrder(rentOrderDTO);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list", dtoList);
        map.put("countOrder", rentOrderMapper.countRentOrder(rentOrderDTO));
        return map;
    }

	@Override
	public int countRentOrder(RentOrderDTO rentOrderDto) {
		// TODO Auto-generated method stub
		return rentOrderMapper.countRentOrder(rentOrderDto);
	}

	@Override
	public Integer insertRentOrderInfo(RentOrder rentOrder) {
		// TODO Auto-generated method stub
		return rentOrderMapper.insertRentOrderInfo(rentOrder);
	}

	@Override
	public Integer insertRentOrderItemList(List<RentOrderItem> list) {
		// TODO Auto-generated method stub
		return rentOrderMapper.insertRentOrderItemList(list);
	}

	@Override
	public RentOrderItem getOrderItemByInitCode(RentOrderItem rentOrderItem) {
		// TODO Auto-generated method stub
		return rentOrderMapper.getOrderItemByInitCode(rentOrderItem);
	}

	@Override
	public Integer insertRentOrderAndItem(RentOrder rentOrder,
			List<RentOrderItem> list, ServiceCouponInfo couponInfo) {
		// TODO Auto-generated method stub
		int num = rentOrderMapper.insertRentOrderInfo(rentOrder);
		int sum = rentOrderMapper.insertRentOrderItemList(list);
		if (couponInfo == null) {
			if (num > 0 && sum > 0) {
				return 1;
			} else {
				return 0;
			}
		} else {
			int flag = serviceCouponMapper.update(couponInfo);
			if (num > 0 && sum > 0 && flag > 0) {
				return 1;
			} else {
				return 0;
			}
		}
		
	}

	@Override
	public RentOrder getRentOrderByOrderId(RentOrder rentOrder) {
		// TODO Auto-generated method stub
		return rentOrderMapper.getRentOrderByOrderId(rentOrder);
	}

	@Override
	public List<RentOrderItem> listOrderItem(RentOrderItem rentOrderItem) {
		// TODO Auto-generated method stub
		return rentOrderMapper.listOrderItem(rentOrderItem);
	}

	@Override
    public boolean updateRentOrder(RentOrder rentOrder) {
        // TODO Auto-generated method stub
	    if(rentOrderMapper.updateRentOrder(rentOrder) > 0){
	        return true;
	    }else{
	        return false;
	    }
    }
	
	@Override
	public boolean updateOrderAndOrderItem(RentOrder rentOrder,
			RentOrderItem rentOrderItem, ServiceCouponInfo serviceCouponInfo) {
		// TODO Auto-generated method stub
		int num = rentOrderMapper.updateRentOrder(rentOrder);
		int sum = rentOrderMapper.updateOrderItem(rentOrderItem);
		if (serviceCouponInfo == null) {
			if (num > 0 && sum > 0) {
				return true;
			} else {
				return false;
			}
		} else {
			int flag = serviceCouponMapper.update(serviceCouponInfo);
			if (num > 0 && sum > 0 && flag > 0) {
				return true;
			} else {
				return false;
			}
		}
	}


	@Override
public List<RentOrderItem> getRentOrderByOpenId(String rentOpenid) {
	// TODO Auto-generated method stub
	return rentOrderMapper.getRentOrderByOpenId(rentOpenid);
}



@Override
public boolean addRentOrderToEfast(String rentOrderId,  String rentOpenId) throws Exception {
	// TODO Auto-generated method stub
	RentOrderDTO rentOrder = new RentOrderDTO();
	rentOrder.setRentOrderId(rentOrderId);
	//根据orderId查询订单信息，只会有一条
	List<RentOrderDTO> rentOrderList = rentOrderMapper.listRentOrder(rentOrder);
	rentOrder = rentOrderList.get(0);
	if (rentOrderList == null || rentOrderList.size() == 0) {
		return false;
	}
	if (rentOrder.getOrderItemList() == null || rentOrder.getOrderItemList().size() == 0) {
		return false;
	}
	// request url
	String url = NameUtils.getConfig("efast_base_url");
	// set Requeset Data
	Map<String, String> requestData = new HashMap<String, String>();
	/**
	 * 系统级参数
	 */
	requestData.put("app_nick", NameUtils.getConfig("app_nick"));
	requestData.put("app_key", NameUtils.getConfig("app_key"));
	requestData.put("app_secret", NameUtils.getConfig("app_secret"));
	requestData.put("timestamp",DateTimeUtil.format(new Date(),"yyyyMMddHHmmss"));
	requestData.put("app_act", "efast.trade.new.add"); // "efast.trade.new.add"
	
	/**
	 * 订单基本信息
	 */
	String [] addressDesc = rentOrder.getRentAddressInfo().split("-");
	
	String address = addressDesc[3];
    if (addressDesc[3]!=null) {
        Pattern p = Pattern.compile("\\s*|\t|\r|\n");
        Matcher m = p.matcher(addressDesc[3]);
        if (m.find()) {
        	address = m.replaceAll("");
		}
    }
	
	String provinceName = addressDesc[0];
	if (addressDesc[0].indexOf("北京") != -1) {
		provinceName = "北京";
	} else if (addressDesc[0].indexOf("上海") != -1) {
		provinceName = "上海";
	} else if (addressDesc[0].indexOf("天津") != -1) {
		provinceName = "天津";
	} else if (addressDesc[0].indexOf("重庆") != -1) {
		provinceName = "重庆";
	}
	Map<String, Object> orderData = new HashMap<String, Object>();
	orderData.put("add_time", DateTimeUtil.format(rentOrder.getRentCreateDate()));	// 时间
	orderData.put("address", address);// 收货地址
	orderData.put("city_name", addressDesc[1]); // 城市
	orderData.put("consignee", rentOrder.getRentAddressName());// 收货人
	orderData.put("district_name", addressDesc[2]);// 区域
	orderData.put("email", "");// email
	orderData.put("goods_amount", (rentOrder.getRentAmount()/100.0));	// 商品总价
	orderData.put("goods_count", 1);	// 产品数量
	orderData.put("mobile", rentOrder.getRentAddressTel());// 手机号码
	orderData.put("money_paid", rentOrder.getRentPayMoney()/100.0);// 已付款
	orderData.put("oid", rentOrder.getRentOrderId());	// 订单号
	orderData.put("order_amount", rentOrder.getRentPayMoney()/100.0);	// 应付款,应付款金额要与已付款金额相同
	
	/**
	 * 产品信息
	 */
	List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
	Map<String, Object> orders1 = new HashMap<String, Object>();
	for (RentOrderItemDTO item : rentOrder.getOrderItemList()) {
		orders1.put("goods_name", item.getItemProductName());	// 产品名称
		orders1.put("goods_number", 1);// 产品数量
		orders1.put("goods_price", (item.getColorDiscount()/100.0));// 产品原价
		orders1.put("outer_sku", item.getColor69Code());// 产品SKU
		orders1.put("payment_ft", rentOrder.getRentPayMoney()/100.0);// 产品分摊价
	}
	maps.add(orders1);
	orderData.put("orders", maps);// 订单产品
	orderData.put("pay_name", "weixinpay");// 支付方式
	orderData.put("pay_time", DateTimeUtil.format(rentOrder.getRentTransactionDate()));// 支付时间
	orderData.put("postscript", "");// 买家留言
	orderData.put("province_name", provinceName);// 省份
	orderData.put("sd_id", NameUtils.getConfig("sd_idt"));// 对应 efast 店铺 id
	orderData.put("shipping_fee", 0);// 快递费
	orderData.put("shipping_name", "02");// 快递公司代码
	orderData.put("tel", "");	// 我司电话
	orderData.put("to_buyer", "租用订单");// 商家备注
	orderData.put("total_amount", (rentOrder.getRentAmount()/100.0));// 订单总额
	orderData.put("user_name", rentOpenId);// 买家账户   百胜根据user_name来判断是否有重复，传openId是为了防止重复
	orderData.put("zipcode", "");						// 邮编
	
	com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
	String orderDataStr = null;;
	try {
		orderDataStr = mapper.writeValueAsString(orderData);
	} catch (JsonProcessingException e2) {
		e2.printStackTrace();
	}
	
	requestData.put("info", orderDataStr);
	
	try {
		String result = HttpClient431Util.doGet(requestData, url);
		result = StringEscapeUtils.unescapeJava(result); // unicode 编码
		logger.info("add-推送订单号为:" + rentOrder.getRentOrderId() + "的订单，百胜返回信息:" + result);
		// parse JSON String to Object
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONObject respData = JSONObject.fromObject(jsonObject.get("resp_data"));
		String oderSn = respData.getString("oder_sn");
		if (oderSn != null) {
			String msg = respData.getString("msg");
			if ("success".equals(msg)) {
				return true;
			}
		}
		logger.error(this, "add-推送订单号为:" + rentOrder.getRentOrderId() + "的订单，百胜返回信息:" + result);
		throw new Exception(respData.getString("msg"));
	} catch (Exception e) {
		throw e;
	}
}
	@Override
    public boolean deliverOrderByOrderId(RentOrder rentOrder) {
        // TODO Auto-generated method stub
		RentOrderItem rentOrderItem = new RentOrderItem();
		rentOrderItem.setItemOrderId(rentOrder.getRentOrderId());
		rentOrderItem.setItemStatus(rentOrder.getRentStatus());
        if(rentOrderMapper.updateRentOrderByOrderId(rentOrder) > 0
				&& rentOrderMapper.updateOrderItem(rentOrderItem) > 0){
            return true;
        }else{
            return false;
        }
    }

	@Override
	public List<RentOrder> listOrderByDeadline(RentOrder rentOrder) {
		// TODO Auto-generated method stub
		return rentOrderMapper.listOrderByDeadline(rentOrder);
	}

	@Override
	public boolean updateOrderAndCoupon(List<String> orderList,
			List<Integer> couponList) {
		// TODO Auto-generated method stub
		int orderNum = 0;	//修改订单数量
		int itemNum = 0;		//修改订单项数量
		int couponNum = 0;//修改服务费抵扣券数量
		
		if (orderList == null || orderList.size() == 0) {
			return false;
		}
		//批量修改订单状态
		orderNum = rentOrderMapper.updateOrderList(orderList);
		//批量修改订单项状态
		itemNum = rentOrderMapper.updateOrderItemList(orderList);
		if (couponList != null && couponList.size() > 0) {
			//批量修改服务费抵扣券状态
			couponNum = serviceCouponMapper.updateServiceCouponList(couponList);
		}
		if (couponList != null && couponList.size() > 0) {
			if (orderNum > 0 && itemNum > 0 && couponNum > 0) {
				return true;
			}
		} else {
			if (orderNum > 0 && itemNum > 0) {
				return true;
			}
		}
		
		return false;
	}

	@Override
	public boolean updateOrderStatusAndItemStatus(RentOrder rentOrder) {
		if(rentOrder == null || StringUtils.isEmpty(rentOrder.getRentOrderId()))
			return false;
		int i = rentOrderMapper.updateRentOrder(rentOrder);
		int j = 0;
		if (rentOrder.getList() != null && rentOrder.getList().size() > 0){
			j = rentOrderMapper.updateOrderItem(rentOrder.getList().get(0));
		}
		if(i < 1 || j < 1){
			return false;
		}
		return true;
	}

	@Override
	public boolean updateReturnRentOrder(RentOrder rentOrder) {

		int money = 0;

		if (rentOrder == null || rentOrder.getList() == null || rentOrder.getList().size() <= 0) {
			return false;
		}
		//判断该订单的机器是否已经被激活,状态为2表示已激活
		if (rentOrder.getList().get(0).getItemCodeState().intValue() == 2) {
			//当租赁类型为1年时，退货只退押金
			if (rentOrder.getRentTypeId().intValue() == 1) {
				for (RentOrderItem item : rentOrder.getList()) {
					//判断租赁物品是否还有押金，如果有，则退货时需要退还押金
					if (item.getItemProductType().intValue() != 5 && item.getRentRemainDeposit() > 0) {
						money = item.getRentRemainDeposit();
					}
				}
			} else {
				long sendDateTime = rentOrder.getRentSendDate().getTime();
				long newDateTime = new Date().getTime();
				//计算使用了多长时间（单位：年，不满一年按一年算）
				int year = (int)Math.ceil((double)(newDateTime - sendDateTime)/1000/24/60/60/365);
				RentTypeInfo typeInfo = new RentTypeInfo();
				typeInfo.setTypeId(rentOrder.getRentTypeId());
				typeInfo.setTypeStatus(1);
				//根据租赁类型id查询租赁的金额和时限
				typeInfo = orderRebateMapper.getRebateType(typeInfo);
				//租用总时长
				int sumYear = typeInfo.getTypePayDuration().intValue()/12;
				//计算每年的平均租赁金额
				int aveMoney = (int)Math.floor(rentOrder.getRentPayMoney().doubleValue()/sumYear/100);
				if (sumYear - year > 0) {
					money = (sumYear - year) * aveMoney;
				}
			}
		} else {
			//如果订单的机器没有被激活，则退货时全额退款；如果使用了优惠券，则需重置优惠券
			//计算已经提取的押金金额
			int deposit = rentOrder.getList().get(0).getRentDeposit() - rentOrder.getList().get(0).getRentRemainDeposit();
			money = rentOrder.getRentPayMoney().intValue() - deposit;
			rentOrderService.updateServiceAndPledge(rentOrder.getRentServiceId(),
					Integer.getInteger(rentOrder.getList().get(0).getRentPledgeId()));
		}



		int returnCode = 500;

		//微信转账
		try {
			ResponseJson json = rentPayService.payTransfer(rentOrder.getRentOpenid(),rentOrder.getRentOrderId(),
					money,3,"订单退货");
			returnCode = json.getReturnCode().intValue();
			if (returnCode == 200) {
				logger.info("订单号为:" + rentOrder.getRentOrderId() + "的退货订单微信转账成功");
			} else {
				logger.info("订单号为:" + rentOrder.getRentOrderId() + "的退货订单微信转账失败");
			}

		} catch (Exception e) {
			logger.info("订单号为:" + rentOrder.getRentOrderId() + "的退货订单微信转账失败");
			e.printStackTrace();
		}

		if(rentOrder == null || StringUtils.isEmpty(rentOrder.getRentOrderId()))
			return false;
		int i = rentOrderMapper.updateRentOrder(rentOrder);
		int j = 0;
		if (rentOrder.getList() != null && rentOrder.getList().size() > 0){
			j = rentOrderMapper.updateOrderItem(rentOrder.getList().get(0));
		}
		if(i < 1 || j < 1 || returnCode != 200){
			return false;
		}
		return true;
	}

	@Override
	public boolean updateServiceAndPledge(Integer serviceId, Integer pledgeId) {
		int serviceNum = 0;
		int pledgeNum = 0;
		//如果服务费抵扣券不为空，则修改服务费抵扣券状态
		if (serviceId != null) {
			ServiceCouponInfo couponInfo = new ServiceCouponInfo();
			couponInfo.setServiceId(serviceId);
			couponInfo.setServiceStatus(1);
			couponInfo.setServiceOldStatus(3);
			serviceNum = serviceCouponMapper.update(couponInfo);
		} else {
			serviceNum = 1;
		}
		//如果押金提取券不为空，则修改押金提取券状态
		if (pledgeId != null) {
			PledgeCouponInfo pledgeCouponInfo = new PledgeCouponInfo();
			pledgeCouponInfo.setPledgeId(pledgeId);
			pledgeCouponInfo.setPledgeStatus(1);
			pledgeNum = serviceCouponMapper.updatePledgeCouponStatus(pledgeCouponInfo);
		} else {
			pledgeNum = 1;
		}
		if (serviceNum > 0 && pledgeNum > 0) {
			return true;
		} else {
			return false;
		}
	}

    @Override
	public boolean rentExitOrder(RentOrder rentOrder){
        boolean flag = rentOrderService.updateOrderStatusAndItemStatus(rentOrder);
        if (flag){
            if (StringUtils.isEmpty(rentOrder.getRentPostNum())){
                return false;
            }
            Integer i = rentOrderMapper.updateRentOrderByOrderId(rentOrder);
            if(i > 0){
                return true;
            }
        }
        return false;
    }

	@Override
	public boolean rentExchangeOrder(RentOrder rentOrder, RentExchangeInfo exchangeInfo) {
		boolean flag = rentOrderService.updateOrderStatusAndItemStatus(rentOrder);
		if (flag){
			if (StringUtils.isEmpty(exchangeInfo.getExchangeAddressName())
					|| StringUtils.isEmpty(exchangeInfo.getExchangeAddressInfo())
					|| StringUtils.isEmpty(exchangeInfo.getExchangeAddressTel())
					|| StringUtils.isEmpty(exchangeInfo.getExchangePostNum())){
				return false;
			}
			exchangeInfo.setExchangeItemId(rentOrder.getList().get(0).getItemId());
			exchangeInfo.setExchangeStatus(1);
			List<RentExchangeInfo> list = rentExchangeMapper.getExchangeInfoByItemId(exchangeInfo);
			if(list != null && list.size() > 0) return true;
			int i = rentExchangeMapper.insertRentExchange(exchangeInfo);
			if(i > 0){
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean opertionRentExchangeOrder(RentOrder order) {
		RentOrderItem item = order.getList().get(0);
		RentExchangeInfo exInfo = new RentExchangeInfo();
		exInfo.setExchangeItemId(item.getItemId());
		exInfo.setExchangeStatus(1);
		List<RentExchangeInfo> list = rentExchangeMapper.getExchangeInfoByItemId(exInfo);
		if(list == null || list.size() != 1) return false;
		RentExchangeInfo exchangeInfo = list.get(0);
		//修改租赁订单和订单项状态
		if (!rentOrderService.updateOrderStatusAndItemStatus(order)) return false;

		//修改换货记录状态
		if(order.getRentStatus() == 9){
			exchangeInfo.setExchangeStatus(2);
		}else{
			exchangeInfo.setExchangeStatus(0);
		}
		exchangeInfo.setExchangeCheckDate(new Date());
		Integer i = rentExchangeMapper.updateExchangeById(exchangeInfo);
		if (i < 1)	return false;
		return true;
	}

	@Override
	public List<RentOrderItem> selectRentOrderByOpenId(String rentOpenid) {
		return rentOrderMapper.selectRentOrderByOpenId(rentOpenid);
	}

	@Override
	public Integer addTransferRecord(AccountLogsInfo accountLogsInfo) {
		return rentOrderMapper.addTransferRecord(accountLogsInfo);
	}

	@Override
	public Integer update(RentOrderItem rentOrderItem) {
		return rentOrderMapper.update(rentOrderItem);
	}

	@Override
	public boolean rentReturnMoneyRentOrder(RentOrder rentOrder) {
		boolean flag = updateOrderStatusAndItemStatus(rentOrder);
		if(!flag){
		    return false;
        }
		if(rentOrder.getRentStatus() == 4){
			//微信转账
            ResponseJson json = rentPayService.payTransfer(rentOrder.getRentOpenid(),rentOrder.getRentOrderId(),
                    rentOrder.getRentPayMoney(),4,"订单退款");
            if (json.getReturnCode().intValue() == 200) {
                logger.info("订单号:" + rentOrder.getRentOrderId() + ",退款，微信转账成功!");
                boolean flag1 = updateServiceAndPledge(rentOrder.getRentServiceId(),
                        Integer.getInteger(rentOrder.getList().get(0).getRentPledgeId()));
                return true;
            } else {
                logger.info("订单号:" + rentOrder.getRentOrderId() + ",退款，微信转账失败!");
                throw new IllegalArgumentException("微信转账失败!");
            }
		}
		return true;
	}
}
