package beilv.web.controller.bootacourse;

import beilv.admissionticket.domain.AdmissionTicket;
import beilv.admissionticket.service.IAdmissionTicketService;
import beilv.bootacourse.domain.BootACourse;
import beilv.bootacourse.domain.BootACourseBO;
import beilv.bootacourse.service.IBootACourseService;
import beilv.common.constant.PriceOptions;
import beilv.common.core.controller.BaseController;
import beilv.common.core.domain.AjaxResult;
import beilv.common.core.page.PageDomain;
import beilv.common.core.page.TableSupport;
import beilv.common.utils.DictUtils;
import beilv.common.utils.StringUtils;
import beilv.common.utils.uuid.IdUtils;
import beilv.site.domain.BeilvSite;
import beilv.site.service.IBeilvSiteService;
import beilv.system.domain.SysNotice;
import beilv.system.service.ISysConfigService;
import beilv.usermembershipcard.domain.MemberStream;
import beilv.usermembershipcard.domain.UserMembershipCard;
import beilv.usermembershipcard.service.IUserMembershipCardService;
import beilv.vipCard.domain.VipCard;
import beilv.vipCard.service.IVipCardService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/app-api/bootACourse")
public class bootACourseController extends BaseController {

    @Autowired
    private IBeilvSiteService siteService;
    @Autowired
    private IAdmissionTicketService ticketService;
    @Autowired
    private IUserMembershipCardService cardService;
    @Autowired
    private IBootACourseService courseService;
    @Autowired
    private IUserMembershipCardService userMembershipCardService;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IVipCardService vipCardService;

    /**
     * 查询球馆列表
     */
    /*@PostMapping("/getVenueList")
    public AjaxResult getVenueList() {
        //获取球场列表
        List<BeilvVenue> resultList = venueService.selectBeilvVenueList(new BeilvVenue());
        return AjaxResult.success(resultList);
    }*/

    /**
     * 根据场馆id查询其具有的场地类型
     */
    /*@PostMapping("/getSiteType")
    public AjaxResult getSiteType(@RequestBody BeilvSite beilvSite) {
        List<Map<String, String>> siteType = siteService.selectSiteTypeByVenueId(beilvSite);

        siteType.forEach(map -> {
            map.put("siteTypeLabel", DictUtils.getDictLabel("site_type", map.get("siteType")));
        });
        return AjaxResult.success(siteType);
    }*/

    /**
     * 根据场馆id获取下面的球场信息
     *
     * @param beilvSite venueId(场馆id) 默认值8
     */
    @GetMapping("/getSiteList")
    public AjaxResult getSiteList(BeilvSite beilvSite) {
        startPage();
        beilvSite.setVenueId(8L);
        //获取会员卡集合
        List<BeilvSite> beilvSites = siteService.selectBeilvSiteList(beilvSite);
        beilvSites.forEach(site->{
            site.setCoverList(new ArrayList<>(Arrays.asList(site.getCover().split(","))));
        });
        return AjaxResult.success(getDataTable(beilvSites).getRows());
    }

    /**
     * 根据球场类型, 判断用户是否具有此类会员卡
     * 有返回会员卡信息集合
     * 没有返回空集合
     */
    @PostMapping("/hasClubCard")
    public AjaxResult hasClubCard(@RequestBody BootACourseBO course) {
        UserMembershipCard userMembershipCard = new UserMembershipCard();
        userMembershipCard.setUserId(course.getUserId());
        userMembershipCard.setCardType(course.getTicketType());
        userMembershipCard.setState("3");
        userMembershipCard.setState("hasClubCard");
        return AjaxResult.success(userMembershipCardService.selectUserMembershipCardList(userMembershipCard));
    }

    /**
     * 查询可购票的场次信息
     * 请求参数:
     * 日期: yyyy-MM-dd
     * 场地类型: site_type字典
     * 球场id:
     */
    @PostMapping("/getTicketList")
    public AjaxResult getTicketList(@RequestBody AdmissionTicket admissionTicket) {
        //设置查询状态: 可以预定的时段
//        admissionTicket.setAdmissionTicketStatus("0");
        //查询可用时段
        List<AdmissionTicket> admissionTickets = ticketService.selectBeilvAdmissionTicketList(admissionTicket);
        Map<String, String> siteType = DictUtils.getDictCacheToMap("site_type");

        //查询会员等级
        String vipLevel = null;
        VipCard vipCard = vipCardService.selectVipCardByUserId(admissionTicket.getUserId());
        if (ObjectUtils.isNotEmpty(vipCard)) {
            vipLevel = vipCard.getVipLevel();
        }
        //查询会员折扣
        BigDecimal coefficient = BigDecimal.valueOf(Double.parseDouble(StringUtils.isEmpty(vipLevel) ? "1" : configService.selectConfigByKey(vipLevel)));

        admissionTickets.forEach(ticket->{
            ticket.setTicketPrice(new PriceOptions(ticket.getPrice(),coefficient));
            ticket.setSiteTypeLabel(MapUtils.getString(siteType, ticket.getSiteType()));
        });

        return AjaxResult.success(admissionTickets);
    }

