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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.utils.StringUtils;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;


@Api(tags = {"优惠商城相关接口"})
@RestController
@Slf4j
@RequestMapping("/api/discount")
@RequiredArgsConstructor
public class DiscountApi extends ApiController {
    final ITCustomerService customerService;
    final ITDiscountMallService discountMallService;
    final ITDiscountRecordService discountRecordService;
    final ITDiscountPayService discountPayService;
    final ITDiscountPatternService discountPatternService;
    final ITOrderService orderService;

    /**
     * 优惠商城
     * 优惠列表
     * 根据消费类型查询所属优惠
     * @return
     */

    @ApiOperation("优惠商城")
    @GetMapping("/get/grant/type")
    @ApiOperationSupport(ignoreParameters = {"id","records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="disType",value="优惠类型(立减卷、满减卷、折扣卡、会员卡)",dataType="String", paramType = "query"),
            @ApiImplicitParam(name="consType",value="消费类型（会员,急送,快递,跨城,拉货）",dataType="String", paramType = "query"),
            @ApiImplicitParam(name="receiveMethod",value="领取方式（充值发放、免费赠送、后台方法）",dataType="String", paramType = "query")})
    public APIEntity getDisByGrantType(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id ,String disType,String receiveMethod,String consType){
        TCustomer tCustomer = customerService.getById(id);
        if (StringUtils.isBlank(receiveMethod)){
            return APIEntity.fail("优惠卷领取方式不能为空！");
        }
        List<TDiscountMall>  discountMalls=null;
        TCustomer customer = customerService.getById(id);
        if(customer != null){
            if(customer.getCustomerType().equals("商家用户") || StringUtils.isNotBlank(customer.getTemplateId())){
                return APIEntity.fail("绑定模板或申请商家的用户无法领取优惠！");
            }
        }
        if(StringUtils.isNotBlank(tCustomer.getTemplateId())){
            return APIEntity.fail("优惠商城为空！");
        }
        switch (receiveMethod){
            case "免费赠送":
                List<Object> ids = discountRecordService.listObjs(new QueryWrapper<TDiscountRecord>().select("dis_id").last("WHERE customer_id="+id+" AND receive_method=\"免费赠送\" AND TO_DAYS(collection_time) = TO_DAYS(\""+LocalDate.now()+"\")"));
                log.info("集合长度：{}",ids.size());
                if(ids.size()<1){
                    discountMalls = discountMallService.list(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method",receiveMethod));break;
                }else {
                    discountMalls = discountMallService.list(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method",receiveMethod).notIn("dis_id",ids));break;
                }
            case "充值发放":
                discountMalls = discountMallService.list(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("dis_type",disType).eq("cons_type",consType).eq("receive_method",receiveMethod));break;
            default:
                return null;
        }
        if(discountMalls.size()<1){
            return APIEntity.fail("优惠商城为空！");
        }
        return APIEntity.success(discountMalls);
    }

    /**
     * 客户使用时查询优惠
     * @param id
     * @return
     * @throws IOException
     */
    @ApiOperation("客户下单时查询未使用优惠卷")
    @GetMapping("/customer/order/get")
    @ApiImplicitParams({
            @ApiImplicitParam(name="useType",value="消费类型（同城急送,同城快递,跨城拉货）",dataType="String", paramType = "query")})
    public APIEntity customerByOrderReceive(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,String useType){
        if (StringUtils.isBlank(useType)){
            return APIEntity.fail("优惠卷消费类型不能为空！");
        }
        List<TDiscountRecord> discountRecords = null;
        TCustomer customer = customerService.getById(id);
        if(customer != null){
            if(customer.getCustomerType().equals("商家用户") || StringUtils.isNotBlank(customer.getTemplateId())){
                return APIEntity.success(discountRecords);
            }
        }
        switch (useType){
            case "同城急送":
                discountRecords = discountRecordService.list(new QueryWrapper<TDiscountRecord>().eq("customer_id",id).eq("usage_status","未使用").eq("cons_type","急送"));break;
            case "同城快递":
                discountRecords = discountRecordService.list(new QueryWrapper<TDiscountRecord>().eq("customer_id",id).eq("usage_status","未使用").eq("cons_type","快递"));break;
            case "跨城拉货":
                discountRecords = discountRecordService.list(new QueryWrapper<TDiscountRecord>().eq("customer_id",id).eq("usage_status","未使用").in("cons_type","跨城","拉货"));break;
            default:
                return null;
        }
        if(discountRecords.size()<1){
            return APIEntity.success(discountRecords);
        }
        for(TDiscountRecord discountRecord : discountRecords){
            if(LocalDate.now().isAfter(discountRecord.getEndDate())){
                discountRecordService.updateById(discountRecord.setUsageStatus("已过期"));
            }
        }
        return APIEntity.success(discountRecords);
    }

    /**
     * 客户购买优惠卷时立即使用
     * @param
     * @return
     */

    @ApiOperation("客户购买优惠卷时立即使用")
    @GetMapping("/customer/get/by/dis")
    public APIEntity getCustomerByDis(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,Integer disId){
        TDiscountRecord discountRecord = discountRecordService.getOne(new QueryWrapper<TDiscountRecord>().last("WHERE customer_id="+id+" AND dis_id="+disId+" AND TO_DAYS(collection_time) = TO_DAYS(\""+ LocalDateTime.now()+"\") LIMIT 1"));
        if(discountRecord == null){
            return APIEntity.success("该用户未购买此优惠卷！");
        }
        return APIEntity.success(discountRecord);
    }

    /**
     * 用户领取、购买的优惠记录
     * @param
     * @return
     */

    @ApiOperation("客户会员卡展示")
    @GetMapping("/customer/get/member/display")
    public APIEntity memberDisplay(@RequestAttribute("JwtUserId") Integer id){
        TDiscountRecord discountRecord = discountRecordService.getOne(new QueryWrapper<TDiscountRecord>().eq("customer_id",id).eq("dis_type","会员卡").eq("usage_status","使用中"));
        if(discountRecord == null){
            return APIEntity.success("该用户未开通会员！").setMessage("未开通");
        }
        return APIEntity.success(discountRecord);
    }

    /**
     * 已领取并未使用的张数
     * @param
     * @return
     */

    @ApiOperation("已领取并未使用的张数")
    @GetMapping("/get/receive/dis/num")
    public APIEntity getDisNum(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id){
        List<TDiscountRecord>  discountRecords= discountRecordService.list(new QueryWrapper<TDiscountRecord>().eq("customer_id",id).eq("usage_status","未使用").notIn("dis_type","会员卡"));
        return APIEntity.success(discountRecords.size());
    }

    /**
     * 我的票卷
     * @param
     * @return
     */

    @ApiOperation("我的票卷")
    @GetMapping("/customer/get/receive/dis")
    public APIEntity customerGetDis(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id, String usageStatus){
        if (StringUtils.isBlank(usageStatus)){
            return APIEntity.fail("查询参数为空！");
        }
        List<TDiscountRecord>  discountRecords;
        switch (usageStatus){
            case "未使用":
                discountRecords = discountRecordService.list(new QueryWrapper<TDiscountRecord>().eq("customer_id",id).eq("usage_status",usageStatus).notIn("dis_type","会员卡"));break;
            case "已使用":
                discountRecords = discountRecordService.list(new QueryWrapper<TDiscountRecord>().eq("customer_id",id).eq("usage_status",usageStatus).notIn("dis_type","会员卡"));break;
            case "已过期":
                discountRecords = discountRecordService.list(new QueryWrapper<TDiscountRecord>().eq("customer_id",id).eq("usage_status",usageStatus).notIn("dis_type","会员卡"));break;
            default:
                return APIEntity.fail("无法识别参数usageStatus");
        }
        return APIEntity.success(discountRecords);
    }

    /**
     * 优惠弹框接口
     * @param
     * @return
     */

    @ApiOperation("优惠弹框接口")
    @GetMapping("/get/dis/frame")
    public APIEntity getVoucherBulletFrame(@RequestAttribute("JwtUserId") Integer id) throws  ParseException {
        TCustomer tCustomer = customerService.getById(id);
        List<TDiscountMall> discountMalls;
        byte[] b = new byte[1024];
        if(tCustomer == null){
            return APIEntity.fail("当前用户不存在，请重新登陆");
        }
        if(StringUtils.isNotBlank(tCustomer.getTemplateId())){
            return APIEntity.fail("优惠商城为空！");
        }
        if(discountRecordService.getWhetherMember(id)){
            log.info("当前用户是否为会员：{}",discountRecordService.getWhetherMember(id));
            return APIEntity.success("未设置弹框");
        }
        discountRecordService.updateOverdue(id);//将客户已过期的数据
        List<Object> disIds = discountRecordService.listObjs(new QueryWrapper<TDiscountRecord>().select("dis_id").last("WHERE customer_id="+id+" AND TO_DAYS(collection_time) = TO_DAYS(\""+LocalDate.now()+"\")"));
        if(disIds.size()<1){
            discountMalls = discountMallService.list(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","免费赠送").eq("dis_mode","弹框"));
        }else {
            discountMalls = discountMallService.list(new QueryWrapper<TDiscountMall>().eq("dis_state","发放中").eq("receive_method","免费赠送").eq("dis_mode","弹框").notIn("dis_id",disIds));
        }
        if(discountMalls.size()<1){
            log.info("当前可弹出优惠数量：{}",discountMalls.size());
            return APIEntity.success("未设置弹框");
        }
        for(TDiscountMall discountMall : discountMalls){
            log.info("优惠卷id：{}",discountMall.getDisId());
            //List<TOrder> orderList = orderService.list(new QueryWrapper<TOrder>().eq("order_status","已完成").eq("player_id",tCustomer.getCustomerId()));
            if(tCustomer.getOrderFrequency()<1 && "新客户".equals(discountMall.getGrantType())){
                return APIEntity.success(discountMall);
            }
            if(tCustomer.getOrderFrequency()>1 && "老客户".equals(discountMall.getGrantType())){
                return APIEntity.success(discountMall);
            }
            if("全部".equals(discountMall.getGrantType()) && tCustomer.getTemplateId()==null){
                return APIEntity.success(discountMall);
            }
        }
        return APIEntity.fail("没有设置需要弹框的优惠卷");
    }

    /**
     * 客户购买优惠支付接口
     * @param id
     * @param disId
     * @param request
     * @return
     * @throws Exception
     */

    @ApiOperation("客户购买/领取优惠支付接口")
    @GetMapping("/order/payment")
    @ApiImplicitParams({})
    public APIEntity insertOrderPayment(@ApiIgnore("id") @RequestAttribute("JwtUserId") Integer id,Integer disId,String type,HttpServletRequest request) throws Exception {
        TDiscountMall discountMall = discountMallService.getById(disId);
        TCustomer customer = customerService.getById(id);
        if(discountMall==null){
            return APIEntity.success("当前优惠卷已领取完！");
        }
        /*if(StringUtils.isBlank(customer.getCustomerPhone())){
            return APIEntity.fail("账号不存在请登录后领取！").setMessage("账号不存在请登录后领取！");
        }*/
        log.info("要领取或购买的优惠id：{},用户id：{},优惠卷名：{}，领取方式：{}",disId,id,discountMall.getDisName(),discountMall.getReceiveMethod());
        switch (discountMall.getReceiveMethod()){
            case "免费赠送":
                TDiscountRecord receiveRecord = discountRecordService.getOne(new QueryWrapper<TDiscountRecord>().last("WHERE customer_id="+id+" AND dis_id="+disId+" AND TO_DAYS(collection_time) = TO_DAYS(\""+LocalDate.now()+"\")"));
                if(receiveRecord != null){
                    return APIEntity.fail().setMessage("免费优惠卷每天只能领取一张");
                }
                discountPayService.handleDiscountService(null,null,null,disId,id);
                return APIEntity.success("领取成功").setMessage("领取成功");
            case "充值发放":
                if("会员卡".equals(discountMall.getDisType())){
                    log.info("当前用户是否为会员：{}",discountRecordService.getWhetherMember(id));
                    if(discountRecordService.getWhetherMember(id)){
                        return APIEntity.success().setMessage("您已经开通会员，请不要重复开通！");
                    }
                }
                discountMall.setType(type);
                return discountPayService.getPayByDis(discountMall,id,request);
            default:
                return null;
        }
    }

}

