package org.jeecg.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.DictAnnotationUtil;
import org.jeecg.modules.app.service.IGameService;
import org.jeecg.modules.app.vo.game.*;
import org.jeecg.modules.system.app.entity.*;
import org.jeecg.modules.system.app.mapper.*;
import org.jeecg.modules.system.app.utils.StringMasker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 赛事表
 * @Author: jeecg-boot
 * @Date: 2025-07-03
 * @Version: V1.0
 */
@Service
public class GameServiceImpl  implements IGameService {


    @Autowired
    private AppGameMapper appGameMapper;
    @Autowired
    private AppGamePriceRulesMapper appGamePriceRulesMapper;

    @Autowired
    private AppGameScheduleMapper appGameScheduleMapper;

    @Autowired
    private AppInsureMapper appInsureMapper;
    @Autowired
    InsurePriceMapper insurePriceMapper;
    @Autowired
    private AppOrderMapper appOrderMapper;


    @Override
    public Result<IPage<FindPagResponse>> findConcerts(FindPageGameVO findPageGame) {

        if (StringUtils.isEmpty(findPageGame.getLatitude())||StringUtils.isEmpty(findPageGame.getLongitude())){
            return Result.error("经纬度不能为空");
        }
        double latitude = 0;
        double longitude = 0;
        try {
            latitude = Double.parseDouble(findPageGame.getLatitude());
            longitude = Double.parseDouble(findPageGame.getLongitude());
        } catch (NumberFormatException e) {
            return Result.error("经纬度格式错误");
        }
        Page<FindPagResponse> page = new Page<>(findPageGame.getPageNo(), findPageGame.getPageSize());

        return Result.OK(appGameMapper.findConcerts(page,longitude,latitude)) ;
    }

    @Override
    public Result<FindByIdResponse> findById(String id,String longitude, String latitude) {
        if (StringUtils.isEmpty(id)){
            return Result.error("未选择赛事");
        }
        if (StringUtils.isEmpty(longitude)||StringUtils.isEmpty(latitude)){
            return Result.error("经纬度不能为空");
        }
        double latitudeNew = 0;
        double longitudeNew = 0;
        try {
            latitudeNew = Double.parseDouble(latitude);
            longitudeNew = Double.parseDouble(longitude);
        } catch (NumberFormatException e) {
            return Result.error("经纬度格式错误");
        }
        FindByIdResponse findByIdResponse =  appGameMapper.findById(id,longitudeNew,latitudeNew);
        if (findByIdResponse==null){
            return Result.error("未查询到数据，请确认赛事是否存在");
        }
        if (StringUtils.isNotEmpty(findByIdResponse.getBackgroundImage())){
            List<String> backgroundImageList = new ArrayList<>();
            if (findByIdResponse.getBackgroundImage().indexOf(",")>0){
                backgroundImageList= Arrays.asList(findByIdResponse.getBackgroundImage().split(","));
            }else {
                backgroundImageList.add(findByIdResponse.getBackgroundImage());
            }
            findByIdResponse.setBackgroundImageList(backgroundImageList);
        }
        List<String> strings = new ArrayList<>();
        if (findByIdResponse.getGamePriceRulesVOList()!=null&&!findByIdResponse.getGamePriceRulesVOList().isEmpty()){
            for (GamePriceRulesVO gamePriceRulesVO : findByIdResponse.getGamePriceRulesVOList()) {
                strings.add(gamePriceRulesVO.getId());
            }
        }
        if (strings!=null&&!strings.isEmpty()){
            int orderNum = appOrderMapper.countTypeAndProductIds(strings, CommonConstant.ORDER_TYPE_1);
            findByIdResponse.setOrderNum(orderNum);
        }
        if (strings!=null&&!strings.isEmpty()){
            List<GameOrderVo> gameOrderVoList = appOrderMapper.findByNewOrderInfo(strings,CommonConstant.ORDER_TYPE_1);
            for (GameOrderVo gameOrderVo : gameOrderVoList) {
                String username = gameOrderVo.getUsername();
                String mask = StringMasker.mask(username);
                gameOrderVo.setUsername(mask);
            }
            findByIdResponse.setGameOrderVoList(gameOrderVoList);
        }
        return Result.OK(findByIdResponse);
    }

