package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
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.security.UserCenter;
import com.hai.common.utils.CoordCommonUtil;
import com.hai.common.utils.PageUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.HuiLianTongUnionCardConfig;
import com.hai.config.TuanYouConfig;
import com.hai.config.WxOrderConfig;
import com.hai.entity.HighChildOrder;
import com.hai.entity.HighGasOilPrice;
import com.hai.entity.HighMerchantStore;
import com.hai.entity.HighOrder;
import com.hai.enum_type.GasOilPriceStatusEnum;
import com.hai.enum_type.MerStoreAmountSourceTypeEnum;
import com.hai.enum_type.MerStoreAmountTypeEnum;
import com.hai.enum_type.OrderPayTypeEnum;
import com.hai.model.HighMerchantStoreModel;
import com.hai.model.OrderRefundModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.msg.entity.MsgTopic;
import com.hai.service.*;
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.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
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;

    @Resource
    private HighMerchantStoreService merchantStoreService;

    @Resource
    private HighUserService highUserService;

    @Resource
    private HighOilCardService oilCardService;

    @Autowired
    private UserCenter userCenter;

    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping(value="/getGasStatistical",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询油站统计")
    public ResponseData getGasStatistical() {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null || userInfoModel.getMerchantStore() == null) {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            Map<String, Object> param = new HashMap<>();;
            param.put("gasName", userInfoModel.getMerchantStore().getStoreName());

            Map<String, Object> today = new HashMap<>();

            Map<String, Object> incometObject = highOrderService.getGasTheDayOrderCount(userInfoModel.getMerchantStore().getId(), "2,3,6,7");
            today.put("incomePrice", incometObject.get("price"));
            today.put("incomeCount", incometObject.get("count"));

            Map<String, Object> refundObject = highOrderService.getGasTheDayOrderCount(userInfoModel.getMerchantStore().getId(), "4");
            today.put("refundPrice", refundObject.get("price"));
            today.put("refundCount", refundObject.get("count"));
            param.put("today", today);

            return ResponseMsgUtil.success(param);

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

    @RequestMapping(value="/getGasOrderList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油站订单列表")
    public ResponseData getGasOrderList(@RequestParam(name = "orderNo", required = false) String orderNo,
                                        @RequestParam(name = "status", required = false) Integer status,
                                        @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                        @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null || userInfoModel.getMerchantStore() == null) {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            Map<String, Object> param = new HashMap<>();;
            param.put("storeId", userInfoModel.getMerchantStore().getId());
            param.put("orderNo", orderNo);

            if (status == null) {
                param.put("status", "2,3,4,6,7");
            } else {
                param.put("status", status);
            }

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(highOrderService.getGasOrderList(param)));

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

    @RequestMapping(value="/getGasOrderDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油站订单详情")
    public ResponseData getGasOrderDetail(@RequestParam(name = "orderNo", required = true) String orderNo) {
        try {

            return ResponseMsgUtil.success(highOrderService.getGasOrderDetail(orderNo));

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

    @RequestMapping(value="/disabledOil",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "禁用油品")
    public ResponseData disabledOil(@RequestBody JSONObject body) {
        try {
            if (body.getLong("storeId") == null || body.getInteger("oilNo") == null) {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询油品价格
            HighGasOilPrice oilNo = highGasOilPriceService.getGasOilPriceByStoreAndOilNo(body.getLong("storeId"), body.getInteger("oilNo"));
            if (oilNo == null) {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            oilNo.setStatus(GasOilPriceStatusEnum.status2.getStatus());
            highGasOilPriceService.editGasOilPrice(oilNo);

            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/enableOil",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "启用油品")
    public ResponseData enableOil(@RequestBody JSONObject body) {
        try {
            if (body.getLong("storeId") == null || body.getInteger("oilNo") == null) {
                log.error("HighGasController -> enableOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询油品价格
            HighGasOilPrice oilNo = highGasOilPriceService.getGasOilPriceByStoreAndOilNo(body.getLong("storeId"), body.getInteger("oilNo"));
            if (oilNo == null) {
                log.error("HighGasController -> enableOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            oilNo.setStatus(GasOilPriceStatusEnum.status1.getStatus());
            highGasOilPriceService.editGasOilPrice(oilNo);

            return ResponseMsgUtil.success("操作成功");

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

    @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() != 3) {
                log.error("HighOrderController --> refuelingOrderRefund() error!", "退款失败，订单状态准许退款");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "退款失败，订单状态准许退款");
            }

            for (HighChildOrder childOrder : order.getHighChildOrderList()) {
                if (!childOrder.getGoodsType().equals(3)) {
                    log.error("HighOrderController --> refuelingOrderRefund() error!", "退款失败，不属于加油站订单");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "退款失败，不属于加油站订单");
                }
                // 查询加油站
                HighMerchantStoreModel store = merchantStoreService.getMerchantStoreById(childOrder.getGoodsId());
                if (store == null) {
                    log.error("HighOrderController --> refuelingOrderRefund() error!", "退款失败，未找到加油站信息");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "退款失败，未找到加油站信息");
                }

                // 来源类型  1：平台自建   2：团油
                if (store.getSourceType().equals(1)) {

                    if (order.getPayType() == 2) {
                        OrderRefundModel orderRefundModel = WxOrderConfig.orderToRefund(order.getPaySerialNo(), order.getPayRealPrice(), order.getPayRealPrice());
                        if(orderRefundModel.getResult_code().equals("SUCCESS")) {
                            order.setOrderStatus(4);
                            order.setRefundTime(new Date());
                            order.setRefundPrice(order.getPayRealPrice());
                            highOrderService.updateOrderDetail(order);
                        }
                    } else if (order.getPayType() == 3){
                        // 积分退款
                        highUserService.goldHandle(order.getMemId(), order.getPayGold(),1, 2, order.getId());
                        order.setOrderStatus(4);
                        order.setRefundTime(new Date());
                        order.setRefundPrice(order.getPayRealPrice());
                        highOrderService.updateOrderDetail(order);

                    } else if (order.getPayType() == 4) {
                        String refundOrderNo = String.valueOf(System.currentTimeMillis());
                        JSONObject refund = HuiLianTongUnionCardConfig.refund(refundOrderNo, order.getPaySerialNo());
                        if(!refund.getString("respCode").equals("0000")) {
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR,refund.getString("respMessage"));
                        }
                        JSONObject consumptionResult = HuiLianTongUnionCardConfig.resolveResponse(refund.getString("data"));
                        if (consumptionResult.getBoolean("success") != true) {
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "交易失败!"+consumptionResult.getString("message"));
                        }
                        order.setOrderStatus(4);
                        order.setRefundTime(new Date());
                        order.setRefundPrice(order.getPayRealPrice());
                        highOrderService.updateOrderDetail(order);
                    } else if (order.getPayType().equals(OrderPayTypeEnum.type7.getType())) {
                        // 油卡退款
                        oilCardService.refund(order.getOrderNo());
                    }

                    Map<String, Object> pushParam = new HashMap<>();
                    pushParam.put("businessType", MerStoreAmountTypeEnum.type1.getType());
                    pushParam.put("storeId", store.getId());
                    pushParam.put("price", order.getTotalPrice());
                    pushParam.put("sourceType", MerStoreAmountSourceTypeEnum.type3.getType());
                    pushParam.put("sourceId", order.getId());
                    pushParam.put("sourceContent", "订单号：" + order.getOrderNo() + ",退款金额：￥" + order.getTotalPrice());
                    // 退款到预存余额
                    this.redisTemplate.boundListOps(MsgTopic.MerStoreAccount.getName()).leftPush(pushParam);

                    order.setOrderStatus(4);
                    order.setRefundTime(new Date());
                    order.setRefundContent(body.getString("refundContent"));
                    highOrderService.updateOrderDetail(order);

                } else if (store.getSourceType().equals(2)) {
                    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);
        }
    }*/

}
