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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.app.service.IAppIsinService;
import org.jeecg.modules.app.vo.AppGmtInfoVO;
import org.jeecg.modules.app.vo.AppIsinVerifyVO;
import org.jeecg.modules.app.vo.AppOrderUseRecordsVO;
import org.jeecg.modules.system.app.entity.*;
import org.jeecg.modules.system.app.mapper.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Log4j2
public class AppIsinServiceImpl extends ServiceImpl<AppIsinMapper, AppIsin> implements IAppIsinService {

    @Resource
    private AppGmtInfoMapper appGmtInfoMapper;
    @Resource
    private AppOrderProInfoMapper appOrderProInfoMapper;
    @Resource
    private AppOrderMapper appOrderMapper;
    @Resource
    private FamilyMembersMapper familyMembersMapper;
    @Resource
    private AppGameMapper appGameMapper;
    @Resource
    private AppSiteMapper appSiteMapper;
    @Resource
    private AppSitePriceRulesMapper appSitePriceRulesMapper;
    @Resource
    private AppSitePlaceMapper appSitePlaceMapper;
    @Resource
    private AppGamePriceRulesMapper appGamePriceRulesMapper;
    @Resource
    private AppCoursesMapper appCoursesMapper;

    @Override
    public Page<AppIsinVerifyVO> pageAppIsinVerifyRecords(Page<AppIsinVerifyVO> page, String orgCode) {
        return baseMapper.pageAppIsinVerifyRecords(page,orgCode);
    }

