package com.happy.service.impl;

import com.happy.Model.AdminManager;
import com.happy.Model.Hotel;
import com.happy.Model.HotelCoupon;
import com.happy.Model.HotelCouponStatus;
import com.happy.Until.DateUtil;
import com.happy.dao.HotelCouponDao;
import com.happy.dao.HotelDao;
import com.happy.dto.IPage;
import com.happy.service.BookService;
import com.happy.service.HotelCoupomService;
import com.happy.service.HotelCoupomStatusService;
import com.happy.vo.*;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service("hotelCoupomService")
public class HotelCoupomImplService implements HotelCoupomService {

    @Resource
    private HotelCouponDao hotelCouponDao;

    @Resource
    public HotelDao hotelDao;

	@Resource
    public HotelCoupomStatusService hotelCoupomStatusService;

    @Resource
    public BookService bookService;

    @Override
    public int insert(HotelCoupon hotelCoupon) {
        return hotelCouponDao.insert(hotelCoupon);
    }

    @Override
    public int update(HotelCoupon hotelCoupon) {
        return hotelCouponDao.update(hotelCoupon);
    }

    @Override
    public int delete(Integer id) {
        return hotelCouponDao.delete(id);
    }

    @Override
    public HotelCoupon getById(String id) {
        return hotelCouponDao.getById(id);
    }

    @Override
    public IPage<HotelCoupon> queryPage(String sqlx, int page, int rows) {
        IPage<HotelCoupon> iPage = new IPage();
        List<HotelCoupon> hotelCouponList = hotelCouponDao.queryPage(sqlx,page,rows);
        hotelCouponList.forEach(hotelCoupon -> {
            String hotelIds = hotelCoupon.getHotelIds();
            String sql = " and id in ( " + hotelIds + " )";
            List<Hotel> hotels = hotelDao.queryList(sql);
            if (hotels!=null){
                StringBuilder stringBuilder = new StringBuilder();
                hotels.forEach(hotel -> {
                    stringBuilder.append(hotel.getHname()).append(",");
                });
                String hotelNames = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
                hotelCoupon.setHotelNames(hotelNames);
            }
        });
        int total = hotelCouponDao.queryTotal(sqlx);
        iPage.setPageList(hotelCouponList);
        iPage.setPage(page);
        iPage.setTotalPage( (int)Math.ceil((double)total/rows));
        iPage.setRows(rows);
        iPage.setTotal(total);
        return iPage;
    }

    @Override
    public List<HotelCoupon> queryList(String sqlx) {
        return hotelCouponDao.queryList(sqlx);
    }

    @Override
    public  int updateExpire() {
        return hotelCouponDao.updateExpire();
    }

    @Override
    public int updateLapse(List<String> coupomIds) {
        return hotelCouponDao.updateLapse(coupomIds);
    }


    /**
     * ��ȯ����
     *
     * @param date
     * @return
     */
    @Override
    public IPage<CouponCollectionVo> couponCollection(String date, int page, int rows,String userId) {
        IPage<CouponCollectionVo> iPage = new IPage();
        List<CouponCollectionVo> hotelCouponList = hotelCouponDao.couponCollection(date, page, rows,userId);
        if (hotelCouponList!=null&&hotelCouponList.size()>0) {
            for (CouponCollectionVo couponCollectionVo : hotelCouponList) {
                if (couponCollectionVo != null) {
                    Integer limitNumber = couponCollectionVo.getLimitNumber();
                    if (limitNumber == null) {
                        limitNumber = 0;
                    }
                    Integer totalCount = couponCollectionVo.getTotalCount();
                    if (totalCount == null) {
                        totalCount = 0;
                    }
                    Integer remainderNumber = couponCollectionVo.getRemainderNumber();
                    if (remainderNumber == null) {
                        remainderNumber = 0;
                    }
                    if (limitNumber > totalCount && remainderNumber > 0) {
                        couponCollectionVo.setClaimStatus(1);
                    } else if (remainderNumber==0){
                        couponCollectionVo.setClaimStatus(3);
                    }else {
                        couponCollectionVo.setClaimStatus(2);
                    }
                }
            }
        }

        int total = hotelCouponDao.couponCollectionTotal(date);
        iPage.setPageList(hotelCouponList);
        iPage.setPage(page);
        iPage.setTotalPage((int) Math.ceil((double) total / rows));
        iPage.setRows(rows);
        iPage.setTotal(total);
        return iPage;

    }

    /**
     * ָ������
     *
     * @param hotelIds
     * @return
     */
    @Override
    public DesignatedHotelVo designatedHotel(String hotelIds) {
        return hotelCouponDao.designatedHotel(hotelIds);
    }

    /**
     * ͨ���Ż�ȯid�ж��Ƿ������ȯ
     *
     * @param complaintId
     * @return
     */
    @Override
    public Boolean quota(String complaintId,String userId) {

        QuotaVo quotaVo = hotelCouponDao.quota(complaintId,userId);

        if (quotaVo != null) {
            Integer limitNumber = quotaVo.getLimitNumber();
            if (limitNumber == null) {
                limitNumber = 0;
            }
            Integer totalCount = quotaVo.getTotalCount();
            if (totalCount == null) {
                totalCount = 0;
            }
            Integer remainderNumber = quotaVo.getRemainderNumber();
            if (remainderNumber == null) {
                remainderNumber = 0;
            }
            if (limitNumber > totalCount && remainderNumber > 0) {
                return true;
            } else {
                return false;
            }
        }

        return true;
    }

