package com.sqx.modules.callBack.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.sqx.common.constant.RedisKey;
import com.sqx.common.exception.SqxException;
import com.sqx.common.utils.Result;
import com.sqx.common.utils.SignUtil;
import com.sqx.modules.address.entity.Address;
import com.sqx.modules.address.service.AddressService;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.callBack.dto.CallBackDto;
import com.sqx.modules.errand.entity.TbIndent;
import com.sqx.modules.errand.service.TbIndentService;
import com.sqx.modules.goods.entity.GoodsShop;
import com.sqx.modules.goods.service.GoodsShopService;
import com.sqx.modules.order.dao.OrderGoodsDao;
import com.sqx.modules.order.entity.OrderGoods;
import com.sqx.modules.order.entity.TbOrder;
import com.sqx.modules.order.service.AppOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/back")
@Slf4j
public class CallBackController {

    @Autowired
    TbIndentService tbIndentService;

    @Autowired
    UserService userService;

    @Autowired
    AppOrderService appOrderService;

    @Autowired
    private GoodsShopService goodsShopService;

    @Autowired
    private OrderGoodsDao orderGoodsDao;


    @Autowired
    private AddressService addressService;

    /**
     * 回调
     */
    @PostMapping("/open")
    public String back(String expire_time, String sign, String trade_no, String order_no, String state, String note, String courier, String longitude, String latitude, String tel, String update_time) {

        log.info("状态："+state);
        log.info("订单号："+order_no);
        log.info("骑手手机号："+tel);

        UserEntity userEntity = userService.queryByPhone(tel);
        if (ObjectUtils.isEmpty(userEntity)) {
            log.info("不存在该手机号的骑手：" + tel);
            return "success";
        }

//            获取骑手订单
        TbIndent tbIndent = tbIndentService.findIndentByIndentNumber(order_no);
        if (ObjectUtils.isEmpty(tbIndent)) {
            log.info("不存在该配送订单：" + order_no);
            return "success";
        }

//            获取订单id
        TbOrder tbOrder = appOrderService.getOne(new QueryWrapper<TbOrder>().eq("order_number", order_no));
        if (ObjectUtils.isEmpty(tbOrder)) {
            log.info("不存在该订单：" + order_no);
            return "success";
        }

        //            状态
        if ("4".equals(state)) {//接单
            log.info("骑手接单：" + order_no);
            tbOrder.setStatus(3);
            appOrderService.updateOrder(tbOrder);
            tbIndentService.orderIndentReceiving(userEntity.getUserId(), tbOrder.getOrderId()+"");
        } else if ("5".equals(state)) {//取餐
            log.info("骑手取餐：" + order_no);
            tbOrder.setStatus(3);
            appOrderService.updateOrder(tbOrder);
            if ("2".equals(tbIndent.getIndentState())) {
                tbIndent.setIndentState("4"); // 4：骑手已取货/购买
                String receiveTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                tbIndent.setRiderUserId(userEntity.getUserId());
                tbIndent.setReceivingTime(receiveTimeStr);
                tbIndentService.updateById(tbIndent);
            }

            tbIndentService.riderBuyGoods(tbIndent);
        } else if ("6".equals(state)) {//完成订单
            log.info("骑手完成订单：" + order_no);
            tbIndentService.finalizeOrder(userEntity.getUserId(), tbIndent);
        }
        return "success";
    }

    @GetMapping("/open/test")
    public Result test(String orderNumber){
        TbOrder order = appOrderService.getOne(new QueryWrapper<TbOrder>().eq("order_number", orderNumber));

        log.info("第一次创建快跑者订单");
        String responseBody = creatSpeedRunnerOrder(order);
        if (ObjectUtils.isNotEmpty(responseBody)) {
            String tradeNo = getTradeNo(responseBody);
            log.info("第一次创建快跑者订单返回的订单号：" + tradeNo);
            if (ObjectUtils.isNotEmpty(tradeNo)) {
                order.setTradeNo(tradeNo);
                appOrderService.updateById(order);
            } else {
                log.info("创建快跑者订单的返回的订单为空，第二次创建");
                String responseBody2 = creatSpeedRunnerOrder(order);
                if (ObjectUtils.isNotEmpty(responseBody2)) {
                    String tradeNo2 = getTradeNo(responseBody2);
                    log.info("第二次创建快跑者订单返回的订单号：" + tradeNo2);
                    if (ObjectUtils.isNotEmpty(tradeNo2)) {
                        order.setTradeNo(tradeNo2);
                        appOrderService.updateById(order);
                    }
                }
            }
        } else {
            String responseBody2 = creatSpeedRunnerOrder(order);
            if (ObjectUtils.isNotEmpty(responseBody2)) {
                String tradeNo2 = getTradeNo(responseBody2);
                log.info("第二次创建快跑者订单返回的订单号：" + tradeNo2);
                if (ObjectUtils.isNotEmpty(tradeNo2)) {
                    order.setTradeNo(tradeNo2);
                    appOrderService.updateById(order);
                }
            }
        }
        return Result.success();
    }

