package com.happy.action;

import com.happy.Model.Booking;
import com.happy.Model.HotelCoupon;
import com.happy.Model.HotelCouponStatus;
import com.happy.Until.DateUtil;
import com.happy.Until.Func;
import com.happy.Until.GetHttpParam;
import com.happy.Until.ResUtil;
import com.happy.dto.*;
import com.happy.service.*;
import com.happy.vo.*;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

public class AppHotelCouponAction extends ActionSupport implements ServletRequestAware {
    public HttpServletRequest request;

    public HttpServletResponse response;

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    @Resource
    HotelCoupomService hotelCoupomService;

    public int page; // 当前页
    public int rows;// 每页显示的行数rows
    public String types; //状态，1,2显示全部，1带金券，2折扣券

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public String getTypes() {
        return types;
    }

    public void setTypes(String types) {
        this.types = types;
    }

    public String hotelIds;

    public String getHotelIds() {
        return hotelIds;
    }

    public void setHotelIds(String hotelIds) {
        this.hotelIds = hotelIds;
    }

    public String userId;

    public int type;


    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    private String hotelId;

    public String getHotelId() {
        return hotelId;
    }

    public void setHotelId(String hotelId) {
        this.hotelId = hotelId;
    }

    private String complaintId;
    private String bookingId;

    public String getComplaintId() {
        return complaintId;
    }

    public void setComplaintId(String complaintId) {
        this.complaintId = complaintId;
    }

    public String getBookingId() {
        return bookingId;
    }

    public void setBookingId(String bookingId) {
        this.bookingId = bookingId;
    }

    public Double totalPrice;

    public Double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(Double totalPrice) {
        this.totalPrice = totalPrice;
    }

    @Resource
    BookService bookService;

    @Resource
    HotelCoupomStatusService hotelCoupomStatusService;

    /**
     * 我的卡券
     *
     * @return
     */
    public JSONObject cardCouponPage() {
        JSONObject jsonObject = new JSONObject();

        System.out.println("进入我的卡券接口");

        if (Func.checkNull(types) || Func.checkNull(userId)) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "未传入usersId数据---complaintPage");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        System.out.println("进入我的卡券接口1");
        if (page <= 0 || rows <= 0) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "未传入page,rows数据---evaluatePage");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        System.out.println("进入我的卡券接口2");
        IPage<CardCouponPageVo> iPage = hotelCoupomService.cardCouponPage(types, userId, page, rows);

        List<String> strs = new ArrayList<>();
        List<CardCouponPageVo> pageList = iPage.getPageList();
        if (pageList != null && pageList.size() > 0) {
            for (CardCouponPageVo data : iPage.getPageList()) {
                if (!data.getHotelIds().contains(",") || data.getHotelIds().contains("-1")) {
                    strs.add(data.getHotelIds());
                }
            }
        }
        if (strs.size() > 0) {
            String hotelIds = StringUtils.join(strs, ",");
            List<CouponModel> coupons = hotelCoupomService.getCoupon(hotelIds);
            if (coupons != null && coupons.size() > 0) {
                for (CardCouponPageVo data : iPage.getPageList()) {
                    if (!data.getHotelIds().contains(",") || data.getHotelIds().contains("-1")) {
                        Optional<CouponModel> d = coupons.stream().filter(e -> e.getId().equals(data.getHotelIds())).findFirst();
                        if (d != null && d.isPresent()) {
                            data.setTown(d.get().getName());
                        }
                    }
                }
            }
        }


        System.out.println("进入我的卡券接口3");
        jsonObject.put("code", 200);
        jsonObject.put("success", true);
        jsonObject.put("message", "成功");
        jsonObject.put("page", iPage);
        ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }

    /**
     * 领券中心
     *
     * @return
     */
    public JSONObject couponCollection() {
        JSONObject jsonObject = new JSONObject();
        if (page <= 0 || rows <= 0 || Func.checkNull(userId)) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "未传入page,rows数据---evaluatePage");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }


        String date = DateUtil.getFormatPaternDate(new Date());
        IPage<CouponCollectionVo> iPage = hotelCoupomService.couponCollection(date, page, rows, userId);
        jsonObject.put("code", 200);
        jsonObject.put("success", true);
        jsonObject.put("message", "成功");
        jsonObject.put("page", iPage);
        ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;

    }


    /**
     * 指定名宿
     *
     * @return
     */
    public JSONObject designatedHotel() {
        JSONObject jsonObject = new JSONObject();
        if (Func.checkNull(hotelIds)) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "未传入hotelIds数据---designatedHotel");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
