package com.cweb.controller.qianZhu;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.utils.PageUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.common.utils.StarbucksUtil;
import com.hfkj.entity.BsProductConfig;
import com.hfkj.model.ResponseData;
import com.hfkj.qianzhu.StarbucksService;
import com.hfkj.service.BsProductConfigService;
import com.hfkj.sysenum.order.OrderChildProductTypeEnum;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value="/starbucks")
@Api(value="星巴克")
public class StarbucksController {
    private static Logger log = LoggerFactory.getLogger(StarbucksController.class);
    @Resource
    private BsProductConfigService productConfigService;

    @RequestMapping(value="/starbucksStores",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询星巴克门店")
    public ResponseData starbucksStores(@RequestParam(name = "name", required = false) String name,
                                        @RequestParam(name = "lat", required = true) String lat,
                                        @RequestParam(name = "lon", required = true) String lon ,
                                        @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                        @RequestParam(value = "pageSize" , required = true) Integer pageSize) {
        try {

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

            params.put("lat", lat);
            params.put("lon", lon);
            List<JSONObject> list = StarbucksService.starbucksStoresList(params);
            if (name != null) {
                list = list.stream()
                        .filter(s -> s.getString("name").contains(name)) // 使用contains方法进行模糊查询
                        .collect(Collectors.toList()); // 将结果收集到列表中
            }

            return ResponseMsgUtil.success(PageUtil.initPageInfoObj(pageNum, list.size(), pageSize, new PageInfo<>(list)));

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

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


            List<JSONObject> products = new ArrayList<>();
            JSONObject product = new JSONObject();
            // 查询产品配置
            BsProductConfig productConfig = productConfigService.queryDetail(OrderChildProductTypeEnum.type4.getCode());
            // 查询产品
            Map<String , Object> map = new HashMap<>();
            map.put("pageIndex", 1);
            map.put("pageSize", 200);
            JSONObject object = StarbucksService.starbucksProducts(map);
            if (object.getJSONObject("data") != null) {
                JSONArray jsonArray = object.getJSONObject("data").getJSONArray("items");
                // 判断数据不为空
                if (!jsonArray.isEmpty()) {
                    for(Object obj : jsonArray) {
                        JSONObject item = (JSONObject) obj;
                        if (item.getInteger("shelfStatus") == 5) {
                            // 中杯售卖价
                            BigDecimal tallPrice = StarbucksUtil.calculatePrice(productConfig.getDiscount() , item.getBigDecimal("salesTallPrice"));

                            List<BigDecimal> priceList = new ArrayList<>();
                            List<BigDecimal> priceListOriginal = new ArrayList<>();
                            priceListOriginal.add(item.getBigDecimal("marketTallPrice"));
                            priceListOriginal.add(item.getBigDecimal("marketGrandePrice"));
                            priceListOriginal.add(item.getBigDecimal("marketVentiPrice"));
                            // 判断如果卖家 大于 原价 展示原价
                            if (tallPrice.compareTo(item.getBigDecimal("marketTallPrice")) > 0) {
                                item.put("tallPrice" , item.getBigDecimal("marketTallPrice"));
                                priceList.add(item.getBigDecimal("marketTallPrice"));
                            } else {
                                item.put("tallPrice" , tallPrice);
                                priceList.add(tallPrice);
                            }

                            // 	大杯销售价
                            BigDecimal grandePrice = StarbucksUtil.calculatePrice(productConfig.getDiscount() , item.getBigDecimal("salesGrandePrice"));
                            if (grandePrice.compareTo(item.getBigDecimal("marketGrandePrice")) > 0) {
                                item.put("grandePrice" , item.getBigDecimal("marketGrandePrice"));
                                priceList.add(item.getBigDecimal("marketGrandePrice"));
                            } else {
                                item.put("grandePrice" , grandePrice);
                                priceList.add(grandePrice);
                            }

                            // 超大杯销售价
                            BigDecimal ventiPrice = StarbucksUtil.calculatePrice(productConfig.getDiscount() , item.getBigDecimal("salesVentiPrice"));
                            if (ventiPrice.compareTo(item.getBigDecimal("marketVentiPrice")) > 0) {
                                item.put("ventiPrice" , item.getBigDecimal("marketVentiPrice"));
                                priceList.add(item.getBigDecimal("marketVentiPrice"));
                            } else {
                                item.put("ventiPrice" , ventiPrice);
                                priceList.add(ventiPrice);
                            }

                            Collections.sort(priceList);
                            Collections.sort(priceListOriginal);
                            item.put("tallPrice" ,priceList.get(0));
                            item.put("tallOriginalPrice" ,priceListOriginal.get(0));


                            List<JSONObject> dataList = new ArrayList<>();

                            JSONObject jsonObject ;
                            if (StringUtils.isNotBlank(item.getString("cupSize"))) {
                                jsonObject = new JSONObject();
                                jsonObject.put("name" , "杯型");
                                jsonObject.put("type" , 1);
                                jsonObject.put("data" , StarbucksUtil.unitLengthTransform(item.getString("cupSize") , item.getBigDecimal("tallPrice") , item.getBigDecimal("grandePrice") , item.getBigDecimal("ventiPrice")));
                                dataList.add(jsonObject);
                            }
                            if (StringUtils.isNotBlank(item.getString("temperature"))) {
                                jsonObject = new JSONObject();
                                jsonObject.put("name" , "温度");
                                jsonObject.put("type" , 2);
                                jsonObject.put("data" , item.getString("temperature").split(","));
                                dataList.add(jsonObject);
                            }
                            if (StringUtils.isNotBlank(item.getString("cream"))) {
                                jsonObject = new JSONObject();
                                jsonObject.put("name" , "奶油");
                                jsonObject.put("type" , 2);
                                jsonObject.put("data" , item.getString("cream").split(","));
                                dataList.add(jsonObject);
                            }
                            if (StringUtils.isNotBlank(item.getString("espresso"))) {
                                jsonObject = new JSONObject();
                                jsonObject.put("name" , "浓缩咖啡");
                                jsonObject.put("type" , 2);
                                jsonObject.put("data" , item.getString("espresso").split(","));
                                dataList.add(jsonObject);
                            }
                            if (StringUtils.isNotBlank(item.getString("milk"))) {
                                jsonObject = new JSONObject();
                                jsonObject.put("name" , "牛奶");
                                jsonObject.put("type" , 2);
                                jsonObject.put("data" , item.getString("milk").split(","));
                                dataList.add(jsonObject);
                            }
                            if (StringUtils.isNotBlank(item.getString("milkBubble"))) {
                                jsonObject = new JSONObject();
                                jsonObject.put("name" , "奶泡");
                                jsonObject.put("type" , 2);
                                jsonObject.put("data" , item.getString("milkBubble").split(","));
                                dataList.add(jsonObject);
                            }
                            item.put("saleData" , dataList);

                            products.add(item);

                        }
                    }
                }
            }

            Map<String, List<JSONObject>> collect = products.stream().collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("categoryName")));

            AtomicReference<Integer> i = new AtomicReference<>(1);
            List<JSONObject> countRecords = collect.keySet().stream().map(key -> {
                JSONObject goodObject = new JSONObject(true);
                goodObject.put("name",key.toUpperCase());
                goodObject.put("id",i.getAndSet(i.get() + 1));
                goodObject.put("list",collect.get(key));
                return goodObject;
            }).collect(Collectors.toList());

            product.put("products", countRecords);

            return ResponseMsgUtil.success(product);

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