    public static void main(String[] args) {
        StringBuilder append = new StringBuilder().append("爆料鸡排\t(藤椒风味酱-香辣花生撒粉）约120克介意慎拍");
        String s1= append.toString().replaceAll("\\t", " ");
        String s="爆料鸡排\t(藤椒风味酱-香辣花生撒粉）约120克介意慎拍".replaceAll("\\t", " ");
        System.out.println("s = " + s);
        System.out.println("append = " + s1);
    }

    public String creatSpeedRunnerOrder(TbOrder tbOrder){
//               获取店铺信息
        GoodsShop goodsShop = goodsShopService.getById(tbOrder.getShopId());
//               获取餐品信息
        List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>()
                .eq("order_id", tbOrder.getOrderId()));
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < orderGoodsList.size(); i++) {
            OrderGoods orderGoods = orderGoodsList.get(i);
            double goodsPrice = orderGoods.getGoodsPrice().doubleValue();
            Integer goodsNum = orderGoods.getGoodsNum();
            String goodsName = orderGoods.getGoodsName();
            if (i == 0) {
                stringBuilder.append(goodsName).append("(").append(goodsPrice).append("x").append(goodsNum).append(")");
            } else {
                stringBuilder.append(",").append(goodsName).append("(").append(goodsPrice).append("x").append(goodsNum).append(")");

            }
        }