    /**
     * 购票接口
     * 用户id, 场次id, 会员卡id
     *
     * @return
     */
//    @PostMapping("/addCourse")
//    public AjaxResult addCourse(@RequestBody BootACourseBO course) {
//        //根据场次id 关联球馆表, 获取球馆允许提前多少分钟可以退票
//        Date refund = calculationTime(ticketService.getThresholdValue(course.getTicketId()));
//
//
//        //生成订单编号
//        String orderId = IdUtils.fastSimpleUUID();
//        //生成订单信息
//        BootACourse bootACourse = new BootACourse(
//                course.getUserId(), //用户id
//                course.getContactPeople(), //联系人
//                course.getContactNumber(), //联系电话
//                new Date(), //下单时间
//                "payment_status_to_be_paid", //支付状态
//                orderId, //订单比那好
//                course.getTicketId(), //场次id
//                course.getTicketType(), //场地类型
//                course.getClubCardId(), //会员卡号
//                refund); //最晚退单时间
//        //验证场次是否可用
//        if (courseService.isOk(course)) {
//            //调用会员卡接口减少次数
//            MemberStream memberStream = new MemberStream();
//            memberStream.setUserCardId(course.getClubCardId());
//            memberStream.setType("0");
//            memberStream.setOrderId(orderId);
//            memberStream.setCreateBy(course.getUserId());
//
//            int i = cardService.addStream(memberStream);
//            if(i == -1){
//                return AjaxResult.error("会员卡次数不足");
//            }
//
//            //扣除成功后, 修改订单状态为已付款.
//            bootACourse.setPaymentTime(new Date());
//            bootACourse.setPaymentStatus("payment_status_have_paid");
//
//            //将门票信息修改为2: 线上预约的时段;
//            AdmissionTicket admissionTicket = new AdmissionTicket();
//            admissionTicket.setId(course.getTicketId());
//            admissionTicket.setAdmissionTicketStatus("2");
//            ticketService.updateBeilvAdmissionTicket(admissionTicket);
//
//            return toAjax(courseService.addCourse(bootACourse));
//        } else {
//            return AjaxResult.error("当前场次已被预订");
//        }
//    }
//
//    /**
//     * 查询订单
//     */
//    @GetMapping("/getCourseList")
//    public AjaxResult getCourseList(BootACourseBO courseBO) {
//        startPage();
//        List<BootACourse> courseList = courseService.getCourseList(courseBO);
//        Map<String, String> paymentStatus = DictUtils.getDictCacheToMap("payment_status");
//        courseList.forEach(course->{
//            course.setPaymentStatusLabel(paymentStatus.get(course.getPaymentStatus()));
//            course.setCoverList(course.getCover().split(","));
//        });
//        return AjaxResult.success(courseList);
//    }
//
//
//    /**
//     * 退票接口
//     * 用户id, 订单编号,
//     *
//     * @return 1: 订单已核销
//     * 2: 退票成功
//     */
//    @PostMapping("/remofeCourse")
//    public AjaxResult remofeCourse(@RequestBody BootACourseBO courseBo) {
//        //通过orderId查询订单信息
//        BootACourse course = courseService.getCourseInfo(courseBo);
//
//        //判断最晚退单时间大于当前时间, 并且订单状态为已支付
//        if (course.getRefund().after(new Date()) && "payment_status_have_paid".equals(course.getPaymentStatus())) {
//            //根据订单信息中的会员卡退次数
//            //调用会员卡接口减少次数
//            MemberStream memberStream = new MemberStream();
//            memberStream.setUserCardId(course.getClubCardId());
//            memberStream.setType("1");
//            memberStream.setOrderId(course.getOrderId());
//            cardService.addStream(memberStream);
//
//
//            //修改场次信息状态为0: 可以预定的时段;
//            AdmissionTicket admissionTicket = new AdmissionTicket();
//            admissionTicket.setId(course.getTicketId());
//            admissionTicket.setAdmissionTicketStatus("0");
//            ticketService.updateBeilvAdmissionTicket(admissionTicket);
//
//            //修改订单信息状态为退款,
//            course.setRefundTime(new Date());
//            course.setRefundInstructions(courseBo.getRefundInstructions());
//            course.setPaymentStatus("payment_status_refunded");
//            return toAjax(courseService.updateCourse(course));
//        } else {
//            if ("payment_status_verification".equals(course.getPaymentStatus())) {
//                return AjaxResult.error("订单已核销");
//            } else if (course.getRefund().after(new Date())) {
//                return AjaxResult.error("当前订单超过最晚退单时间, 不允许退单");
//            }
//            return AjaxResult.error("未知原因退款失败!");
//        }
//
//    }
//
//
//    private Date calculationTime(Map<String, Object> map) {
//
//        String sessionStr = MapUtils.getString(map, "session").split("-")[0]; //12:15
//
//        String thresholdValueStr = MapUtils.getString(map, "thresholdValue");// 120
//
//        String ticketDate = MapUtils.getString(map, "ticketDate");// 2025-01-07
//
//        // 拼接 ticketDate 和 sessionStr 形成完整的时间字符串
//        String fullTimeStr = ticketDate + " " + sessionStr + ":00"; // 例如 "2025-01-07 12:15:00"
//
//        // 将完整的时间字符串解析为 Date 对象
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date = null;
//        try {
//            date = dateFormat.parse(fullTimeStr);
//        } catch (ParseException e) {
//            e.printStackTrace();
//            return null; // 如果解析失败，返回 null
//        }
//
//        // 将 thresholdValueStr 转换为整数
//        int thresholdValue = Integer.parseInt(thresholdValueStr);
//
//        // 使用 Calendar 类来减去 thresholdValue 分钟
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(date);
//        calendar.add(Calendar.MINUTE, -thresholdValue);
//
//        // 返回计算后的 Date 对象
//        return calendar.getTime();
//    }
}