//根据id找对应的名字
        DesignatedHotelVo vo = hotelCoupomService.designatedHotel(hotelIds);
        jsonObject.put("code", 200);
        jsonObject.put("success", true);
        jsonObject.put("message", "成功");
        jsonObject.put("data", vo);
        ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }


    /**
     * 领券
     *
     * @return
     */
    public JSONObject getCoupon() {
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();

        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
        if (json == null) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "缺少数据---getCoupon");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        HotelCouponStatus hotelCouponStatus = com.alibaba.fastjson.JSONObject.parseObject(json.toString(), HotelCouponStatus.class);
        String complaintId = hotelCouponStatus.getComplaintId();
        if (hotelCouponStatus == null || Func.checkNull(complaintId)) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "缺少数据---getCoupon");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        String userId = hotelCouponStatus.getUserId();
//        通过优惠券id判断领券的张数是否大于等于每人限领次数,并且剩余张数不能为0
        Boolean quota = hotelCoupomService.quota(complaintId, userId);
        if (!quota) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "此券领取次数已达上限");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

//        领取优惠券
        int num = hotelCoupomService.coupon(hotelCouponStatus);
        if (num > 0) {
            jsonObject.put("code", 200);
            jsonObject.put("message", "领取成功");
            jsonObject.put("success", true);
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        jsonObject.put("message", "未知异常");
        jsonObject.put("success", false);
        jsonObject.put("code", 205);
        ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }


    /**
     * 可用优惠券
     *
     * @return
     */
    public JSONObject usefulCoupon() {
        JSONObject jsonObject = new JSONObject();

        if (Func.checkNull(hotelId) || Func.checkNull(userId) || totalPrice == null) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "缺少数据hotelId,userId,totalPrice---usefulCoupon");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        if (page <= 0 || rows <= 0) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "未传入page,rows数据---usefulCoupon");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        IPage<UsefulCouponVo> iPage = hotelCoupomService.usefulCoupon(hotelId, userId, page, rows, totalPrice);

        jsonObject.put("code", 200);
        jsonObject.put("success", true);
        jsonObject.put("message", "成功");
        jsonObject.put("page", iPage);
        ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;


    }


    /**
     * 使用优惠券
     *
     * @return
     */
    public JSONObject useCoupons() {
        JSONObject jsonObject = new JSONObject();

        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
        if (json == null) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "缺少数据---getCoupon");

            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        UseCouponsDto dto = com.alibaba.fastjson.JSONObject.parseObject(json.toString(), UseCouponsDto.class);

        if (dto == null) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "缺少数据---useCoupons");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        String id = dto.getId();
        Double totalPrice = dto.getTotalPrice();
        String complaintId = dto.getComplaintId();

        if (Func.checkNull(complaintId) && totalPrice <= 0 && totalPrice == null && Func.checkNull(id)) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "缺少数据id,complaintId,bookingId---useCoupons");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        UseCouponsVo useCouponsVo = new UseCouponsVo();
        useCouponsVo.setComplaintId(complaintId);
        useCouponsVo.setId(id);
//        优惠券
        HotelCoupon hotelCoupon = hotelCoupomService.getById(complaintId);

//        优惠券状态，1.优惠卷，需看是否满足满减 2.折扣卷，需判断是否大于最大减免金额
        Integer type1 = hotelCoupon.getType();