//               获取用户收货地址
        Address address = addressService.getById(tbOrder.getAddressId());

        JSONObject body = new JSONObject();
        String shopId = tbOrder.getShopId()+"";
        if (ObjectUtils.isNotEmpty(shopId)) {
            try {
                shopId = URLEncoder.encode(shopId, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        body.put("shop_id", shopId);

        String shopName = goodsShop.getShopName();
        if (ObjectUtils.isNotEmpty(shopName)) {
            try {
                shopName = URLEncoder.encode(shopName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
//            shopName=shopName.replaceAll("\\+","-");
        }
        body.put("shop_name", shopName);

        String phone = goodsShop.getPhone();
        if (ObjectUtils.isNotEmpty(phone)) {
            try {
                phone = URLEncoder.encode(phone, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        body.put("shop_tel", phone);


        String detailedAddress = goodsShop.getDetailedAddress();
        if (ObjectUtils.isNotEmpty(detailedAddress)) {
            try {
                detailedAddress = URLEncoder.encode(detailedAddress, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
//            detailedAddress=detailedAddress.replaceAll("\\+","-");
        }
        body.put("shop_address", detailedAddress);


        String shopTag  =goodsShop.getShopLng() + "," + goodsShop.getShopLat();
        if (ObjectUtils.isNotEmpty(detailedAddress)) {
            try {
                shopTag = URLEncoder.encode(shopTag, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        body.put("shop_tag", shopTag);


//        将+变成-
        String orderContent = stringBuilder.toString();
        if (ObjectUtils.isNotEmpty(orderContent)) {
            try {
                orderContent=orderContent.replaceAll("\\t", " ");
                orderContent = URLEncoder.encode(orderContent, "UTF-8");
//                orderContent=orderContent.replaceAll("🦆","");
//                orderContent=orderContent.replaceAll("（双拼）","");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
//            orderContent=orderContent.replaceAll("\\+","-");
        }
        body.put("order_content", orderContent);


        String remark = tbOrder.getRemark();
        if (ObjectUtils.isNotEmpty(remark)) {
            try {
                remark=remark.replaceAll("\\r\\n|\\n|\\r", " ");
                remark = URLEncoder.encode(remark, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
//            remark=remark.replaceAll("\\+","-");
        }
        body.put("order_note", remark);

        String orderSequence = tbOrder.getOrderSequence();
        if (ObjectUtils.isNotEmpty(orderSequence)) {
            try {
                orderSequence =URLEncoder.encode(orderSequence, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        body.put("order_mark", orderSequence);


        body.put("order_from", shopName+ "#" + orderSequence);


        String payTime = tbOrder.getPayTime();
        if (ObjectUtils.isNotEmpty(payTime)) {
            try {
                payTime = URLEncoder.encode(payTime, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        body.put("order_time", payTime);


        String userName = address.getUserName();
        if (ObjectUtils.isNotEmpty(userName)) {
            try {
                userName = URLEncoder.encode(userName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
//            userName=userName.replaceAll("\\+","-");
        }
        body.put("customer_name", userName);

        String userPhone = tbOrder.getPhone();
        if (ObjectUtils.isNotEmpty(userPhone)) {
            try {
                userPhone = URLEncoder.encode(userPhone, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        body.put("customer_tel", userPhone);


        String addressDetail = address.getAddressDetail();
        if (ObjectUtils.isNotEmpty(addressDetail)) {
            try {
                addressDetail = URLEncoder.encode(addressDetail, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }

//            addressDetail=addressDetail.replaceAll("\\+","-");
        }
        body.put("customer_address", addressDetail);


        String customerTag=address.getLng() + "," + address.getLat();
        if (ObjectUtils.isNotEmpty(customerTag)) {
            try {
                customerTag = URLEncoder.encode(customerTag, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        body.put("customer_tag", customerTag);


        String orderNumber = tbOrder.getOrderNumber();
        if (ObjectUtils.isNotEmpty(orderNumber)) {
            try {
                orderNumber = URLEncoder.encode(orderNumber, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        body.put("order_no", orderNumber);

        String payMoney = tbOrder.getPayMoney().toPlainString();
        if (ObjectUtils.isNotEmpty(payMoney)) {
            try {
                payMoney = URLEncoder.encode(payMoney, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        body.put("order_price",payMoney);
        body.put("pay_status", 0);

        log.info("body信息：" + body);

//               版本
        String version = "1";
//               时间戳
        long currentTimeMillis = System.currentTimeMillis();
        long currentTimeSeconds = currentTimeMillis / 1000;
        String timestamp = String.valueOf(currentTimeSeconds);
        log.info("timestamp: "+timestamp);
//               唯一标识符
        String ticket = "83f0ff99-7c8e-47e8-8802-bd3754414a52";
//               团队token
        String teamToken = "Q444DMV4LT8WSGRW";
//               开发者中心的开发密钥
        String devKey = "31RRHA4O165VFN9W2DAPDYDH8N83BT12";

        JSONObject body2 = new JSONObject();
//        String shopId = tbOrder.getShopId()+"";
        body2.put("shop_id", tbOrder.getShopId()+"");

//        String shopName = goodsShop.getShopName();
        body2.put("shop_name", goodsShop.getShopName());

//        String phone = goodsShop.getPhone();
        body2.put("shop_tel", goodsShop.getPhone());

//        String detailedAddress = goodsShop.getDetailedAddress();
        body2.put("shop_address", goodsShop.getDetailedAddress());


//        String shopTag  =goodsShop.getShopLng() + "," + goodsShop.getShopLat();
        body2.put("shop_tag", goodsShop.getShopLng() + "," + goodsShop.getShopLat());


//        将+变成-
        String orderContent2 = stringBuilder.toString();
        if (ObjectUtils.isNotEmpty(orderContent2)) {
            orderContent2=orderContent2.replaceAll("\\t", " ");
        }

        body2.put("order_content", orderContent2);


        String remark2 = tbOrder.getRemark();
        if (ObjectUtils.isNotEmpty(remark2)) {
            remark2=remark2.replaceAll("\\r\\n|\\n|\\r", " ");

            // 方法2：使用Java 8+的\\R正则表达式;
        }
        body2.put("order_note", remark2);

//        String orderSequence = tbOrder.getOrderSequence();
        body2.put("order_mark", tbOrder.getOrderSequence());


        body2.put("order_from", goodsShop.getShopName()+ "#" + tbOrder.getOrderSequence());


//        String payTime = tbOrder.getPayTime();

        body2.put("order_time", tbOrder.getPayTime());


//        String userName = address.getUserName();

        body2.put("customer_name", address.getUserName());

//        String userPhone = address.getUserPhone();

        body2.put("customer_tel", tbOrder.getPhone());


//        String addressDetail = address.getAddressDetail();
        body2.put("customer_address", address.getAddressDetail());


//        String customerTag=address.getLng() + "," + address.getLat();
        body2.put("customer_tag", address.getLng() + "," + address.getLat());


//        String orderNumber = tbOrder.getOrderNumber();

        body2.put("order_no", tbOrder.getOrderNumber());

//        String payMoney = tbOrder.getPayMoney().toPlainString();
        body2.put("order_price",tbOrder.getPayMoney().toPlainString());
        body2.put("pay_status", 0);
        log.info("body2信息：" + body2);
//               获取签名
        String sign = SignUtil.getSign(body2.toString(), devKey, teamToken, ticket, currentTimeSeconds, 1);
        String responseBody="";
        try {
            log.info("创建快跑者订单");
            CloseableHttpClient client = HttpClients.createDefault();
            // 创建httppost
            HttpPost httpPost = new HttpPost("https://open.keloop.cn/open/order/createOrder");
            String params = "version=" + version + "&timestamp=" + timestamp + "&ticket=" + ticket + "&team_token=" + teamToken + "&dev_key=" + devKey + "&sign=" + sign + "&body=" + body.toString(); // 注意：这里不需要手动编码，HttpClient会处理它。
            System.out.println("params = " + params);
            StringEntity entity = new StringEntity(params, StandardCharsets.UTF_8);
            entity.setContentType("application/x-www-form-urlencoded"); // 设置Content-Type为application/x-www-form-urlencoded，但不是必须的，HttpClient会自动设置。
            httpPost.setEntity(entity);
            responseBody = EntityUtils.toString(client.execute(httpPost).getEntity());
            log.info("创建结果："+responseBody);
        }catch (Exception e){
            e.printStackTrace();
//            throw new RuntimeException("responseBody");
        }
        return responseBody;
    }

    public static String getTradeNo(String responseBody){
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(responseBody);
        String tradeNo="";
        Integer code = jsonObject.getInteger("code");
        if (ObjectUtils.isNotEmpty(code)) {
            if (code==200) {
                JSONObject date = jsonObject.getJSONObject("data");
                tradeNo = date.getString("trade_no");
            }
        }
        return tradeNo;
    }

}
