package com.cweb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cweb.config.SysConfig;
import com.cweb.config.SysConst;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.CoordCommonUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.CommonSysConst;
import com.hai.config.QianZhuConfig;
import com.hai.config.ThirdProductConfig;
import com.hai.entity.*;
import com.hai.enum_type.ProductImgEnum;
import com.hai.model.*;
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.apache.logging.log4j.spi.CopyOnWrite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.ls.LSException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;


@Controller
@RequestMapping(value = "/highThirdParty")
@Api(value = "订单接口")
public class HighThirdPartyController {

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

    @Resource
    private ApiProductService apiProductService;

    @Resource
    private ThirdProductConfig thirdProductConfig;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private BsCompanyService bsCompanyService;

    @Resource
    private CommonService commonService;

    @Autowired
    private UserCenter userCenter;

    @Resource
    private ApiMemberProductService apiMemberProductService;


    @RequestMapping(value = "/getAllCity", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询所有城市")
    public ResponseData getAllCity(@RequestParam(name = "cityName", required = false) String cityName) {
        try {
            return ResponseMsgUtil.success(apiProductService.getAllCity(cityName));

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

    @RequestMapping(value = "/getStarbucksProducts", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询星巴克商品")
    public ResponseData getStarbucksProducts(@RequestParam(name = "name", required = false) String name,
                                             @RequestParam(value = "regionId", required = true) String regionId) {
        try {

            SecRegion region = commonService.getParentByRegion(Long.valueOf(regionId));
            BigDecimal productDiscount = null;
            if (region != null) {
                BsCompany bsCompany = bsCompanyService.selectCompanyByRegion(region.getRegionId().toString());
                productDiscount = thirdProductConfig.getProductConfigNum(1, bsCompany.getId());
            }

            if (productDiscount == null) {
                log.error("getRechargeProduct error!", "查询失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前地区未配置产品");
            }

            List<String> CategoryNameList = apiProductService.getCategoryName();

            List<ApiStarbucksProducts> starbucksProductsList = new ArrayList<>();
            int i = 9999;
            for (String s : CategoryNameList) {
                i++;
                ApiStarbucksProducts starbucksProducts = new ApiStarbucksProducts();
                Map<String, Object> map = new HashMap<>();
                map.put("name", name);
                map.put("categoryName", s);
                List<ApiStarbucksProducts> list = apiProductService.getStarbucksProducts(map);
                for (ApiStarbucksProducts apiStarbucksProducts : list) {
                    apiStarbucksProducts.setExt1(String.valueOf(i));

                    BigDecimal salesVentiPrice = apiStarbucksProducts.getSalesVentiPrice().add(apiStarbucksProducts.getMarketVentiPrice().multiply(productDiscount.divide(new BigDecimal(100)))).setScale(2, RoundingMode.HALF_UP);
                    BigDecimal salesTallPrice = apiStarbucksProducts.getSalesTallPrice().add(apiStarbucksProducts.getMarketTallPrice().multiply(productDiscount.divide(new BigDecimal(100)))).setScale(2, RoundingMode.HALF_UP);
                    BigDecimal salesGrandePrice = apiStarbucksProducts.getSalesGrandePrice().add(apiStarbucksProducts.getMarketGrandePrice().multiply(productDiscount.divide(new BigDecimal(100)))).setScale(2, RoundingMode.HALF_UP);

                    if (salesVentiPrice.compareTo(apiStarbucksProducts.getMarketVentiPrice()) > 0) {
                        salesVentiPrice = apiStarbucksProducts.getMarketVentiPrice();
                    }
                    if (salesTallPrice.compareTo(apiStarbucksProducts.getMarketTallPrice()) > 0) {
                        salesTallPrice = apiStarbucksProducts.getMarketTallPrice();
                    }
                    if (salesGrandePrice.compareTo(apiStarbucksProducts.getMarketGrandePrice()) > 0) {
                        salesGrandePrice = apiStarbucksProducts.getMarketGrandePrice();
                    }
                    apiStarbucksProducts.setSalesVentiPrice(salesVentiPrice);
                    apiStarbucksProducts.setSalesTallPrice(salesTallPrice);
                    apiStarbucksProducts.setSalesGrandePrice(salesGrandePrice);
                    starbucksProductsList.add(apiStarbucksProducts);
                }
                starbucksProducts.setName(s);
                starbucksProducts.setExt2(SysConst.getSysConfig().getImgUrl() + ProductImgEnum.getNameByImgUrl(s));
                starbucksProducts.setId((long) i);
                starbucksProductsList.add(starbucksProducts);
            }

            return ResponseMsgUtil.success(starbucksProductsList);

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

    @RequestMapping(value = "/getStarbucksStore", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询星巴克门店")
    public ResponseData getStarbucksStore(@RequestParam(name = "lat", required = true) String lat,
                                          @RequestParam(name = "lon", required = true) String lon) {
        try {
            JSONObject jsonObject = QianZhuConfig.getStarbucksStore(lat, lon);
            if (jsonObject.getBoolean("success")) {
                return ResponseMsgUtil.success(jsonObject.getJSONArray("data"));
            } else {
                log.error("getRechargeProduct error!", "查询失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, jsonObject.getString("message"));
            }

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


    @RequestMapping(value = "/getKfcStoresList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询肯德基门店")
    public ResponseData getKfcStoresList(@RequestParam(name = "storeName", required = false) String storeName,
                                         @RequestParam(name = "cityCode", required = false) String cityCode,
                                         @RequestParam(name = "cityName", required = false) String cityName,
                                         @RequestParam(name = "lat", required = true) String lat,
                                         @RequestParam(name = "lon", required = true) String lon) {
        try {

            Map<String, Object> map = new HashMap<>();
            map.put("storeName", storeName);
            map.put("cityCode", cityCode);
            map.put("cityName", cityName);

            List<ApiKfcStores> list = apiProductService.getKfcStoresList(map);

            if (StringUtils.isNotBlank(lat)) {
                for (ApiKfcStores stores : list) {
                    double distance = CoordCommonUtil.getDistance(Double.valueOf(stores.getLat()), Double.valueOf(stores.getLon()), Double.valueOf(lat), Double.valueOf(lon));
                    stores.setDistance(String.valueOf(Math.round(distance / 100d) / 10d));
                }
            }

            return ResponseMsgUtil.success(list.stream().sorted(Comparator.comparing(ApiKfcStores::getDistance)).collect(Collectors.toList()));

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

    @RequestMapping(value = "/listByStoreCode", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询肯德基门店菜单")
    public ResponseData listByStoreCode(@RequestParam(name = "storeCode", required = false) String storeCode, @RequestParam(value = "regionId", required = true) String regionId) {
        try {

            JSONObject jsonObject = QianZhuConfig.listByStoreCode(storeCode);

            JSONArray array = jsonObject.getJSONArray("data");

            if (array == null) {
                log.error("addOrder error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未查询到任何门店");
            }

            BigDecimal productDiscount = null;
            SecRegion region = commonService.getParentByRegion(Long.valueOf(regionId));
            if (region != null) {
                BsCompany bsCompany = bsCompanyService.selectCompanyByRegion(region.getRegionId().toString());
                productDiscount = thirdProductConfig.getProductConfigNum(2, bsCompany.getId());
            }

            if (productDiscount == null) {
                log.error("getRechargeProduct error!", "查询失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前地区未配置产品");
            }
            int i = 0;

            for (Object data : array) {
                JSONObject dataObject = (JSONObject) data;
                i++;
                dataObject.put("kfcId", i);
                if (dataObject.getJSONArray("products") != null) {
                    for (Object products : dataObject.getJSONArray("products")) {
                        JSONObject productsObject = (JSONObject) products;
                        BigDecimal productsPrice = productsObject.getBigDecimal("price");

                        BigDecimal salePriceF = productsPrice.add(productsObject.getBigDecimal("originalPrice").multiply(productDiscount).divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_UP);
                        if (salePriceF.compareTo(productsObject.getBigDecimal("originalPrice")) > 0) {
                            salePriceF = productsObject.getBigDecimal("originalPrice");
                        }
                        productsObject.put("salePrice", salePriceF);

                        if (productsObject.getJSONArray("specGroups") != null) {
                            for (Object specGroups : productsObject.getJSONArray("specGroups")) {
                                JSONObject specGroupsObject = (JSONObject) specGroups;
                                BigDecimal specGroupsPrice = specGroupsObject.getBigDecimal("price");
                                BigDecimal salePrice = specGroupsPrice.add(specGroupsObject.getBigDecimal("originalPrice").multiply(productDiscount).divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_UP);
                                if (salePrice.compareTo(specGroupsObject.getBigDecimal("originalPrice")) > 0) {
                                    salePrice = specGroupsObject.getBigDecimal("originalPrice");
                                }
                                specGroupsObject.put("salePrice", salePrice);
                            }
                        }
                    }
                }
            }

            if (jsonObject.getBoolean("success")) {
                return ResponseMsgUtil.success(array);
            } else {
                log.error("getRechargeProduct error!", "查询失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, jsonObject.getString("message"));
            }

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

    @RequestMapping(value = "/getThirdPartyByDetail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询第三方产品详情")
    public ResponseData getThirdPartyByDetail(@RequestParam(name = "platformId", required = true) Integer platformId,
                                              @RequestParam(name = "productType", required = true) Integer productType,
                                              @RequestParam(name = "regionId", required = true) String regionId) {
        try {

            SecRegion region = commonService.getParentByRegion(Long.valueOf(regionId));

            if (region == null) {
                log.error("getRechargeProduct error!", "查询失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, regionId + "当前地区未配置产品");
            }

            BsCompany bsCompany = bsCompanyService.selectCompanyByRegion(region.getRegionId().toString());

            return ResponseMsgUtil.success(thirdProductConfig.getThirdPartyByDetail(platformId , productType , bsCompany.getId()));

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


    @RequestMapping(value = "/addOrder", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "增加订单")
    public ResponseData addOrder(@RequestBody JSONObject object, HttpServletRequest request) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            System.out.println("======================================================" + object);

            if (StringUtils.isBlank(object.getString("customerMobile")) ||
                    StringUtils.isBlank(object.getString("regionId")) ||
                    object.getInteger("productType") == null ||
                    object.getInteger("platformId") == null
            ) {
                log.error("addOrder error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            SecRegion region = commonService.getParentByRegion(object.getLong("regionId"));
            if (region != null) {
                BsCompany bsCompany = bsCompanyService.selectCompanyByRegion(region.getRegionId().toString());
                object.put("companyId", String.valueOf(bsCompany.getId()));
            }

            object.put("userId", userInfoModel.getHighUser().getId());
            object.put("mchId", request.getHeader("mchId"));

            return ResponseMsgUtil.success(highOrderService.insertThirdProduct(object));

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



    @RequestMapping(value = "/getThirdOrderByOrderId", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询第三方订单详情")
    public ResponseData getThirdOrderByOrderId(@RequestParam(name = "orderId", required = true) Long orderId) {
        try {


            HighOrder order = highOrderService.getOrderById(orderId);

            JSONObject object;
            ThirdPartyModel partyModel = new ThirdPartyModel();
            List<Map<String, Object>> list = new ArrayList<>();
            // 实际支付金额
            BigDecimal orderPayPrice = new BigDecimal(0);


            if (order.getHighChildOrderList().get(0).getGoodsType() == 4) {

                object = QianZhuConfig.getKfcOrderByOrderNo(order.getOrderNo());
                if (object.getBoolean("success")) {
                    BeanUtils.copyProperties(order, partyModel);
                    partyModel.setCode(object.getJSONObject("data").getString("ticket"));
                    partyModel.setThirdOrderStatus(object.getJSONObject("data").getInteger("status"));
                    partyModel.setStatusDesc(object.getJSONObject("data").getString("statusDesc"));
                    if (object.getJSONObject("data").getString("ticket") != null) {
                        String[] s =  object.getJSONObject("data").getString("ticket").split(",");

                        for (String s1 : s) {
                            Map<String , Object> map = new HashMap<>();
                            String[] childString = s1.split("\\|");
                            map.put("code" , childString[0]);
                            map.put("phone" , childString[1]);
                            list.add(map);
                        }

                        partyModel.setList(list);
                    }
                    partyModel.setEatType(object.getJSONObject("data").getJSONObject("kfcPlaceOrder").getInteger("eatType"));
                    partyModel.setKfcOrderMobileRemark(object.getJSONObject("data").getString("kfcOrderMobileRemark"));

                } else {
                    log.error("getThirdOrderByOrderId error!", "查询失败！");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, object.getString("message"));
                }
            } else if (order.getHighChildOrderList().get(0).getGoodsType() == 9) {
                // 查询详单订单的实际
                JSONObject productDetail = thirdProductConfig.getThirdPartyByDetail(1, 1, order.getCompanyId());

                object = QianZhuConfig.starbucksOrderByOrderNo(order.getOrderNo());
                if (object.getBoolean("success")) {
                    BeanUtils.copyProperties(order, partyModel);
                    partyModel.setCode(object.getJSONObject("data").getString("ticket"));
                    partyModel.setStatusDesc(object.getJSONObject("data").getString("statusDesc"));
                    partyModel.setObject(object.getJSONObject("data"));


                    // 获取星巴克订单内容
                    JSONArray starbucksOrder = object.getJSONObject("data").getJSONArray("orderItems");

                    for (Object starbucksObject : starbucksOrder) {
                        JSONObject childObject = (JSONObject) starbucksObject;

                        // 计算利润
                        BigDecimal profitPrice = childObject.getBigDecimal("unitPrice").multiply(productDetail.getBigDecimal("priceDiscount").divide(new BigDecimal(100)));
                        BigDecimal childPrice = childObject.getBigDecimal("unitPrice").add(profitPrice).setScale(2 , RoundingMode.HALF_UP);
                        // 计算实际支付金额
                        orderPayPrice = orderPayPrice.add(childPrice);
                        childObject.put("unitPrice" , childPrice);
                        childObject.put("totalPrice" , childPrice.multiply(childObject.getBigDecimal("quantity")));

                    }
                    object.getJSONObject("data").put("paymentAmount" , orderPayPrice);

                    partyModel.setObject(object.getJSONObject("data"));

                    if (object.getJSONObject("data").getString("code") != null) {
                        String[] s =  object.getJSONObject("data").getString("code").split(",");

                        for (String s1 : s) {
                            Map<String , Object> map = new HashMap<>();
                            String[] childString = s1.split("\\|");
                            map.put("code" , childString[0]);
                            map.put("phone" , childString[1]);
                            list.add(map);
                        }

                        partyModel.setList(list);
                    }

                }else {
                    log.error("getThirdOrderByOrderId error!", "查询失败！");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, object.getString("message"));
                }
            } else if (order.getHighChildOrderList().get(0).getGoodsType() == 10) {
                BeanUtils.copyProperties(order, partyModel);
            }

            return ResponseMsgUtil.success(partyModel);
        } catch (Exception e) {
            log.error("HighUserCardController --> oilCardRefund() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/thirdCancelOrder", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "取消订单")
    public ResponseData thirdCancelOrder(@RequestParam(name = "orderId", required = true) Long orderId) {
        try {

            HighOrder order = highOrderService.getOrderById(orderId);

            if (order.getOrderStatus() == 1) {
                highOrderService.thirdCancelOrder(orderId);
            } else {
                log.error("orderToPay error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.STATUS_ERROR, "");
            }

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

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

    @RequestMapping(value = "/getMemberProducts", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询会员产品")
    public ResponseData getMemberProducts(@RequestParam(name = "name", required = false) String name,
                                          @RequestParam(value = "typeId", required = true) Integer typeId,
                                          @RequestParam(value = "brandId", required = true) Integer brandId,
                                             @RequestParam(value = "regionId", required = true) String regionId) {
        try {

            SecRegion region = commonService.getParentByRegion(Long.valueOf(regionId));
            BigDecimal productDiscount = null;
            if (region != null) {
                BsCompany bsCompany = bsCompanyService.selectCompanyByRegion(region.getRegionId().toString());
                productDiscount = thirdProductConfig.getProductConfigNum(3, bsCompany.getId());
            }

            if (productDiscount == null) {
                log.error("getRechargeProduct error!", "查询失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前地区未配置产品");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("name" , name);
            map.put("typeId" , typeId);
            map.put("brandId" , brandId);

            List<ApiMemberProduct> list = apiMemberProductService.getListApiMemberProduct(map);

            for (ApiMemberProduct memberProduct : list) {

                BigDecimal costPrice = memberProduct.getCostPrice().add(memberProduct.getPrice().multiply(productDiscount.divide(new BigDecimal(100)))).setScale(2, RoundingMode.HALF_UP);

                if (costPrice.compareTo(memberProduct.getPrice()) > 0) {
                    costPrice = memberProduct.getPrice();
                }

                memberProduct.setCostPrice(costPrice);
            }

            return ResponseMsgUtil.success(list);

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

}