    @Override
    public Page<AppIsinVerifyVO> pageAppIsinVerifies(Page<AppIsinVerifyVO> page, String userId) {
        return baseMapper.pageAppIsinVerifies(page,userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String repealVerifyRecord(String appIsinId) throws ParseException {

        AppIsin appIsin = this.getById(appIsinId);
        //校验核验时间
        if(ObjectUtil.isNotEmpty(appIsin.getUseTime())){
            Date expTime = getDate(appIsin.getUseTime());
            if(expTime.before(new Date())){
                throw new JeecgBootException("已超过可撤销时间,无法撤销！");
            }
        }
        appIsin.setIsinStatus(0);

        // 创建SimpleDateFormat对象，指定目标格式
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");

        // 定义要转换的字符串格式的日期
        String dateString = appIsin.getExpireTime();

        // 使用parse方法将字符串转换为Date对象
        Date expireTime = ft.parse(dateString);

        //判断当前时间是否过期
        if(expireTime.before(new Date())) {
            appIsin.setIsinStatus(2);
        }
        this.updateById(appIsin);

       //查询订单，修改订单状态为待使用
        AppOrderProInfo appOrderProInfo = appOrderProInfoMapper.selectOne(Wrappers.<AppOrderProInfo>lambdaQuery().eq(AppOrderProInfo::getTicketNo, appIsin.getTicketNo()));
        if(ObjectUtil.isNotEmpty(appOrderProInfo)){
            appOrderProInfo.setOrderStatus(1);
            appOrderProInfoMapper.updateById(appOrderProInfo);
        }
        String orderId = appOrderProInfo.getOrderId();
        AppOrder appOrder = appOrderMapper.selectById(orderId);
        List<AppOrderProInfo> proInfoList = appOrderProInfoMapper.selectList(Wrappers.<AppOrderProInfo>lambdaQuery().eq(AppOrderProInfo::getOrderId, orderId).gt(AppOrderProInfo::getOrderStatus, 1));
        if (ObjectUtil.isEmpty(proInfoList)){
            appOrder.setOrderStatus(CommonConstant.ORDER_STATUS_1);
            appOrderMapper.updateById(appOrder);
        }
        return "撤销成功！";
    }

    @Override
    public AppOrderUseRecordsVO queryOrderUseRecords(String ticketNo) {
        AppOrderUseRecordsVO appOrderUseRecordsVO = new AppOrderUseRecordsVO();
        List<AppIsin> appIsinList = this.list(Wrappers.lambdaQuery(AppIsin.class).eq(AppIsin::getTicketNo, ticketNo));
        appOrderUseRecordsVO.setAppIsinList(appIsinList);
        List<AppGmtInfoVO> appGmtInfoVOList = new ArrayList<>();
        List<AppOrderProInfo> appOrderProInfos = appOrderProInfoMapper.selectList(Wrappers.lambdaQuery(AppOrderProInfo.class).eq(AppOrderProInfo::getTicketNo, ticketNo));
        for (AppOrderProInfo appOrderProInfo : appOrderProInfos) {
            if (Objects.equals(
                    appOrderProInfo.getType(), CommonConstant.ORDER_PRO_INFO_TYPE_3)
                    || Objects.equals(appOrderProInfo.getType(), CommonConstant.ORDER_PRO_INFO_TYPE_0)
                    || Objects.equals(appOrderProInfo.getType(), CommonConstant.ORDER_PRO_INFO_TYPE_5)){
                //个人赛
                if (Objects.equals(appOrderProInfo.getType(), CommonConstant.ORDER_PRO_INFO_TYPE_3)){
                    String familyUserId = appOrderProInfo.getFamilyUserId();
                    List<String> familyIds = Arrays.stream(familyUserId.split(",")).collect(Collectors.toList());
                    AppOrder appOrder = appOrderMapper.selectById(appOrderProInfo.getOrderId());
                    AppGamePriceRules appGamePriceRules = appGamePriceRulesMapper.selectById(appOrder.getProductIds());
                    AppGame appGame = appGameMapper.selectById(appGamePriceRules.getGameId());
                    for (String familyId : familyIds) {
                        if (Objects.nonNull(appGame)){
                            List<AppGmtInfo> appGmtInfos = appGmtInfoMapper.selectList(Wrappers.lambdaQuery(AppGmtInfo.class).eq(AppGmtInfo::getFamilyId, familyId).between(AppGmtInfo::getGmtCreate, appGame.getStartTime(), appGame.getEndTime()));
                            for (AppGmtInfo appGmtInfo : appGmtInfos) {
                                String familyUserName = familyMembersMapper.selectById(appGmtInfo.getFamilyId()).getFullName();
                                String siteName = appSiteMapper.selectById(appGmtInfo.getSiteId()).getName();
                                AppGmtInfoVO appGmtInfoVO = new AppGmtInfoVO();
                                appGmtInfoVO
                                        .setSiteId(appGmtInfo.getSiteId())
                                        .setSiteName(siteName)
                                        .setFamilyId(appGmtInfo.getFamilyId())
                                        .setFamilyUserName(familyUserName)
                                        .setGmtCreate(appGmtInfo.getGmtCreate())
                                        .setPicUrl(appGmtInfo.getPicUrl());
                                appGmtInfoVOList.add(appGmtInfoVO);
                            }
                        }
                    }
                }
                //学校
                if (Objects.equals(appOrderProInfo.getType(), CommonConstant.ORDER_PRO_INFO_TYPE_0)){
                    String familyUserId = appOrderProInfo.getFamilyUserId();
                    AppOrder appOrder = appOrderMapper.selectById(appOrderProInfo.getOrderId());
                    String productIds = appOrder.getProductIds();
                    AppSitePriceRules appSitePriceRules = appSitePriceRulesMapper.selectById(productIds);
                    if (Objects.nonNull(appSitePriceRules)){
                        String sitePlaceId = appSitePriceRules.getSitePlaceId();
                        AppSitePlace appSitePlace = appSitePlaceMapper.selectById(sitePlaceId);
                        AppSite appSite = appSiteMapper.selectById(appSitePlace.getSiteId());
                        List<AppGmtInfo> appGmtInfos = appGmtInfoMapper.selectList(Wrappers.lambdaQuery(AppGmtInfo.class)
                                        .eq(AppGmtInfo::getSiteId, appSite.getId())
                                .eq(AppGmtInfo::getFamilyId, familyUserId).between(AppGmtInfo::getGmtCreate, appSitePriceRules.getStartTime(), appSitePriceRules.getEndTime()));
                        for (AppGmtInfo appGmtInfo : appGmtInfos) {
                            String familyUserName = familyMembersMapper.selectById(appGmtInfo.getFamilyId()).getFullName();
                            String siteName = appSiteMapper.selectById(appGmtInfo.getSiteId()).getName();
                            AppGmtInfoVO appGmtInfoVO = new AppGmtInfoVO();
                            appGmtInfoVO
                                    .setSiteId(appGmtInfo.getSiteId())
                                    .setSiteName(siteName)
                                    .setFamilyId(appGmtInfo.getFamilyId())
                                    .setFamilyUserName(familyUserName)
                                    .setGmtCreate(appGmtInfo.getGmtCreate())
                                    .setPicUrl(appGmtInfo.getPicUrl());
                            appGmtInfoVOList.add(appGmtInfoVO);
                        }
                    }
                }
                //课程
                if (Objects.equals(appOrderProInfo.getType(), CommonConstant.ORDER_PRO_INFO_TYPE_5)){
                    String familyUserId = appOrderProInfo.getFamilyUserId();
                    AppOrder appOrder = appOrderMapper.selectById(appOrderProInfo.getOrderId());
                    String productIds = appOrder.getProductIds();
                    AppCourses appCourses = appCoursesMapper.selectById(productIds);
                    if (Objects.nonNull(appCourses)){
                        String siteId = appCourses.getAddressSiteId();

                        List<AppGmtInfo> appGmtInfos = appGmtInfoMapper.selectList(Wrappers.lambdaQuery(AppGmtInfo.class)
                                .eq(AppGmtInfo::getSiteId, siteId)
                                .eq(AppGmtInfo::getFamilyId, familyUserId).between(AppGmtInfo::getGmtCreate, appCourses.getStartTime(), appCourses.getEndTime()));
                        for (AppGmtInfo appGmtInfo : appGmtInfos) {
                            String familyUserName = familyMembersMapper.selectById(appGmtInfo.getFamilyId()).getFullName();
                            String siteName = appSiteMapper.selectById(appGmtInfo.getSiteId()).getName();
                            AppGmtInfoVO appGmtInfoVO = new AppGmtInfoVO();
                            appGmtInfoVO
                                    .setSiteId(appGmtInfo.getSiteId())
                                    .setSiteName(siteName)
                                    .setFamilyId(appGmtInfo.getFamilyId())
                                    .setFamilyUserName(familyUserName)
                                    .setGmtCreate(appGmtInfo.getGmtCreate())
                                    .setPicUrl(appGmtInfo.getPicUrl());
                            appGmtInfoVOList.add(appGmtInfoVO);
                        }
                    }
                }
            }
        }
        appOrderUseRecordsVO.setAppGmtInfoList(appGmtInfoVOList);
        return appOrderUseRecordsVO;
    }

    //时间加1小时
    public static Date getDate(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 24小时制
        cal.add(Calendar.HOUR, 1);
        return cal.getTime();
    }
}