    /**
     * ��ȡ�Ż�ȯ
     *
     * @param hotelCouponStatus
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, readOnly = false)
    public int coupon(HotelCouponStatus hotelCouponStatus) {
        try {
            //        �����޸��Ż�ȯ������
            int num = hotelCouponDao.updateRemainderNumber(hotelCouponStatus.getComplaintId(), hotelCouponStatus.getModifyDate());
            num = hotelCoupomStatusService.insert(hotelCouponStatus);
            return num;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;

    }

    @Override
    public IPage<CardCouponPageVo> cardCouponPage(String types, String userId, int page, int rows) {
        IPage<CardCouponPageVo> iPage = new IPage();
        List<CardCouponPageVo> hotelCouponList = hotelCouponDao.cardCouponPage(types, userId, page, rows);
        if (hotelCouponList!=null && hotelCouponList.size()>0) {
            for (CardCouponPageVo cardCouponPageVo : hotelCouponList) {
                Integer effectiveType = cardCouponPageVo.getEffectiveType();
                if (2==effectiveType) {
                    //生效天数
                    Integer effectiveDay = cardCouponPageVo.getEffectiveDay();
                    //失效时间天数
                    Integer effectiveLoseDay = cardCouponPageVo.getEffectiveLoseDay();
                    //领券时间
                    String dateTime = cardCouponPageVo.getDateTime();
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    String substring = dateTime.substring(0, 19);
                    LocalDateTime parse = LocalDateTime.parse(substring, dateTimeFormatter);
//                    开始时间
                    LocalDateTime localDateTime = parse.plusDays(effectiveDay);
                    cardCouponPageVo.setEffectiveStartDate(localDateTime.format(dateTimeFormatter));
//                    结束时间
                    LocalDateTime localDateTime1 = localDateTime.plusDays(effectiveLoseDay);
                    cardCouponPageVo.setEffectiveEndDate(localDateTime1.format(dateTimeFormatter));
                }
            }
        }

        int total = hotelCouponDao.cardCouponPageTotal(types, userId);
        iPage.setPageList(hotelCouponList);
        iPage.setPage(page);
        iPage.setTotalPage((int) Math.ceil((double) total / rows));
        iPage.setRows(rows);
        iPage.setTotal(total);
        return iPage;
    }

    @Override
    public IPage<UsefulCouponVo> usefulCoupon(String hotelId, String userId, int page, int rows,Double totalPrice) {
        IPage<UsefulCouponVo> iPage = new IPage();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //判断当前时间是否在有效期内
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(dateTimeFormatter);
        List<UsefulCouponVo> hotelCouponList = hotelCouponDao.usefulCoupon(hotelId, userId, page, rows,totalPrice,format);

        int total = hotelCouponDao.usefulCouponTotal(hotelId, userId,totalPrice,format);

        iPage.setPageList(hotelCouponList);
        iPage.setPage(page);
        iPage.setTotalPage((int) Math.ceil((double) total / rows));
        iPage.setRows(rows);
        iPage.setTotal(total);
        return iPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int useCoupons( HotelCoupon hotelCoupon, HotelCouponStatus hotelCouponStatus) {
        int update = hotelCouponDao.update(hotelCoupon);
        int u=hotelCoupomStatusService.update(hotelCouponStatus);

        if (update>0&&u>0) {
            return update;
        }
        return 0;
    }

    @Override
    public int updatReversedNumber(HotelCoupon hotelCoupon) {
        return hotelCouponDao.updatReversedNumber(hotelCoupon);
    }

    @Override
    public List<CouponModel> getCoupon(String strs){
        return hotelCouponDao.getCoupon(strs);
    }

    @Override
    public IPage<HotelCoupon> advertisingCouponPage(String sqlx, Integer page, Integer rows) {

        IPage<HotelCoupon> iPage = new IPage();
        List<HotelCoupon> hotelCouponList = hotelCouponDao.advertisingCouponPage(sqlx,page,rows);

        if (hotelCouponList!=null && hotelCouponList.size()>0) {

            hotelCouponList.forEach(hotelCoupon -> {
                String hotelIds = hotelCoupon.getHotelIds();
                String sql = " and id in ( " + hotelIds + " )";
                List<Hotel> hotels = hotelDao.queryList(sql);
                if (hotels != null) {
                    StringBuilder stringBuilder = new StringBuilder();
                    hotels.forEach(hotel -> {
                        stringBuilder.append(hotel.getHname()).append(",");
                    });
                    String hotelNames = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
                    hotelCoupon.setHotelNames(hotelNames);
                }
            });
        }
        int total = hotelCouponDao.advertisingCouponPageTotal(sqlx);
        iPage.setPageList(hotelCouponList);
        iPage.setPage(page);
        iPage.setTotalPage( (int)Math.ceil((double)total/rows));
        iPage.setRows(rows);
        iPage.setTotal(total);
        return iPage;



    }

}
