package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserSessionObject;
import com.hfkj.service.BsOilPriceAdjustDateService;
import com.hfkj.service.BsOilPriceAdjustService;
import com.hfkj.service.CommonService;
import com.hfkj.service.discount.BsDiscountService;
import com.hfkj.service.quiz.BsOilPriceQuizRewardService;
import com.hfkj.service.quiz.BsOilPriceQuizUserService;
import com.hfkj.sysenum.OilPriceAdjustDateResultEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
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.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @className: BsOilPriceQuizController
 * @author: HuRui
 * @date: 2025/11/18
 **/
@Controller
@RequestMapping(value = "/oilPriceQuiz")
@Api(value = "油价竞猜")
public class BsOilPriceQuizController {
    private static Logger log = LoggerFactory.getLogger(BsOilPriceQuizController.class);
    @Resource
    private BsOilPriceQuizUserService oilPriceQuizUserService;
    @Resource
    private BsOilPriceAdjustService oilPriceAdjustService;
    @Resource
    private BsOilPriceAdjustDateService oilPriceAdjustDateService;
    @Resource
    private BsOilPriceQuizRewardService oilPriceQuizRewardService;
    @Resource
    private CommonService commonService;
    @Resource
    private UserCenter userCenter;

    @RequestMapping(value = "/queryOilPriceInfo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油价信息")
    public ResponseData queryOilPriceInfo(@RequestParam(name = "regionId", required = true) Long regionId) {
        try {
            // 查询地区
            SecRegion area = commonService.getRegionsById(regionId);
            if (area == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到地区数据");
            }
            // 查询地区
            SecRegion city = commonService.getRegionsById(area.getParentId());
            if (city == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到地区数据");
            }
            // 查询地区
            SecRegion province = commonService.getRegionsById(city.getParentId());
            if (province == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到地区数据");
            }
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("provinceCode", province.getRegionId());
            map.put("provinceName", province.getRegionName());
            map.put("cityCode", city.getRegionId());
            map.put("cityName", city.getRegionName());
            map.put("areaCode", area.getRegionId());
            map.put("areaName", area.getRegionName());

            // 下一个调价周期
            BsOilPriceAdjustDate nextPriceDate = oilPriceAdjustDateService.getNextPriceDate();
            if (nextPriceDate == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未设置下一个调价周期");
            }
            map.put("nextPriceDate", DateUtil.date2String(nextPriceDate.getDate(),"MM月dd日"));

            // 油价信息
            List<BsOilPriceAdjust> oilPriceAdjustList = oilPriceAdjustService.getList(
                    oilPriceAdjustDateService.getCurrentPriceDate().getDate(),
                    province.getRegionId(),
                    null);
            map.put("oilPriceList", oilPriceAdjustList);

            Map<String,Object> param = new HashMap<>();
            param.put("priceAdjustDateId", nextPriceDate.getId());
            List<BsOilPriceQuizUser> data = oilPriceQuizUserService.getList(param);

            Long riseTotal = data.stream().filter(o -> o.getQuizOption().equals(OilPriceAdjustDateResultEnum.status1.getType())).count();
            Long fallTotal = data.stream().filter(o -> o.getQuizOption().equals(OilPriceAdjustDateResultEnum.status2.getType())).count();
            Long noAdjustTotal = data.stream().filter(o -> o.getQuizOption().equals(OilPriceAdjustDateResultEnum.status3.getType())).count();

            List<Map<String,Object>> quizInfoList = new LinkedList<>();

            // 上涨
            Map<String,Object> riseMap = new HashMap<>();
            riseMap.put("typeCode", OilPriceAdjustDateResultEnum.status1.getType());
            riseMap.put("typeName", OilPriceAdjustDateResultEnum.status1.getName());
            riseMap.put("total", riseTotal);
            riseMap.put("rate", data.size()<=0?0:new BigDecimal(riseTotal.toString()).divide(new BigDecimal(""+data.size()),2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal("100")));
            quizInfoList.add(riseMap);

            // 下跌
            Map<String,Object> fallMap = new HashMap<>();
            fallMap.put("typeCode", OilPriceAdjustDateResultEnum.status2.getType());
            fallMap.put("typeName", OilPriceAdjustDateResultEnum.status2.getName());
            fallMap.put("total", fallTotal);
            fallMap.put("rate", data.size()<=0?0:new BigDecimal(fallTotal.toString()).divide(new BigDecimal(""+data.size()),2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal("100")));
            quizInfoList.add(fallMap);

            // 不调整
            Map<String,Object> noAdjustMap = new HashMap<>();
            noAdjustMap.put("typeCode", OilPriceAdjustDateResultEnum.status3.getType());
            noAdjustMap.put("typeName", OilPriceAdjustDateResultEnum.status3.getName());
            noAdjustMap.put("total", noAdjustTotal);
            noAdjustMap.put("rate", data.size()<=0?0:new BigDecimal(noAdjustTotal.toString()).divide(new BigDecimal(""+data.size()),2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal("100")));
            quizInfoList.add(noAdjustMap);

            map.put("quizInfoList", quizInfoList);

            map.put("isShow", !oilPriceAdjustList.isEmpty());
            return ResponseMsgUtil.success(map);

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

    @RequestMapping(value = "/queryPrice", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油价信息")
    public ResponseData queryPrice(@RequestParam(name = "regionId", required = true) Long regionId,
                                   @RequestParam(name = "oilNo", required = true) String oilNo) {
        try {
            // 查询地区
            SecRegion area = commonService.getRegionsById(regionId);
            if (area == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到地区数据");
            }
            // 查询地区
            SecRegion city = commonService.getRegionsById(area.getParentId());
            if (city == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到地区数据");
            }
            // 查询地区
            SecRegion province = commonService.getRegionsById(city.getParentId());
            if (province == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到地区数据");
            }
            Map<String,Object> map = new LinkedHashMap<>();
            // 近期调价时间
            List<String> adjustDateData = new LinkedList<>();
            List<BigDecimal> priceList = new LinkedList<>();

            Map<String,Object> adjustParam = new LinkedHashMap<>();
            adjustParam.put("showStatus", "1");
            adjustParam.put("orderBy", "1");
            List<BsOilPriceAdjustDate> dateList = oilPriceAdjustDateService.getList(adjustParam);
            if (dateList.size() >= 4) {
                int total = 0;
                BigDecimal upPrice = new BigDecimal("0");
                for (BsOilPriceAdjustDate date : dateList) {
                    // 限制展示近期4次调价
                    if (total < 4) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(date.getDate());
                        LocalDate dateS = LocalDate.of(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1,calendar.get(Calendar.DATE));
                        if (ChronoUnit.DAYS.between(dateS, LocalDate.now()) >= 10) {
                            adjustDateData.add(DateUtil.date2String(date.getDate(), "MM-dd"));
                            // 价格
                            BsOilPriceAdjust priceAdjust = oilPriceAdjustService.getDetail(date.getDate(), province.getRegionId(), null, oilNo);
                            if (priceAdjust != null) {
                                upPrice = priceAdjust.getPriceOfficial();
                                priceList.add(priceAdjust.getPriceOfficial());
                            } else {
                                priceList.add(upPrice);
                            }
                        } else {
                            if (date.getResult() > 0) {
                                adjustDateData.add("今天");
                            } else {
                                adjustDateData.add(DateUtil.date2String(date.getDate(), "MM-dd"));
                            }
                            // 价格
                            BsOilPriceAdjust priceAdjust = oilPriceAdjustService.getDetail(date.getDate(), province.getRegionId(), null, oilNo);
                            if (priceAdjust != null) {
                                upPrice = priceAdjust.getPriceOfficial();
                                priceList.add(priceAdjust.getPriceOfficial());
                            } else {
                                priceList.add(upPrice);
                            }
                        }
                    }
                    total++;
                }
            }
            map.put("dateList", adjustDateData);
            map.put("priceList", priceList);

            return ResponseMsgUtil.success(map);

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

    @RequestMapping(value = "/queryQuizInfo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询竞猜信息")
    public ResponseData queryQuizInfo() {
        try {
            Map<String,Object> map = new LinkedHashMap<>();
            // 下一个调价周期
            BsOilPriceAdjustDate nextPriceDate = oilPriceAdjustDateService.getNextPriceDate();
            if (nextPriceDate == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未设置下一个调价周期");
            }
            map.put("nextPriceDate", nextPriceDate.getDate());

            // 竞猜详情
            Map<String,Object> param = new HashMap<>();
            param.put("priceAdjustDateId", nextPriceDate.getId());
            // 竞猜用户数据
            List<BsOilPriceQuizUser> data = oilPriceQuizUserService.getList(param);
            map.put("quizUserTotal", data.size());

            Long riseTotal = data.stream().filter(o -> o.getQuizOption().equals(OilPriceAdjustDateResultEnum.status1.getType())).count();
            Long fallTotal = data.stream().filter(o -> o.getQuizOption().equals(OilPriceAdjustDateResultEnum.status2.getType())).count();
            Long noAdjustTotal = data.stream().filter(o -> o.getQuizOption().equals(OilPriceAdjustDateResultEnum.status3.getType())).count();

            List<Map<String,Object>> quizInfoList = new LinkedList<>();

            // 上涨
            Map<String,Object> riseMap = new HashMap<>();
            riseMap.put("typeCode", OilPriceAdjustDateResultEnum.status1.getType());
            riseMap.put("typeName", OilPriceAdjustDateResultEnum.status1.getName());
            riseMap.put("total", riseTotal);
            riseMap.put("rate", data.size()<=0?0:new BigDecimal(riseTotal.toString()).divide(new BigDecimal(""+data.size()),2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal("100")));
            quizInfoList.add(riseMap);

            // 下跌
            Map<String,Object> fallMap = new HashMap<>();
            fallMap.put("typeCode", OilPriceAdjustDateResultEnum.status2.getType());
            fallMap.put("typeName", OilPriceAdjustDateResultEnum.status2.getName());
            fallMap.put("total", fallTotal);
            fallMap.put("rate", data.size()<=0?0:new BigDecimal(fallTotal.toString()).divide(new BigDecimal(""+data.size()),2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal("100")));
            quizInfoList.add(fallMap);

            // 不调整
            Map<String,Object> noAdjustMap = new HashMap<>();
            noAdjustMap.put("typeCode", OilPriceAdjustDateResultEnum.status3.getType());
            noAdjustMap.put("typeName", OilPriceAdjustDateResultEnum.status3.getName());
            noAdjustMap.put("total", noAdjustTotal);
            noAdjustMap.put("rate", data.size()<=0?0:new BigDecimal(noAdjustTotal.toString()).divide(new BigDecimal(""+data.size()),2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal("100")));
            quizInfoList.add(noAdjustMap);

            map.put("quizInfoList", quizInfoList);

            Map<String,Object> rewardParam = new LinkedHashMap<>();
            rewardParam.put("priceAdjustDateId", nextPriceDate.getId());
            map.put("rewardList", oilPriceQuizRewardService.getList(rewardParam));

            map.put("userQuizInfo", null);

            // 用户信息
            try {
                UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);
                if (userSession != null) {
                    map.put("userQuizInfo", oilPriceQuizUserService.getDetail(nextPriceDate.getDate(), userSession.getUser().getId()));
                }
            } catch (Exception e) { }
            return ResponseMsgUtil.success(map);

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

    @RequestMapping(value = "/userQuiz", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "用户竞猜")
    public ResponseData userQuiz(@RequestBody JSONObject body) {
        try {
            UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);
            if (body == null
                    || body.getDate("priceAdjustDate") == null
                    || body.getInteger("quizOption") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 竞猜时间
            BsOilPriceAdjustDate adjustDate = oilPriceAdjustDateService.getDetailByDate(body.getDate("priceAdjustDate"));
            if (adjustDate == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到竞猜时间");
            }
            if (oilPriceQuizUserService.getDetail(body.getDate("priceAdjustDate"),userSession.getUser().getId()) != null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请勿重复竞猜");
            }
            BsOilPriceQuizUser quizUser = new BsOilPriceQuizUser();
            quizUser.setPriceAdjustDateId(adjustDate.getId());
            quizUser.setPriceAdjustDate(adjustDate.getDate());
            quizUser.setUserId(userSession.getUser().getId());
            quizUser.setUserPhone(userSession.getUser().getPhone());
            quizUser.setQuizOption(body.getInteger("quizOption"));
            quizUser.setNoticeStatus(false);
            oilPriceQuizUserService.edit(quizUser);

            return ResponseMsgUtil.success("竞猜成功");

        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

}
