package com.cweb.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.CommonSysConst;
import com.hai.config.TuanYouConfig;
import com.hai.dao.HighGasOrderPushMapper;
import com.hai.entity.*;
import com.hai.enum_type.GasOilPriceStatusEnum;
import com.hai.enum_type.MerchantStoreSourceType;
import com.hai.enum_type.OrderPushType;
import com.hai.model.HighMerchantStoreModel;
import com.hai.model.ResponseData;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
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.math.BigDecimal;
import java.math.RoundingMode;
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 CommonService commonService;

    @Resource
    private HighTyAgentOilStationService tyAgentOilStationService;

    @Resource
    private HighTyAgentPriceService tyAgentPriceService;

    @Resource
    private HighGasOrderPushMapper highGasOrderPushMapper;

    @Resource
    private HighMerchantStoreService merchantStoreService;

    @Resource
    private HighGasOilPriceService gasOilPriceService;

    @Resource
    private HighGasOilGunNoService gasOilGunNoService;

    @Resource
    private HighGasDiscountOilPriceService gasDiscountOilPriceService;

    @RequestMapping(value="/getGasStoreList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询加油站列表")
    public ResponseData getGasStoreList(@RequestParam(name = "isTyAgent", required = false) Boolean isTyAgent,
                                        @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 = false) String longitude,
                                        @RequestParam(name = "latitude", required = false) String latitude,
                                        @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                        @RequestParam(name = "pageSize", required = true) Integer pageSize
    ) {
        try {
            if (StringUtils.isBlank(storeName)) {
                storeName = null;
            }
            SecRegion region = commonService.getParentByRegion(regionId);
            if (region != null) {
                List<Map<String, Object>> storeList = highGasOilPriceService.getStoreListByOilNo(storeName,region.getRegionId(), oilNoName);
                for (Map<String, Object> store : storeList) {
                    if (MapUtils.getInteger(store, "source_type").equals(1)) {
                        if (StringUtils.isNotBlank(MapUtils.getString(store, "store_logo"))) {
                            store.put("store_logo", CommonSysConst.getSysConfig().getHsgDomainName() +"/filesystem/"+MapUtils.getString(store, "store_logo"));
                        } else {
                            store.put("store_logo", null);
                        }
                    }

                    if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)
                            && StringUtils.isNotBlank(store.get("longitude").toString()) && StringUtils.isNotBlank(store.get("latitude").toString())) {
                        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);
                    } else {
                        store.put("distance", null);
                    }
                }

                PageInfo<Map<String, Object>> mapPageInfo;
                if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)) {
                    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();
                        }
                    }
                    mapPageInfo = PageUtil.initPageInfoObj(pageNum, distance.size(), pageSize, new PageInfo<>(distance));
                } else {
                    mapPageInfo = PageUtil.initPageInfoObj(pageNum, storeList.size(), pageSize, new PageInfo<>(storeList));
                }

                for (Map<String, Object> map : mapPageInfo.getList()) {
                    if (StringUtils.isNotBlank(MapUtils.getString(map, "oil_no"))) {

                        if (MapUtils.getInteger(map, "source_type").equals(1)) {
                            // 查询是否配置了【油站的】优惠比例
                            HighTyAgentPrice tyAgentPrice = tyAgentPriceService.getDetail(1, MapUtils.getLong(map, "id"), MapUtils.getString(map, "oil_no"));
                            if (tyAgentPrice != null) {
                                // 优惠比例 / 100 = 最终优惠比例
                                BigDecimal priceRate = tyAgentPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                                // 油枪价 - 优惠幅度
                                BigDecimal price = new BigDecimal(MapUtils.getString(map, "price_gun")).subtract(new BigDecimal(MapUtils.getString(map, "preferential_margin")));
                                // (油枪价 - 优惠幅度) * 系统折扣
                                map.put("price_vip", price.multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));

                            } else {
                                // 查询是否配置了【油品】优惠比例
                                HighGasDiscountOilPrice gasDiscountOilPrice = gasDiscountOilPriceService.getDetailByOilNo(MapUtils.getString(map, "oil_no"));
                                if (gasDiscountOilPrice != null) {
                                    // 优惠比例 / 100 = 最终优惠比例
                                    BigDecimal priceRate = gasDiscountOilPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                                    // 油枪价 - 优惠幅度
                                    BigDecimal price = new BigDecimal(MapUtils.getString(map, "price_gun")).subtract(new BigDecimal(MapUtils.getString(map, "preferential_margin")));
                                    // (油枪价 - 优惠幅度) * 系统折扣
                                    map.put("price_vip", price.multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                                }
                            }

                            // 查询是否配置了【代理商】优惠比例
                            if (isTyAgent != null && isTyAgent == true) {
                                HighTyAgentPrice agentPrice = tyAgentPriceService.getDetail(2, MapUtils.getLong(map, "id"), MapUtils.getString(map, "oil_no"));
                                if (agentPrice != null) {
                                    // 优惠比例 / 100 = 最终优惠比例
                                    BigDecimal priceRate = agentPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                                    // 油枪价 - 优惠幅度
                                    BigDecimal price = new BigDecimal(MapUtils.getString(map, "price_gun")).subtract(new BigDecimal(MapUtils.getString(map, "preferential_margin")));
                                    // (油枪价 - 优惠幅度) * 系统折扣
                                    map.put("price_vip", price.multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                                }
                            }

                        } else if (MapUtils.getInteger(map, "source_type").equals(2)) {
                            // 查询是否配置了【油站的】优惠比例
                            HighTyAgentPrice tyAgentPrice = tyAgentPriceService.getDetail(1, MapUtils.getLong(map, "id"), MapUtils.getString(map, "oil_no"));
                            if (tyAgentPrice != null) {
                                // 优惠比例 / 100 = 最终优惠比例
                                BigDecimal priceRate = tyAgentPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                                // 油品国标价 * 最终优惠比例
                                map.put("price_vip", new BigDecimal(MapUtils.getString(map, "price_gun")).multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                            } else {
                                // 查询是否配置了【油品】优惠比例
                                HighGasDiscountOilPrice gasDiscountOilPrice = gasDiscountOilPriceService.getDetailByOilNo(MapUtils.getString(map, "oil_no"));
                                if (gasDiscountOilPrice != null) {
                                    // 优惠比例 / 100 = 最终优惠比例
                                    BigDecimal priceRate = gasDiscountOilPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                                    // 油品国标价 * 最终优惠比例
                                    map.put("price_vip", new BigDecimal(MapUtils.getString(map, "price_gun")).multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                                }
                            }

                            // 查询是否配置了【代理商】优惠比例
                            if (isTyAgent != null && isTyAgent == true) {
                                HighTyAgentPrice agentPrice = tyAgentPriceService.getDetail(2, MapUtils.getLong(map, "id"), MapUtils.getString(map, "oil_no"));
                                if (agentPrice != null) {
                                    // 优惠比例 / 100 = 最终优惠比例
                                    BigDecimal priceRate = agentPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                                    // 油品国标价 * 最终优惠比例
                                    map.put("price_vip", new BigDecimal(MapUtils.getString(map, "price_gun")).multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                                }
                            }
                        }
                    }
                }

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

    @RequestMapping(value="/oilPriceCompute",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "油价计算")
    public ResponseData oilPriceCompute(@RequestParam(name = "price", required = true) BigDecimal price,
                                        @RequestParam(name = "goodsId", required = true) Long goodsId,
                                        @RequestParam(name = "oilNo", required = true) String oilNo,
                                        @RequestParam(name = "isTyAgent", required = false) Boolean isTyAgent) {
        try {
            BigDecimal discount = new BigDecimal("1");
            // 查询是否配置了【油站的】优惠比例
            HighTyAgentPrice tyAgentPrice = tyAgentPriceService.getDetail(1, goodsId, oilNo);
            if (tyAgentPrice != null) {
                discount = tyAgentPrice.getPriceRate();
            } else {
                // 查询是否配置了【油品】优惠比例
                HighGasDiscountOilPrice gasDiscountOilPrice = gasDiscountOilPriceService.getDetailByOilNo(oilNo);
                if (gasDiscountOilPrice != null) {
                    discount = gasDiscountOilPrice.getPriceRate();
                }
            }

            if (isTyAgent != null && isTyAgent.equals(true)) {
                // 价格
                HighTyAgentPrice priceRate = tyAgentPriceService.getDetail(2, goodsId, oilNo);
                if (priceRate == null) {
                    discount = gasDiscountOilPriceService.getDetailByOilNo(oilNo).getPriceRate();
                } else {
                    discount = priceRate.getPriceRate();
                }
            }
            return ResponseMsgUtil.success(price.multiply(discount.divide(new BigDecimal("100"))).setScale(2,BigDecimal.ROUND_HALF_UP));
        } catch (Exception e) {
            log.error("HighGasController -> oilPriceCompute() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/oilPriceDiscountCompute",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "油价优惠计算")
    public ResponseData oilPriceDiscountCompute(@RequestParam(name = "price", required = true) BigDecimal price,
                                        @RequestParam(name = "goodsId", required = true) Long goodsId,
                                        @RequestParam(name = "oilNo", required = true) String oilNo,
                                        @RequestParam(name = "isTyAgent", required = false) Boolean isTyAgent) {
        try {

            return ResponseMsgUtil.success(gasDiscountOilPriceService.oilPriceDiscountCompute(price,goodsId,oilNo,isTyAgent));

        } catch (Exception e) {
            log.error("HighGasController -> oilPriceDiscountCompute() 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 = false) String longitude,
                                               @RequestParam(name = "latitude", required = false) String latitude,
                                               @RequestParam(name = "isTyAgent", required = false) Boolean isTyAgent) {
        try {

            // 商户门店
            HighMerchantStoreModel store = merchantStoreService.getMerchantStoreByKey(storeKey);
            if (store == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到加油站");
            }
            if (!store.getType().equals(1)) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到加油站");
            }
            // 来源类型  1：平台自建   2：团油
            if (store.getSourceType().equals(MerchantStoreSourceType.type1.getNumber())
                    || store.getSourceType().equals(MerchantStoreSourceType.type3.getNumber())
                    || store.getSourceType().equals(MerchantStoreSourceType.type4.getNumber())) {
                Map<String, Object> param = new HashMap<>();
                param.put("provinceName", null);
                param.put("provinceCode", null);
                param.put("cityCode", null);
                param.put("cityName", null);
                param.put("countyCode", null);
                param.put("countyName", null);
                param.put("goodsId", store.getId());
                param.put("gasId", store.getStoreKey());
                param.put("gasName", store.getStoreName());
                param.put("gasAddress", store.getAddress());

                if (store.getSourceType().equals(1)) {
                    param.put("gasLogoBig", CommonSysConst.getSysConfig().getHsgDomainName()+"/filesystem/"+store.getStoreLogo());
                    param.put("gasLogoSmall", CommonSysConst.getSysConfig().getHsgDomainName()+"/filesystem/"+store.getStoreLogo());
                } else {
                    param.put("gasLogoBig", store.getStoreLogo());
                    param.put("gasLogoSmall", store.getStoreLogo());
                }
                param.put("gasAddressLatitude", store.getLatitude());
                param.put("gasAddressLongitude", store.getLongitude());

                if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)) {
                    // 距离
                    double distance = CoordCommonUtil.getDistance(Double.valueOf(param.get("gasAddressLatitude").toString()), Double.valueOf(param.get("gasAddressLongitude").toString()), Double.valueOf(latitude), Double.valueOf(longitude));
                    param.put("distance", Math.round(distance/100d)/10d);
                } else {
                    param.put("distance", null);
                }

                // 查询油枪
                List<Map<String, Object>> gasGunMapList = new ArrayList<>();
                Map<String, Object> gasGunMap;
                List<HighGasOilGunNo> oilGunNoList = gasOilGunNoService.getGunNoListByStoreId(store.getId());
                for (HighGasOilGunNo oilGunNo : oilGunNoList) {
                    gasGunMap = new HashMap<>();
                    gasGunMap.put("gunNo", oilGunNo.getGunNo());
                    gasGunMap.put("oilNo", oilGunNo.getOilNo());
                    gasGunMap.put("oilNoName", oilGunNo.getOilNoName());
                    gasGunMapList.add(gasGunMap);
                }
                param.put("gasGunList", gasGunMapList);
                
                // 查询油品
                List<Map<String, Object>> oilPriceMapList = new ArrayList<>();
                Map<String, Object> oilPriceMap;

                List<HighGasOilPrice> oilPriceList = gasOilPriceService.getGasOilPriceByStore(store.getId());
                for (HighGasOilPrice oilPrice : oilPriceList) {
                    oilPriceMap = new HashMap<>();
                    oilPriceMap.put("oilType", oilPrice.getOilType());
                    oilPriceMap.put("oilTypeName", oilPrice.getOilTypeName());
                    oilPriceMap.put("oilNo", oilPrice.getOilNo());
                    oilPriceMap.put("oilNoName", oilPrice.getOilNoName());
                    oilPriceMap.put("priceVip", oilPrice.getPriceVip());
                    oilPriceMap.put("priceGun", oilPrice.getPriceGun());
                    oilPriceMap.put("priceOfficial", oilPrice.getPriceOfficial());

                    // 查询是否配置了【油站的】优惠比例
                    HighTyAgentPrice tyAgentPrice = tyAgentPriceService.getDetail(1, store.getId(), oilPrice.getOilNo().toString());
                    if (tyAgentPrice != null) {
                        // 优惠比例 / 100 = 最终优惠比例
                        BigDecimal priceRate = tyAgentPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                        // 油枪价 - 优惠幅度
                        BigDecimal price = oilPrice.getPriceGun().subtract(oilPrice.getPreferentialMargin());
                        // (油枪价 - 优惠幅度) * 系统折扣
                        oilPriceMap.put("priceVip", price.multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));

                    } else {
                        // 查询是否配置了【油品】优惠比例
                        HighGasDiscountOilPrice gasDiscountOilPrice = gasDiscountOilPriceService.getDetailByOilNo(oilPrice.getOilNo().toString());
                        if (gasDiscountOilPrice != null) {
                            // 优惠比例 / 100 = 最终优惠比例
                            BigDecimal priceRate = gasDiscountOilPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                            // 油枪价 - 优惠幅度
                            BigDecimal price = oilPrice.getPriceGun().subtract(oilPrice.getPreferentialMargin());
                            // (油枪价 - 优惠幅度) * 系统折扣
                            oilPriceMap.put("priceVip", price.multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                    }

                    // 查询是否配置了【代理商】优惠比例
                    if (isTyAgent != null && isTyAgent == true) {
                        HighTyAgentPrice agentPrice = tyAgentPriceService.getDetail(2, store.getId(), oilPrice.getOilNo().toString());
                        if (agentPrice != null) {
                            // 优惠比例 / 100 = 最终优惠比例
                            BigDecimal priceRate = agentPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                            // 油枪价 - 优惠幅度
                            BigDecimal price = oilPrice.getPriceGun().subtract(oilPrice.getPreferentialMargin());
                            // (油枪价 - 优惠幅度) * 系统折扣
                            oilPriceMap.put("priceVip", price.multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                    }

                    oilPriceMapList.add(oilPriceMap);
                }
                param.put("oilPriceList", oilPriceMapList);

                return ResponseMsgUtil.success(param);

            } else if (store.getSourceType().equals(store.getSourceType().equals(MerchantStoreSourceType.type2.getNumber())))  {
                JSONObject jsonObject = TuanYouConfig.queryGasInfoByGasId(storeKey);
                if (jsonObject != null && jsonObject.getString("code").equals("200")) {
                    JSONObject result = jsonObject.getJSONObject("result");
                    result.put("goodsId", store.getId());

                    // 原始油品价格
                    JSONArray originalOilPriceList = result.getJSONArray("oilPriceList");

                    // 新油品价格
                    JSONArray newOilPriceList = new JSONArray();

                    // 处理油品价格
                    for (Object oilPriceObject : originalOilPriceList) {
                        JSONObject price = JSON.parseObject(JSONObject.toJSONString(oilPriceObject), JSONObject.class);

                        // 查询油站油品状态
                        HighGasOilPrice oilNo = highGasOilPriceService.getGasOilPriceByStoreAndOilNo(store.getId(), price.getInteger("oilNo"));
                        if (oilNo != null && !oilNo.getStatus().equals(GasOilPriceStatusEnum.status1.getStatus())) {
                            continue;
                        }
                        // 查询是否配置了【油站的】优惠比例
                        HighTyAgentPrice tyAgentPrice = tyAgentPriceService.getDetail(1, store.getId(), price.getString("oilNo"));
                        if (tyAgentPrice != null) {
                            // 优惠比例 / 100 = 最终优惠比例
                            BigDecimal priceRate = tyAgentPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                            // 油品国标价 * 最终优惠比例
                            price.put("priceVip", price.getBigDecimal("priceGun").multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                        } else {
                            // 查询是否配置了【油品】优惠比例
                            HighGasDiscountOilPrice gasDiscountOilPrice = gasDiscountOilPriceService.getDetailByOilNo(price.getString("oilNo"));
                            if (gasDiscountOilPrice != null) {
                                // 优惠比例 / 100 = 最终优惠比例
                                BigDecimal priceRate = gasDiscountOilPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                                // 油品国标价 * 最终优惠比例
                                price.put("priceVip", price.getBigDecimal("priceGun").multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                            }
                        }

                        // 查询是否配置了【代理商油站】优惠比例
                        if (isTyAgent != null && isTyAgent == true) {
                            HighTyAgentPrice agentPrice = tyAgentPriceService.getDetail(2, store.getId(), price.getString("oilNo"));
                            if (agentPrice != null) {
                                // 优惠比例 / 100 = 最终优惠比例
                                BigDecimal priceRate = agentPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                                // 油品国标价 * 最终优惠比例
                                price.put("priceVip", price.getBigDecimal("priceGun").multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                            }
                        }
                        newOilPriceList.add(price);
                    }
                    result.put("oilPriceList", newOilPriceList);

                    if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)) {
                        // 距离
                        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);
                    } else {
                        result.put("distance", null);
                    }
                    return ResponseMsgUtil.success(jsonObject.get("result"));
                }
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, jsonObject.getString("message"));
            }

            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到加油站");

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

    @RequestMapping(value="/recentGasStation",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询最近的油站")
    public ResponseData recentGasStation(@RequestParam(name = "longitude", required = true) String longitude,
                                         @RequestParam(name = "latitude", required = true) String latitude,
                                         @RequestParam(name = "isTyAgent", required = false) Boolean isTyAgent) {
        try {
            if (StringUtils.isBlank(latitude) || StringUtils.isBlank(latitude)) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            Map<String, Object> station = gasOilPriceService.recentGasStation(longitude, latitude);
            if (station == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "附近没有加油站哦");
            }
            // 商户门店
            HighMerchantStoreModel store = merchantStoreService.getMerchantStoreByKey(MapUtils.getString(station, "storeKey"));
            if (store == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到加油站");
            }
            if (!store.getType().equals(1)) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到加油站");
            }
            if (store.getSourceType() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知来源的加油站");
            }
            // 来源类型  1：平台自建   2：团油
            if (store.getSourceType().equals(MerchantStoreSourceType.type1.getNumber())
                    || store.getSourceType().equals(MerchantStoreSourceType.type3.getNumber())
                    || store.getSourceType().equals(MerchantStoreSourceType.type4.getNumber()) ) {
                Map<String, Object> param = new HashMap<>();
                param.put("provinceName", null);
                param.put("provinceCode", null);
                param.put("cityCode", null);
                param.put("cityName", null);
                param.put("countyCode", null);
                param.put("countyName", null);
                param.put("goodsId", store.getId());
                param.put("gasId", store.getStoreKey());
                param.put("gasName", store.getStoreName());
                param.put("gasAddress", store.getAddress());
                if (store.getSourceType().equals(1)) {
                    param.put("gasLogoBig", CommonSysConst.getSysConfig().getHsgDomainName()+"/filesystem/"+store.getStoreLogo());
                    param.put("gasLogoSmall", CommonSysConst.getSysConfig().getHsgDomainName()+"/filesystem/"+store.getStoreLogo());
                } else {
                    param.put("gasLogoBig", store.getStoreLogo());
                    param.put("gasLogoSmall", store.getStoreLogo());
                }
                param.put("gasAddressLatitude", store.getLatitude());
                param.put("gasAddressLongitude", store.getLongitude());
                // 距离
                double distance = CoordCommonUtil.getDistance(Double.valueOf(param.get("gasAddressLatitude").toString()), Double.valueOf(param.get("gasAddressLongitude").toString()), Double.valueOf(latitude), Double.valueOf(longitude));
                param.put("distance", Math.round(distance/100d)/10d);

                // 查询油枪
                List<Map<String, Object>> gasGunMapList = new ArrayList<>();
                Map<String, Object> gasGunMap;
                List<HighGasOilGunNo> oilGunNoList = gasOilGunNoService.getGunNoListByStoreId(store.getId());
                for (HighGasOilGunNo oilGunNo : oilGunNoList) {
                    gasGunMap = new HashMap<>();
                    gasGunMap.put("gunNo", oilGunNo.getGunNo());
                    gasGunMap.put("oilNo", oilGunNo.getOilNo());
                    gasGunMap.put("oilNoName", oilGunNo.getOilNoName());
                    gasGunMapList.add(gasGunMap);
                }
                param.put("gasGunList", gasGunMapList);

                // 查询油品
                List<Map<String, Object>> oilPriceMapList = new ArrayList<>();
                Map<String, Object> oilPriceMap;

                List<HighGasOilPrice> oilPriceList = gasOilPriceService.getGasOilPriceByStore(store.getId());
                for (HighGasOilPrice oilPrice : oilPriceList) {
                    oilPriceMap = new HashMap<>();
                    oilPriceMap.put("oilType", oilPrice.getOilType());
                    oilPriceMap.put("oilTypeName", oilPrice.getOilTypeName());
                    oilPriceMap.put("oilNo", oilPrice.getOilNo());
                    oilPriceMap.put("oilNoName", oilPrice.getOilNoName());
                    oilPriceMap.put("priceVip", oilPrice.getPriceVip());
                    oilPriceMap.put("priceGun", oilPrice.getPriceGun());
                    oilPriceMap.put("priceOfficial", oilPrice.getPriceOfficial());

                    // 查询是否配置了【油站的】优惠比例
                    HighTyAgentPrice tyAgentPrice = tyAgentPriceService.getDetail(1, store.getId(), oilPrice.getOilNo().toString());
                    if (tyAgentPrice != null) {
                        // 优惠比例 / 100 = 最终优惠比例
                        BigDecimal priceRate = tyAgentPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                        // 油枪价 - 优惠幅度
                        BigDecimal price = oilPrice.getPriceGun().subtract(oilPrice.getPreferentialMargin());
                        // (油枪价 - 优惠幅度) * 系统折扣
                        oilPriceMap.put("priceVip", price.multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));

                    } else {
                        // 查询是否配置了【油品】优惠比例
                        HighGasDiscountOilPrice gasDiscountOilPrice = gasDiscountOilPriceService.getDetailByOilNo(oilPrice.getOilNo().toString());
                        if (gasDiscountOilPrice != null) {
                            // 优惠比例 / 100 = 最终优惠比例
                            BigDecimal priceRate = gasDiscountOilPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                            // 油枪价 - 优惠幅度
                            BigDecimal price = oilPrice.getPriceGun().subtract(oilPrice.getPreferentialMargin());
                            // (油枪价 - 优惠幅度) * 系统折扣
                            oilPriceMap.put("priceVip", price.multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                    }

                    // 查询是否配置了【代理商】优惠比例
                    if (isTyAgent != null && isTyAgent == true) {
                        HighTyAgentPrice agentPrice = tyAgentPriceService.getDetail(2, store.getId(), oilPrice.getOilNo().toString());
                        if (agentPrice != null) {
                            // 优惠比例 / 100 = 最终优惠比例
                            BigDecimal priceRate = agentPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                            // 油枪价 - 优惠幅度
                            BigDecimal price = oilPrice.getPriceGun().subtract(oilPrice.getPreferentialMargin());
                            // (油枪价 - 优惠幅度) * 系统折扣
                            oilPriceMap.put("priceVip", price.multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                    }

                    oilPriceMapList.add(oilPriceMap);
                }
                param.put("oilPriceList", oilPriceMapList);

                return ResponseMsgUtil.success(param);

            } else if (store.getSourceType().equals(MerchantStoreSourceType.type2.getNumber()))  {
                JSONObject jsonObject = TuanYouConfig.queryGasInfoByGasId(MapUtils.getString(station, "storeKey"));
                if (jsonObject != null && jsonObject.getString("code").equals("200")) {
                    JSONObject result = jsonObject.getJSONObject("result");
                    result.put("goodsId", store.getId());

                    // 原始油品价格
                    JSONArray originalOilPriceList = result.getJSONArray("oilPriceList");

                    // 新油品价格
                    JSONArray newOilPriceList = new JSONArray();

                    // 处理油品价格
                    for (Object oilPriceObject : originalOilPriceList) {
                        JSONObject price = JSON.parseObject(JSONObject.toJSONString(oilPriceObject), JSONObject.class);

                        // 查询油站油品状态
                        HighGasOilPrice oilNo = highGasOilPriceService.getGasOilPriceByStoreAndOilNo(store.getId(), price.getInteger("oilNo"));
                        if (oilNo != null && !oilNo.getStatus().equals(GasOilPriceStatusEnum.status1.getStatus())) {
                            continue;
                        }
                        // 查询是否配置了【油站的】优惠比例
                        HighTyAgentPrice tyAgentPrice = tyAgentPriceService.getDetail(1, store.getId(), price.getString("oilNo"));
                        if (tyAgentPrice != null) {
                            // 优惠比例 / 100 = 最终优惠比例
                            BigDecimal priceRate = tyAgentPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                            // 油品国标价 * 最终优惠比例
                            price.put("priceVip", price.getBigDecimal("priceGun").multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                        } else {
                            // 查询是否配置了【油品】优惠比例
                            HighGasDiscountOilPrice gasDiscountOilPrice = gasDiscountOilPriceService.getDetailByOilNo(price.getString("oilNo"));
                            if (gasDiscountOilPrice != null) {
                                // 优惠比例 / 100 = 最终优惠比例
                                BigDecimal priceRate = gasDiscountOilPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                                // 油品国标价 * 最终优惠比例
                                price.put("priceVip", price.getBigDecimal("priceGun").multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                            }
                        }

                        // 查询是否配置了【代理商油站】优惠比例
                        if (isTyAgent != null && isTyAgent == true) {
                            HighTyAgentPrice agentPrice = tyAgentPriceService.getDetail(2, store.getId(), price.getString("oilNo"));
                            if (agentPrice != null) {
                                // 优惠比例 / 100 = 最终优惠比例
                                BigDecimal priceRate = agentPrice.getPriceRate().divide(new BigDecimal("100").setScale(2, BigDecimal.ROUND_DOWN));
                                // 油品国标价 * 最终优惠比例
                                price.put("priceVip", price.getBigDecimal("priceGun").multiply(priceRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                            }
                        }
                        newOilPriceList.add(price);
                    }
                    result.put("oilPriceList", newOilPriceList);

                    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, jsonObject.getString("message"));
            }

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

}
