package com.bohuikeji.delivery.backstage.controller.api.customer;

import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.constants.discountConst;
import com.bohuikeji.delivery.backstage.entity.TCustomer;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountMall;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountRecord;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.back.DataPage;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhouliwu
 * 优惠卷操作接口
 * 注：所以接口类必须继承 ApiController，否则无法被接口文档识别
 */

@Api(tags = {"客户优惠卷功能接口"})
@RestController
@Slf4j
@RequestMapping("/api/v2/voucher")
public class VoucherV2Api extends ApiController {

    @Autowired
    ITDiscountMallService createVoucherService;
    @Autowired
    ITCustomerService customerService;
    @Autowired
    ITOrderService orderService;
    @Autowired
    ITDiscountRecordService receiveRecordService;

    /**
     * 客户下单时查询未使用优惠卷
     * @param
     * @return
     */

    @ApiOperation("客户下单时查询未使用优惠卷")
    @GetMapping("/customer/order/get")
    public APIEntity customerByOrderReceive(@RequestAttribute("JwtUserId") Integer id){
        List<TDiscountRecord> receiveRecords = new ArrayList<>(0);//receiveRecordService.list(new QueryWrapper<TDiscountRecord>().eq("customer_id",id).in("usage_status","未使用","使用中"));
        /*if(receiveRecords.size()<1){
            return APIEntity.success(receiveRecords);
        }
        for(TDiscountRecord receiveRecord : receiveRecords){
            if(LocalDate.now().isAfter(receiveRecord.getEndDate())){
                receiveRecordService.updateById(receiveRecord.setUsageStatus("已过期"));
            }
        }*/
        return APIEntity.success(receiveRecords);
    }

    /**
     * 获取用户领取的优惠劵
     * @param
     * @return
     */

    @ApiOperation("获取用户领取的优惠劵的记录")
    @GetMapping("/customer/get/receive")
    @ApiImplicitParams({
            @ApiImplicitParam(name="usageStatus",value="使用状态(未使用,已使用,已过期)",dataType="String", paramType = "query")})
    public APIEntity customerGetReceive(@RequestAttribute("JwtUserId") Integer id, DataPage page,String usageStatus){
        if (StringUtils.isBlank(usageStatus)){
            return APIEntity.fail("查询参数为空！");
        }
        /*List<TDiscountRecord> receiveRecords = receiveRecordService.list(new QueryWrapper<TDiscountRecord>().eq("customer_id",id));
        for(TDiscountRecord receiveRecord : receiveRecords){
            if(LocalDate.now().isAfter(receiveRecord.getEndDate())){
                receiveRecordService.updateById(receiveRecord.setUsageStatus("已过期"));
            }
        }
        QueryWrapper<TDiscountRecord> queryWrapper=new QueryWrapper<TDiscountRecord>().eq("customer_id",id);
        switch (usageStatus){
            case "未使用":
                queryWrapper.in("usage_status",usageStatus,"使用中");break;
            case "其他":
                queryWrapper.notIn("usage_status","未使用","使用中");break;
            default:
                return APIEntity.fail("无法识别参数usageStatus");
        }
        page = (DataPage) receiveRecordService.page(page,queryWrapper);
        JSONArray tPatternCour = new JSONArray();
        List<TDiscountRecord> tReceiveRecords = page.getRecords();*/
        /*for(TDiscountRecord receiveRecord :tReceiveRecords){
            TPatternInfo tPatternInfo = patternInfoService.getById(receiveRecord.getPatternId());
            receiveRecord.setPatternInfo(tPatternInfo);
            tPatternCour.add(receiveRecord);
        }*/
        //page.setRecords(tPatternCour);
        return APIEntity.success(page);
    }
    /**
     * 判断优惠卷是否弹框
     * @param
     * @return
     */

