package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.CoordCommonUtil;
import com.hai.common.utils.PageUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.TuanYouConfig;
import com.hai.entity.HighOrder;
import com.hai.model.ResponseData;
import com.hai.service.HighGasOilPriceService;
import com.hai.service.HighOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/highGas")
@Api(value = "团油业务接口")
public class HighGasController {

    private static Logger log = LoggerFactory.getLogger(HighGasController.class);

    @Resource
    private HighGasOilPriceService highGasOilPriceService;

    @Resource
    private HighOrderService highOrderService;

    @RequestMapping(value="/getGasStoreList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询加油站列表")
    public ResponseData getGasStoreList(@RequestParam(name = "storeName", required = false) String storeName,
                                        @RequestParam(name = "distance", required = true) Integer distanceRecent,
                                        @RequestParam(name = "regionId", required = true) Long regionId,
                                        @RequestParam(name = "oilNoName", required = true) String oilNoName,
                                        @RequestParam(name = "longitude", required = true) String longitude,
                                        @RequestParam(name = "latitude", required = true) String latitude,
                                        @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                        @RequestParam(name = "pageSize", required = true) Integer pageSize
    ) {
        try {
            if (StringUtils.isBlank(storeName)) {
                storeName = null;
            }
            List<Map<String, Object>> storeList = highGasOilPriceService.getStoreListByOilNo(storeName,regionId, oilNoName);
            for (Map<String, Object> store : storeList) {
                double distance = CoordCommonUtil.getDistance(Double.valueOf(store.get("latitude").toString()), Double.valueOf(store.get("longitude").toString()), Double.valueOf(latitude), Double.valueOf(longitude));
                store.put("distance", Math.round(distance/100d)/10d);
            }
            List<Map<String, Object>> distance = storeList.stream().sorted(Comparator.comparingDouble(entry ->  Double.valueOf(entry.get("distance").toString()))).collect(Collectors.toList());
            Iterator<Map<String, Object>> iterator = distance.iterator();
            while (iterator.hasNext()) {
                if ((int)Math.round(Double.valueOf(iterator.next().get("distance").toString()))  > distanceRecent.intValue()) {
                    iterator.remove();
                }
            }
            return ResponseMsgUtil.success(PageUtil.initPageInfoObj(pageNum,distance.size(),pageSize,new PageInfo<>(distance)));

        } catch (Exception e) {
            log.error("HighGasController -> getGasDetailByStoreKey() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getGasDetailByStoreKey",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据门店key 查询")
    public ResponseData getGasDetailByStoreKey(@RequestParam(name = "storeKey", required = true) String storeKey,
                                               @RequestParam(name = "longitude", required = true) String longitude,
                                               @RequestParam(name = "latitude", required = true) String latitude) {
        try {

            JSONObject jsonObject = TuanYouConfig.queryGasInfoByGasId(storeKey);
            if (jsonObject != null && jsonObject.getString("code").equals("200")) {
                JSONObject result = jsonObject.getJSONObject("result");
                double distance = CoordCommonUtil.getDistance(Double.valueOf(result.get("gasAddressLatitude").toString()), Double.valueOf(result.get("gasAddressLongitude").toString()), Double.valueOf(latitude), Double.valueOf(longitude));
                result.put("distance", Math.round(distance/100d)/10d);
                return ResponseMsgUtil.success(jsonObject.get("result"));
            }
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未获取到加油站信息");

        } catch (Exception e) {
            log.error("HighGasController -> getGasDetailByStoreKey() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getGasPriceDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据门店key和油号 查询油价")
    public ResponseData getGasPriceDetail(@RequestParam(name = "storeKey", required = true) String storeKey,
                                          @RequestParam(name = "oilNo", required = true) String oilNo) {
        try {

            JSONObject jsonObject = TuanYouConfig.queryCompanyPriceDetail(storeKey,oilNo);
            if (jsonObject != null && jsonObject.getString("code").equals("200")) {
                if(jsonObject.getJSONArray("result").size() == 0) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未获取到价格信息");
                }
                return ResponseMsgUtil.success(jsonObject.get("result"));
            }
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未获取到价格信息");

        } catch (Exception e) {
            log.error("HighGasController -> getGasPriceDetail() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/refuelingOrderRefund",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "订单退款")
    public ResponseData refuelingOrderRefund(@RequestBody JSONObject body) {
        try {

            if(body == null && body.getLong("orderId") == null && StringUtils.isBlank(body.getString("refundContent"))) {
                log.error("HighOrderController --> refuelingOrderRefund() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            HighOrder order = highOrderService.getOrderById(body.getLong("orderId"));
            if(order == null) {
                log.error("HighOrderController --> refuelingOrderRefund() error!", "未找到订单信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到订单信息");
            }
            // 订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消   6.退款中   7.拒绝退款
            if (order.getOrderStatus() != 2) {
                log.error("HighOrderController --> refuelingOrderRefund() error!", "提交退款审核失败，订单不处于已支付");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "提交退款审核失败，订单不处于已支付");
            }

            JSONObject object = TuanYouConfig.refuelingOrderRefund(order.getMemPhone(), order.getOrderNo(), body.getString("refundContent"));
            if (object == null || !object.getString("code").equals("200")) {
                log.error("HighOrderController --> refuelingOrderRefund() error!", "提交退款审核失败," + object.getString("message"));
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "提交退款审核失败，" + object.getString("message"));
            }

            order.setOrderStatus(6);
            highOrderService.updateOrderDetail(order);
            return ResponseMsgUtil.success("退款审核中");

        } catch (Exception e) {
            log.error("HighGasController -> refuelingOrderRefund() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

   /* @RequestMapping(value="/refuelingOrderPush",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "推送订单")
    public ResponseData refuelingOrderPush() {
        try {

            Map<String,Object> map = new HashMap<>();
            map.put("gasId", "CS000116576");
            map.put("oilNo", "92");
            map.put("gunNo", 1);
            BigDecimal priceGun = new BigDecimal("6");
            BigDecimal priceVip = new BigDecimal("4.9");
            //BigDecimal priceGun = new BigDecimal("5.58");
            //BigDecimal priceVip = new BigDecimal("5.58");
            map.put("priceGun", priceGun);  // 枪单价
            map.put("priceVip", priceVip);  // 优惠价
            map.put("driverPhone", "17726395120");
            map.put("thirdSerialNo", new Date().getTime());


            BigDecimal refuelingAmount = new BigDecimal("1200").divide(priceGun,2,BigDecimal.ROUND_HALF_UP).multiply(priceVip).setScale(2,BigDecimal.ROUND_HALF_UP);
            map.put("refuelingAmount", refuelingAmount);
            JSONObject orderPushObject = TuanYouConfig.refuelingOrderPush(map);
            if (orderPushObject == null || !orderPushObject.getString("code").equals("200")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "提交订单，出现了未知错误");
            }
            JSONObject result = orderPushObject.getJSONObject("result");
            return ResponseMsgUtil.success(result.getString("orderNo"));
            //return ResponseMsgUtil.success(map);


        } catch (Exception e) {
            log.error("HighGasController -> refuelingOrderPush() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/queryThirdOrderDretail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询订单信息")
    public ResponseData queryThirdOrderDretail() {
        try {


            return ResponseMsgUtil.success(TuanYouConfig.queryThirdOrderDretail("1624611159129"));
            //return ResponseMsgUtil.success(map);


        } catch (Exception e) {
            log.error("HighGasController -> queryThirdOrderDretail() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/test",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "测试")
    public ResponseData test() {
        try {

            String data = "{\"data\":\"ui2KbK5jpLtw7YaA52uSt1TzDpaE5OjeW5O6xg+saM4nN4aVnpoT1aTgJwQt/DuNSbs7LrX6q1B0cpW5T531ltYl1ERxyKXqZyMKBNWzDFuB5QSww22VGfypchGNm+oW\",\"timestamp\":1624611912047,\"companyCode\":\"208241666939552\"}";

            JSONObject jsonObject = JSONObject.parseObject(data, JSONObject.class);
            //return ResponseMsgUtil.success(AESEncodeUtil.aesDecryptByBytes(AESEncodeUtil.base64Decode(jsonObject.getString("data")), SysConst.getSysConfig().getTuanYouAppSecret()));
            return ResponseMsgUtil.success(CommonSysConst.getSysConfig().getTuanYouUrl());

        } catch (Exception e) {
            log.error("HighGasController -> queryThirdOrderDretail() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }*/

}
