package com.sqx.modules.shopping.service.impl;


import com.sqx.modules.shopping.dao.CouponsJpaRepository;
import com.sqx.modules.shopping.dao.CouponsUserJpaRepository;
import com.sqx.modules.shopping.entity.Coupons;
import com.sqx.modules.shopping.entity.CouponsUser;
import com.sqx.modules.shopping.service.CouponsService;
import com.sqx.modules.shopping.service.CouponsUserService;
import com.sqx.modules.shopping.utils.ExceptionEnum;
import com.sqx.modules.shopping.utils.Result;
import com.sqx.modules.shopping.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class CouponsServiceImpl implements CouponsService {
    @Autowired
    private CouponsJpaRepository jpaRepository;
    @Autowired
    private CouponsUserService couponsUserService;
    @Autowired
    private CouponsUserJpaRepository couponsUserJpaRepository;

    @Override
    public Result findAll(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Coupons> all = jpaRepository.findAll(pageable);
        List<Coupons> list = all.getContent();
        //判断是否有库存且未过期
        for (int i = 0; i < list.size(); i++) {
            Coupons c = list.get(i);
            Integer remainingNumber = c.getRemainingNumber(); //优惠券库存
            String endDay = c.getEndDay(); //过期时间
            if (remainingNumber == 0 || !isTimeOut(endDay)){
                c.setStatus(1);
                Coupons newCoupons = jpaRepository.save(c);
                list.set(i, newCoupons);
            }
        }
        return ResultUtil.success(all);
    }

    @Override
    public Result saveBody(Coupons entity) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        entity.setCreateAt(sdf.format(now));
        entity.setStatus(0);
        entity.setCouponsType(1);
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result updateBody(Coupons entity) {
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result findOne(Long id) {
        return ResultUtil.success(jpaRepository.findById(id).orElse(null));
    }

    @Override
    public Result delete(Long id) {
        jpaRepository.deleteById(id);
        return ResultUtil.success();
    }

    /**
     * 用户点击领取优惠券
     * @param userId 用户id
     * @return
     */
    @Override
    public Result userGetCoupons(Long userId, Long couponsId) {
        Coupons c = jpaRepository.findById(couponsId).orElse(null);
        Integer remainingNumber = c.getRemainingNumber(); //优惠券库存
        String endDay = c.getEndDay(); //过期时间
        if (remainingNumber == 0){
            return ResultUtil.error(ExceptionEnum.COUPONS_ZERO);
        }
        if (!isTimeOut(endDay)){
            return ResultUtil.error(ExceptionEnum.COUPONS_TIME_OUT);
        }
        //获取用户对应当前优惠券的领取次数
        int userCouponsCount = couponsUserJpaRepository.findByCouponsId(couponsId, userId);
        //优惠券限领次数
        int count = c.getGetNumber().intValue();
        if (userCouponsCount >= count){
            return ResultUtil.error(ExceptionEnum.COUPONS_GET_OUT);
        }
        //保存用户领券信息
        CouponsUser s = new CouponsUser();
        s.setCouponsId(c.getId());
        s.setTitle(c.getTitle());
        s.setInstructions(c.getInstructions());
        s.setEndDay(c.getEndDay());
        s.setUserId(userId);
        couponsUserService.saveBody(s);
        //优惠券库存减1
        int number = c.getRemainingNumber().intValue()-1;
        c.setRemainingNumber(number);
        this.updateBody(c);
        return ResultUtil.success();
    }


    /**
     * 用户优惠券列表
     * @param userId 用户id
     * @return
     */
    @Override
    public Result userCoupons(Long userId) {
        List<CouponsUser> list = couponsUserJpaRepository.findAll();
        //判断是否过期
        for (int i = 0; i < list.size(); i++) {
            CouponsUser c = list.get(i);
            String endDay = c.getEndDay(); //过期时间
            if (!isTimeOut(endDay)){
                c.setStatus(1);
            }
        }
        return ResultUtil.success(list);
    }


    /**
     * 判断优惠券是否过期
     * @param endDay 过期时间
     * @return  是否超时 true没有过期 false过期
     */
    public static boolean isTimeOut(String endDay){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            Date finish = sf.parse(endDay);
            Calendar c = Calendar.getInstance();
            c.setTime(finish);
            finish = c.getTime();
            System.out.println(sf.format(finish));
            //过期时间和现在时间比
            return finish.after(new Date());
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

}
