package com.v1.controller.business;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.*;
import com.hai.model.ResponseData;
import com.hai.openApi.model.ApiGasOliPriceModel;
import com.hai.openApi.model.ApiMchStoreModel;
import com.hai.openApi.service.ApiMchProductService;
import com.hai.order.type.OrderProductType;
import com.hai.service.*;
import com.v1.config.ApiCommonConfig;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/refuelOnline")
@Api(value = "在线加油业务")
public class RefuelOnlineController {

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

    @Resource
    private ApiIpAddressService apiIpAddressService;

    @Resource
    private ApiMerchantsService apiMerchantsService;

    @Resource
    private SecConfigService secConfigService;

    @Resource
    private ApiMchProductService apiMchProductService;

    @Resource
    private HighMerchantStoreService highMerchantStoreService;

    @Resource
    private HighGasOilPriceService gasOilPriceService;

    @Resource
    private ApiCommonConfig apiCommonConfig;

    @RequestMapping(value = "/getStationStore", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取油站门店")
    public ResponseData getStationStore(@RequestBody JSONObject object , HttpServletRequest request ) {
        try {

            String ip = "";
            // 有的user可能使用代理，为处理用户使用代理的情况，使用x-forwarded-for
            if  (request.getHeader("x-forwarded-for") == null)  {
                ip = request.getRemoteAddr();
            }  else  {
                ip = request.getHeader("x-forwarded-for");
            }

            if (
                    StringUtils.isBlank(object.getString("merchId")) ||
                    StringUtils.isBlank(object.getString("sign"))
            ) {
                log.error("getRechargeProduct error!", "请求参数校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR);
            }

            if (!apiIpAddressService.validationIpAddressLegal(object.getString("merchId") , ip)) {
                log.error("getRechargeProduct error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

            ApiMerchants apiMerchants = apiMerchantsService.findByMchId(object.getString("merchId"));

            if (apiMerchants == null) {
                log.error("getRechargeProduct error!", "帐户号错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }

            if (!secConfigService.isConfig(OrderProductType.PRODUCT_TYPE6.getApiCode(), object.getString("merchId"))) {
                log.error("getAllCities error!", "当前帐户无权限查询！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOT_AUTHORIZED, "");
            }

            Map<String , Object> map = new HashMap<>();
            map.put("apiKey" , apiMerchants.getApiKey());
            map.put("merchId" , object.getString("merchId"));

            if (!secConfigService.isSignVerify(map , object.getString("sign"))) {
                log.error("getRechargeProduct error!", "签名校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SIGN_VERIFY);
            }

            Map<String, Object> mapProduct = new HashMap<>();
            mapProduct.put("mchId" , object.getString("merchId"));
            mapProduct.put("productType" , OrderProductType.PRODUCT_TYPE6.getNumber());

            List<ApiMchProduct> apiMchProducts = apiMchProductService.getListMchProduct(mapProduct);

            Map<String, Object> mapMerchant = new HashMap<>();;
            Map<Long, BigDecimal> discountMap = new HashMap<>();
            List<HighMerchantStore> merchantStores = new ArrayList<>();

            for (ApiMchProduct mchProduct : apiMchProducts) {
                mapMerchant.put("merchantId" , mchProduct.getMerchantId());
                discountMap.put(mchProduct.getMerchantId() , mchProduct.getDiscount());
                merchantStores.addAll(highMerchantStoreService.getMerchantStoreList(mapMerchant));
            }

            List<ApiMchStoreModel> apiMchStoreModels = new ArrayList<>();

            for (HighMerchantStore merchantStore : merchantStores) {
                ApiMchStoreModel apiMchStoreModel =  new ApiMchStoreModel();
                apiMchStoreModel.setAddress(merchantStore.getAddress());
                apiMchStoreModel.setStoreCode(merchantStore.getId().toString());
                apiMchStoreModel.setLatitude(merchantStore.getLatitude());
                apiMchStoreModel.setLongitude(merchantStore.getLongitude());
                apiMchStoreModel.setStoreName(merchantStore.getStoreName());
                apiMchStoreModel.setRegionName(merchantStore.getRegionName());

                List<HighGasOilPrice> gasOilPrices = gasOilPriceService.getGasOilPriceByStore(merchantStore.getId());


                List<ApiGasOliPriceModel> list = new ArrayList<>();

                for (HighGasOilPrice gasOilPrice : gasOilPrices) {
                    ApiGasOliPriceModel gasOliPriceModel = new ApiGasOliPriceModel();
                    gasOliPriceModel.setPriceCost(apiCommonConfig.computationPriceCost(discountMap.get(merchantStore.getMerchantId()), gasOilPrice.getPriceGun()));
                    gasOliPriceModel.setPriceGun(gasOilPrice.getPriceGun());
                    gasOliPriceModel.setPriceOfficial(gasOilPrice.getPriceOfficial());
                    gasOliPriceModel.setOilNo(gasOilPrice.getOilNo());
                    gasOliPriceModel.setOilNoName(gasOilPrice.getOilNoName());
                    gasOliPriceModel.setOilType(gasOilPrice.getOilType());
                    gasOliPriceModel.setOilTypeName(gasOilPrice.getOilTypeName());
                    gasOliPriceModel.setGasOliNo(apiCommonConfig.assemblyGasOilGunNo(gasOilPrice.getId()));
                    list.add(gasOliPriceModel);

                }
                apiMchStoreModel.setApiGasOliPriceModels(list);
                apiMchStoreModels.add(apiMchStoreModel);
            }

            return ResponseMsgUtil.success(apiMchStoreModels);

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

}