    @Override
    public Result<FindByGameIdPriceVo> findByGameId(String id) {
        FindByGameIdPriceVo findByGameIdPriceVo = appGameMapper.findByGameId(id);
        if (findByGameIdPriceVo==null){
            return Result.error("该赛事未查询到比赛");
        }
        if (StringUtils.isNotEmpty(findByGameIdPriceVo.getInsureIds())){
            List<String> aptitudesList = new ArrayList<>();
            if (findByGameIdPriceVo.getInsureIds().indexOf(",")>0){
                aptitudesList =  Arrays.asList(findByGameIdPriceVo.getInsureIds().split(","));
            }else {
                aptitudesList.add(findByGameIdPriceVo.getInsureIds());
            }
            LambdaQueryWrapper<AppInsure> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(AppInsure::getId, aptitudesList)
                    .eq(AppInsure::getStatus,0)
                    .eq(AppInsure::getDelFlag,0);  // 方法引用 + 集合
            List<AppInsure> appInsureList = appInsureMapper.selectList(wrapper);
            DictAnnotationUtil.translateDictList(appInsureList);
            for (AppInsure appInsure : appInsureList) {
                List<InsurePrice> insurePrices = insurePriceMapper.selectList(new QueryWrapper<InsurePrice>().lambda().eq(InsurePrice::getInsureId, appInsure.getId()).eq(InsurePrice::getDelFlag, 0).orderByAsc(InsurePrice::getInsureDay));
                appInsure.setPriceDataList(insurePrices);
            }
            findByGameIdPriceVo.setInsureIdList(appInsureList);
        }


        if (StringUtils.isNotEmpty(findByGameIdPriceVo.getAptitudes())){
            List<String> aptitudesList = new ArrayList<>();
            if (findByGameIdPriceVo.getAptitudes().indexOf(",")>0){
                aptitudesList =  Arrays.asList(findByGameIdPriceVo.getAptitudes().split(","));
            }else {
                aptitudesList.add(findByGameIdPriceVo.getAptitudes());
            }
            findByGameIdPriceVo.setAptitudesList(aptitudesList);
        }
        if (ObjectUtils.isNotEmpty(findByGameIdPriceVo.getGamePriceRulesTypeVOList())&&!findByGameIdPriceVo.getGamePriceRulesTypeVOList().isEmpty()){
            for (GamePriceRulesTypeVO gamePriceRulesTypeVO : findByGameIdPriceVo.getGamePriceRulesTypeVOList()) {
                if (ObjectUtils.isNotEmpty(gamePriceRulesTypeVO.getType())){
                    List<GamePriceRulesVO> gamePriceRulesVOList=  appGamePriceRulesMapper.findByGameIdList(id,gamePriceRulesTypeVO.getType());
                    gamePriceRulesTypeVO.setGamePriceRulesVOList(gamePriceRulesVOList);
                }
            }
        }
        return Result.OK(findByGameIdPriceVo);
    }

    @Override
    public Result<AppGame> findScoreByGameId(String orderId) {
        Result<String> result = findGetGameId(orderId);
        if (!result.isSuccess()){
            return Result.error(result.getMessage());
        }
        AppGame appGame = appGameMapper.selectById(result.getMessage());
        if (appGame==null){
            return Result.error("请确认所查询需要的数据是否存在");
        }
        if (StringUtils.isEmpty(appGame.getGameResults())){
            return Result.error("后台人员还没有发布成绩，请等待");
        }
        return Result.ok(appGame);
    }

    @Override
    public Result<String> findGetGameId(String orderId) {
        AppOrder appOrder = appOrderMapper.selectById(orderId);
        if (appOrder==null){
            return Result.error("该订单不存在");
        }
        if (StringUtils.isEmpty(appOrder.getProductIds())||appOrder.getType()!=1){
            return Result.error("该订单不存在赛事商品");
        }
        AppGamePriceRules appGamePriceRules = appGamePriceRulesMapper.selectById(appOrder.getProductIds());
        if (appGamePriceRules==null){
            return Result.error("该商品不存在,订单号："+appOrder.getOrderCode());
        }
        if (StringUtils.isEmpty(appGamePriceRules.getGameId())){
            return Result.error("该商品未关联赛事,订单号："+appOrder.getOrderCode());
        }
        return Result.ok(appGamePriceRules.getGameId());
    }

    @Override
    public Result<List<GameScheduleVO>> findScheduleByOrderId(String orderId) {
        Result<String> result = findGetGameId(orderId);
        if (!result.isSuccess()){
            return Result.error(result.getMessage());
        }

        return Result.ok(appGameScheduleMapper.findByGameId(result.getMessage()));
    }


}
