package com.iamberry.rent.service.efast;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.rent.face.efast.EfastRentService;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.face.porduct.ProductColorService;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.HttpClient431Util;
import com.iamberry.wechat.tools.NameUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/4/21.
 */
@Service
public class EfastRentServiceImpl implements EfastRentService {

    @Autowired
    private RatFWLogger logger;
    @Autowired
    private ProductColorService productColorService;

    @Override
    public Map<String,Object> getEfastSendOrderInfo(String oid) {
        // TODO Auto-generated method stub

        // 组装数据
        Map<String, String> requestData = new HashMap<String, String>();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("status", false);
        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.detail.get");
        requestData.put("oid", oid);
        requestData.put("feilds", NameUtils.getConfig("order_field"));
        try {
            String resultJson = HttpClient431Util.doPost(requestData, NameUtils.getConfig("efast_base_url"));
            logger.info("订单号为:" + oid + "的订单，百胜返回信息:" + resultJson);
            resultJson = StringEscapeUtils.unescapeJava(resultJson); // unicode
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(resultJson);
            if (m.find()) {
                resultJson = m.replaceAll("");
            }
            logger.info("get-订单号为:" + oid + "的订单，百胜返回信息:" + resultJson);
            JSONObject jsonObject = JSONObject.fromObject(resultJson);

            // default HTTP SUCCESS
            JSONObject respData = JSONObject.fromObject(jsonObject.get("resp_data"));
            // 发货状态 : shipping_status
            String shippingStatus = respData.getString("shipping_status");
            if ("1".equals(shippingStatus)) {
                map.put("postFirm", respData.getString("shipping_name"));
                map.put("postNum", respData.getString("invoice_no"));
                map.put("status", true);
            }
            logger.error(this, "get-订单号为:" + oid + "的订单，百胜返回信息:" + resultJson);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error(this, "get-订单号为:" + oid + "的订单，发生错误:" + e.getMessage());
        }
        return map;
    }

    @Override
    public boolean sendRentFilter(String address, String id, Integer colorId, String addrName, String tel, String openId) throws Exception {
        Map<String, Object> orderData = new HashMap<String, Object>();
        Map<String, String> requestData = new HashMap<String, String>();
        // request url
        String url = NameUtils.getConfig("efast_base_url");

        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");

        //颜色表查询
        ProductColor productColor =	productColorService.selectProductColorById(colorId);

        //地址截取
        String [] addressDesc = address.split("-");

        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 = "重庆";
        }


        String	sd_id = NameUtils.getConfig("sd_id");

        orderData.put("add_time", DateTimeUtil.format(new Date()));				// 时间
        orderData.put("address", addressDesc[3]);								// 收货地址
        orderData.put("city_name", addressDesc[1]); 							// 城市
        orderData.put("consignee", addrName);									// 收货人
        orderData.put("district_name", addressDesc[2]);							// 区域
        orderData.put("email", "");												// email
        orderData.put("goods_amount", 0);			// 商品总价
        orderData.put("goods_count", 1);										// 产品数量
        orderData.put("mobile", tel);											// 手机号码
        orderData.put("money_paid", 0);				// 已付款
        // 兑换
        orderData.put("oid", id);		// 订单号
        orderData.put("order_amount", 0);			// 应付款,应付款金额要与已付款金额相同


        /**
         * 产品信息
         */
        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
        Map<String, Object> orders1 = new HashMap<String, Object>();
        orders1.put("goods_name", productColor.getColorProductName());	// 产品名称
        orders1.put("goods_number",1);									    	// 产品数量
        orders1.put("goods_price", 0);				// 产品原价
        orders1.put("outer_sku", productColor.getColor69Code());				// 产品SKU
        orders1.put("payment_ft", 0);		// 产品分摊价
        maps.add(orders1);


        orderData.put("orders", maps);													// 订单产品
        orderData.put("pay_name", "weixinpay");											// 支付方式
        orderData.put("pay_time", DateTimeUtil.format(new Date()));						// 支付时间
        orderData.put("postscript", "");												// 买家留言
        orderData.put("province_name", provinceName);									// 省份
        orderData.put("sd_id", sd_id);													// 对应 efast 店铺 id
        orderData.put("shipping_fee", 0);												// 快递费
        orderData.put("shipping_name", "yto");											// 快递公司代码
        orderData.put("tel", "");											// 我司电话
        orderData.put("to_buyer", "");													// 商家备注
        orderData.put("total_amount", 0);					// 订单总额
        orderData.put("user_name", openId);												// 买家账户   百胜根据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-推送订单号为:" + id + "的订单，百胜返回信息:" + 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-推送订单号为:" + id + "的订单，百胜返回信息:" + result);
            throw new Exception(respData.getString("msg"));
        } catch (Exception e) {
            throw e;
        }
    }
}