    @ApiOperation("判断优惠卷是否弹框")
    @GetMapping("/get/voucher/bullet/frame/list")
    public APIEntity getVoucherBulletFrame(@RequestAttribute("JwtUserId") Integer id) throws IOException {
        TCustomer tCustomer = customerService.getById(id);
        List<TDiscountMall> discountMalls;
        byte[] b = new byte[1024];
        if(tCustomer == null){
            return APIEntity.fail("当前用户不存在，请重新登陆");
        }
        /*List<Object> couponIds = receiveRecordService.listObjs(new QueryWrapper<TDiscountRecord>().select("dis_id").eq("customer_id",id));
        if(couponIds.size()<1){
            discountMalls = createVoucherService.list(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","客户领取").eq("dis_mode","弹框"));
        }else {
            discountMalls = createVoucherService.list(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","客户领取").eq("dis_mode","弹框").notIn("dis_id",couponIds));
        }

        if(discountMalls.size()<1){
            return APIEntity.success();
        }*/
        /*log.info("获取弹框优惠卷的数量：[{}]",discountMalls.size());
        for(TDiscountMall discountMall : discountMalls){
            List<TDiscountRecord>  receiveRecords = receiveRecordService.list(new QueryWrapper<TDiscountRecord>().eq("dis_id",discountMall.getDisId()).eq("customer_id",id));
            if(receiveRecords.size()>1){
                return APIEntity.success();
            }
            if(tCustomer.getTemplateId() != null && "商户卷".equals(discountMall.getGrantType())){
                log.info("进入商户卷弹框");
                return APIEntity.success(discountConst.frameTemplate(discountMall));
            }
            List<TOrder> orderList = orderService.list(new QueryWrapper<TOrder>().eq("order_status","已完成").eq("player_id",tCustomer.getCustomerId()));
            log.info("当前客户的id:{},下单数量:{}",tCustomer.getCustomerId(),orderList.size());
            if(orderList.size()<1 && "新客户卷".equals(discountMall.getGrantType())){
                log.info("进入新客户卷弹框");
                return APIEntity.success(discountMall);
            }
            if(orderList.size()>1 && "老客户卷".equals(discountMall.getGrantType())){
                log.info("进入老客户卷弹框");
                return APIEntity.success(discountConst.frameTemplate(discountMall));
            }
            if("全部".equals(discountMall.getGrantType()) && tCustomer.getTemplateId()==null){
                log.info("进入全部卷弹框");
                return APIEntity.success(discountConst.frameTemplate(discountMall));
            }
        }*/
        return APIEntity.success();
    }
/**
     * 向不同客户发放符合条件的优惠卷
     * @param
     * @return
     */
    @ApiOperation("向不同客户发放符合条件的优惠卷")
    @GetMapping("/get/voucher/list")
    public APIEntity getVoucherList(@RequestAttribute("JwtUserId") Integer id,DataPage page){
        List<TDiscountMall> discountMalls = null;
        TCustomer tCustomer = customerService.getById(id);
        if(tCustomer == null){
            return APIEntity.fail("当前用户不存在，请重新登陆");
        }
        if(StringUtils.isNotBlank(tCustomer.getTemplateId())){
            return APIEntity.success(page);
        }
        List<TDiscountMall> createVouchers = createVoucherService.list(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中"));
        for(TDiscountMall discountMall : createVouchers){
            if(LocalDate.now().isAfter(discountMall.getEndDate())){
                createVoucherService.updateById(discountMall.setDisState("已过期"));
            }
        }
        List<Object> couponIds = receiveRecordService.listObjs(new QueryWrapper<TDiscountRecord>().select("dis_id").eq("customer_id",id));
        JSONArray voucher = new JSONArray();
        if(!tCustomer.getBigId().equals(0)){
            if(couponIds.size()<1){
                page = (DataPage) createVoucherService.page(page,new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","客户领取").eq("grant_type","商户卷")
                        .or().eq("dis_state","发放中").eq("receive_method","客户领取").eq("grant_type","全部"));
            }else {
                page = (DataPage) createVoucherService.page(page,new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","客户领取").notIn("dis_id",couponIds).eq("grant_type","商户卷")
                        .or().eq("dis_state","发放中").eq("receive_method","客户领取").notIn("dis_id",couponIds).eq("grant_type","全部"));
            }
            discountMalls = page.getRecords();
        }
        List<TOrder> orderList = orderService.list(new QueryWrapper<TOrder>().eq("order_status","已完成").eq("player_id",tCustomer.getCustomerId()));
        log.info("当前客户的下单数量:[{}]",orderList.size());
        if(orderList.size()<1){
            if(couponIds.size()<1){
                page = (DataPage) createVoucherService.page(page,new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","客户领取").eq("grant_type","新客户卷")
                        .or().eq("dis_state","发放中").eq("receive_method","客户领取").eq("grant_type","全部"));
            }else {
                page = (DataPage) createVoucherService.page(page,new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","客户领取").notIn("dis_id",couponIds).eq("grant_type","新客户卷")
                        .or().eq("dis_state","发放中").eq("receive_method","客户领取").notIn("dis_id",couponIds).eq("grant_type","全部"));
            }
            discountMalls = page.getRecords();
        }
        if(orderList.size()>=1){
            if(couponIds.size()<1){
                page = (DataPage) createVoucherService.page(page,new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","客户领取").eq("grant_type","老客户卷")
                        .or().eq("dis_state","发放中").eq("receive_method","客户领取").eq("grant_type","全部"));
            }else {
                page = (DataPage) createVoucherService.page(page,new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","客户领取").notIn("dis_id",couponIds).eq("grant_type","老客户卷")
                        .or().eq("dis_state","发放中").eq("receive_method","客户领取").notIn("dis_id",couponIds).eq("grant_type","全部"));
            }
            discountMalls = page.getRecords();
        }
        for(TDiscountMall discountMall : discountMalls){
            voucher.add(discountMall);
        }
        log.info("优惠卷数量:[{}]",voucher.size());
        page.setRecords(voucher);
        return APIEntity.success(page);
    }

    /**
     * 招商加盟轮播
     * @param
     * @return
     */
    @ApiOperation("客户领取优惠卷")
    @GetMapping("/get/receive")
    public APIEntity getReceive(@RequestAttribute("JwtUserId") Integer id,Integer couponId){
        TCustomer tCustomer = customerService.getById(id);
        if(tCustomer == null){
            return APIEntity.fail("当前用户不存在，请重新登陆");
        }
        TDiscountMall discountMall = createVoucherService.getById(couponId);
        log.info("优惠卷信息:[{}]",discountMall);
        if(discountMall == null){
            return APIEntity.fail("当前优惠卷已领取完");
        }
        if(LocalDate.now().isAfter(discountMall.getEndDate())){
            log.info("!!!!!!!!!!!!!!!!!!!!!!!!!:[{}]",Duration.between(discountMall.getEndDate(),LocalDateTime.now()).toHours());
            return APIEntity.fail("优惠卷领取时间已结束");
        }
        TDiscountRecord tReceiveRecord = receiveRecordService.getOne(new QueryWrapper<TDiscountRecord>().eq("dis_id",discountMall.getDisId()).eq("usage_status","未使用"));
        if(tReceiveRecord != null){
            return APIEntity.fail("您已领取当前优惠卷");
        }
        if(!"发放中".equals(discountMall.getDisState())){
            return APIEntity.fail("当前优惠卷已暂停发放");
        }else {
            if(receiveRecordService.saveRecord(discountMall,tCustomer)){
                discountMall.setReceiveNum(discountMall.getReceiveNum()+1);
                createVoucherService.updateById(discountMall);
            }
        }
        return APIEntity.success("领取成功");
    }

}