//          订单金额
        BigDecimal houseTotalPriceBigDecimal = new BigDecimal(totalPrice);

        useCouponsVo.setCapitalSum(totalPrice);
        if (1 == type1) {
//            满减金额
            Double meetPrice = hotelCoupon.getMeetPrice();
            BigDecimal meetPriceBigDecimal = new BigDecimal(meetPrice);

            if (meetPrice > totalPrice) {
                BigDecimal subtract = meetPriceBigDecimal.subtract(houseTotalPriceBigDecimal);
                double v = subtract.doubleValue();
                jsonObject.put("code", 400);
                jsonObject.put("success", false);
                jsonObject.put("message", "还差" + v + "元可使用");
                ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
                return null;
            }
//            减免金额
            Double deductionPrice = hotelCoupon.getDeductionPrice();
            BigDecimal deductionPriceBigDecimal = new BigDecimal(deductionPrice);

//            实付金额
            BigDecimal subtract = houseTotalPriceBigDecimal.subtract(deductionPriceBigDecimal);


            useCouponsVo.setTypeName("优惠卷");
            useCouponsVo.setHotelCouponName(hotelCoupon.getName());
            useCouponsVo.setDiscountAmount(deductionPrice);

        } else if (2 == type1) {
            //            满减金额
            Double meetPrice = hotelCoupon.getMeetPrice();
            if (meetPrice == null || meetPrice < 0) {
                meetPrice = 0.0;
            }
            BigDecimal meetPriceBigDecimal = new BigDecimal(meetPrice);

            if (meetPrice > totalPrice) {
                BigDecimal subtract = meetPriceBigDecimal.subtract(houseTotalPriceBigDecimal);
                double v = subtract.doubleValue();
                jsonObject.put("code", 400);
                jsonObject.put("success", false);
                jsonObject.put("message", "还差" + v + "元可使用");
                ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
                return null;
            }

//            享受的折扣
            Double rebatePrice = hotelCoupon.getRebatePrice();
            BigDecimal rebatePriceBigDecimal = new BigDecimal(rebatePrice / 10);

//            最大减免金额
            Double maxDeduction = hotelCoupon.getMaxDeduction();
            BigDecimal maxDeductionBigDecimal = new BigDecimal(maxDeduction);

//            折扣后的价格
            BigDecimal bigDecimal = houseTotalPriceBigDecimal.multiply(rebatePriceBigDecimal).setScale(2, BigDecimal.ROUND_HALF_UP);
            double v = bigDecimal.doubleValue();

//            减去最大折扣后的价格
            BigDecimal subtract = houseTotalPriceBigDecimal.subtract(maxDeductionBigDecimal);
            double v1 = subtract.doubleValue();

            if (v > v1) {
                BigDecimal subtract1 = houseTotalPriceBigDecimal.subtract(bigDecimal);
                useCouponsVo.setDiscountAmount(subtract1.doubleValue());
            } else if (v < v1) {
                useCouponsVo.setDiscountAmount(maxDeduction);
            } else if (v == v1) {
                useCouponsVo.setDiscountAmount(maxDeduction);
            }

            useCouponsVo.setTypeName("折扣卷");
            useCouponsVo.setHotelCouponName(hotelCoupon.getName());


        } else {
            jsonObject.put("message", "未知异常");
            jsonObject.put("success", false);
            jsonObject.put("code", 205);
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        jsonObject.put("code", 200);
        jsonObject.put("success", true);
        jsonObject.put("message", "成功");
        jsonObject.put("data", useCouponsVo);
        ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());


        return null;
    }

    /**
     * 锁定优惠券
     *
     * @return
     */
    public JSONObject lockCoupon() {
        JSONObject jsonObject = new JSONObject();

        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
        if (json == null) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "缺少数据---getCoupon");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        CancelUseCouponsDto dto = com.alibaba.fastjson.JSONObject.parseObject(json.toString(), CancelUseCouponsDto.class);

        if (dto == null) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "缺少数据---cancelUseCoupons");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        //无优惠券金额
        Double discountAmount = dto.getCapitalSum();
//        优惠券id
        String complaintId = dto.getComplaintId();
//        领取的优惠券id
        String id = dto.getId();

        if (discountAmount != null && discountAmount > 0 && Func.checkNull(complaintId) && Func.checkNull(id)) {
            jsonObject.put("code", 400);
            jsonObject.put("success", false);
            jsonObject.put("message", "缺少bookingId,discountAmount,complaintId,id数据---cancelUseCoupons");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }


        //        优惠券
        HotelCoupon hotelCoupon = hotelCoupomService.getById(complaintId);

//      领取的优惠
        HotelCouponStatus hotelCouponStatus = hotelCoupomStatusService.getById(id);

        hotelCoupon.setReversedNumber(hotelCoupon.getReversedNumber() + 1);
        hotelCouponStatus.setStatus(2);

        int i = hotelCoupomService.useCoupons(hotelCoupon, hotelCouponStatus);
        if (i > 0) {
            jsonObject.put("code", 200);
            jsonObject.put("success", true);
            jsonObject.put("message", "成功");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        jsonObject.put("message", "未知异常");
        jsonObject.put("success", false);
        jsonObject.put("code", 205);
        ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;

    }


}
