package com.v1.controller.business;

import com.alibaba.fastjson.JSONArray;
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.config.QianZhuConfig;
import com.hai.entity.ApiKfcStores;
import com.hai.entity.ApiMchProduct;
import com.hai.entity.ApiMerchants;
import com.hai.model.ResponseData;
import com.hai.openApi.config.PriceComputeConfig;
import com.hai.openApi.service.ApiMchProductService;
import com.hai.order.type.OrderProductType;
import com.hai.service.ApiIpAddressService;
import com.hai.service.ApiMerchantsService;
import com.hai.service.ApiProductService;
import com.hai.service.SecConfigService;
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.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/kfc")
@Api(value = "kfc业务")
public class KfcController {

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

    @Resource
    private ApiMerchantsService apiMerchantsService;

    @Resource
    private SecConfigService secConfigService;

    @Resource
    private ApiIpAddressService apiIpAddressService;

    @Resource
    private ApiProductService apiProductService;

    @Resource
    private PriceComputeConfig priceComputeConfig;

    @Resource
    private ApiMchProductService apiMchProductService;

    @RequestMapping(value = "/kfcStoresList", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询肯德基门店")
    public ResponseData kfcStoresList(@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 (!apiIpAddressService.validationIpAddressLegal(object.getString("merchId") , ip)) {
                log.error("getRechargeProduct error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

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

            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_TYPE2.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> mapStores = new HashMap<>();
            List<ApiKfcStores> list = apiProductService.getKfcStoresList(mapStores);

            return ResponseMsgUtil.success(list);

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


    @RequestMapping(value = "/kfcProductByStoreCode", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "根据门店编码查询KFC产品")
    public ResponseData kfcProductByStoreCode(@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 (!apiIpAddressService.validationIpAddressLegal(object.getString("merchId") , ip)) {
                log.error("getRechargeProduct error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

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

            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_TYPE2.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"));
            map.put("storeCode" , object.getString("storeCode"));

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

            JSONObject jsonObject = QianZhuConfig.listByStoreCode(object.getString("storeCode"));
            JSONArray array = jsonObject.getJSONArray("data");
            if (array == null) {
                log.error("kfcProductByStoreCode error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未查询到商品");
            }

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

            ApiMchProduct apiMchProducts = apiMchProductService.findByMap(mapProduct);


            for (Object data : array) {
                JSONObject dataObject = (JSONObject) data;
                if (dataObject.getJSONArray("products") != null) {
                    for (Object products : dataObject.getJSONArray("products")) {
                        JSONObject productsObject = (JSONObject) products;
                        productsObject.put("taxOriginalPrice" , null);
                        productsObject.put("taxOriginalTotalPrice" , null);
                        productsObject.put("price" , priceComputeConfig.computationPriceCost(apiMchProducts.getDiscount() , productsObject.getBigDecimal("originalPrice") , productsObject.getBigDecimal("price")));
                        productsObject.put("taxPrice" , null);

                        if (productsObject.getJSONArray("specGroups") != null) {
                            for (Object specGroups : productsObject.getJSONArray("specGroups")) {
                                JSONObject specGroupsObject = (JSONObject) specGroups;
                                specGroupsObject.put("taxOriginalPrice" , null);
                                specGroupsObject.put("taxOriginalTotalPrice" , null);
                                specGroupsObject.put("price" , priceComputeConfig.computationPriceCost(apiMchProducts.getDiscount() , specGroupsObject.getBigDecimal("originalPrice") , specGroupsObject.getBigDecimal("price")));
                                specGroupsObject.put("taxPrice" , null);
                            }
                        }
                    }
                }
            }

            return ResponseMsgUtil.success(array);

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