package com.platform.controller;

import com.github.pagehelper.PageHelper;
import com.platform.annotation.CanUserUpdateRecord;
import com.platform.entity.CouponEntity;
import com.platform.entity.Result;
import com.platform.enums.ResultCodeEnum;
import com.platform.exception.CommonBaseException;
import com.platform.service.CouponService;
import com.platform.service.UserCouponService;
import com.platform.utils.*;
import com.platform.vo.CouponRequestVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 优惠券Controller
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-19 12:53:26
 */
@RestController
@RequestMapping("coupon")
@Slf4j
public class CouponController extends AbstractController{
    @Autowired
    private CouponService couponService;

    @Autowired
    private UserCouponService userCouponService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @Transactional(rollbackFor = Exception.class)
    public Result list(@RequestBody Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        PageHelper.startPage(query.getPage(), query.getLimit());
        Long userId = getUserId();
        PageUtils pageUtil = new PageUtils(new ArrayList<>(), 0 , query.getLimit(), query.getPage());
        List<Long> roleIdList = getUser().getRoleIdList();
        if (!roleIdList.contains(1L) && !roleIdList.contains(5L)) {
            //通过部门ID过滤数据
            if(null == getDeptId()){
                return Result.success(pageUtil);
            }
            query.put("deptIdList", getDeptId());
        }
        List<CouponEntity> couponList = couponService.queryList(query);
        //更新优惠券的状态，TODO:这里如果优惠券比较多，发放的用户比较多，这里会很慢
        if(!CollectionUtils.isEmpty(couponList)){
            for(CouponEntity couponEntity : couponList){
                checkCouponStatus(couponEntity , query.getLimit());
            }
        }
        int total = couponService.queryTotal(query);
        pageUtil = new PageUtils(couponList , total , query.getLimit(), query.getPage());

        return Result.success( pageUtil);
    }

    @Transactional(rollbackFor = Exception.class)
    public void checkCouponStatus(CouponEntity couponEntity , int limit){
        if(null == couponEntity){
            return;
        }
        //未生效->生效
        if(couponEntity.getUseStartDate().before(new Date()) && couponEntity.getUseEndDate().after(new Date())){
            if(couponEntity.getCouponStatus().compareTo(1) == 0){
                couponEntity.setCouponStatus(2);
                couponService.updateStatus(couponEntity.getId() , 2);
                log.info("优惠券[{}]原为未生效，但当前时间已起始时间，更新优惠券状态为2");
            }
        }
        // 生效中->过期
        if(couponEntity.getUseEndDate().before(new Date())) {
            //优惠券状态 1 未生效 2 生效中 3 已失效 4 停止发放
            if(couponEntity.getCouponStatus().compareTo(2) == 0 || couponEntity.getCouponStatus().compareTo(1) == 0){
                couponEntity.setCouponStatus(3);
                couponService.updateStatus(couponEntity.getId() , 3);
                log.info("优惠券[{}]原为未过期，但当前时间已过期，更新优惠券状态为3");
                //这里更新用户优惠券使用状态 1. 可用 2. 已用 3. 过期 4、作废
                //TODO:这里如果优惠券发放的人多了，每次获取的页数会比较大的时候，会很慢，需要转移到定时任务不停的去刷新
                userCouponService.updateAllStatusByCouponId(couponEntity.getId() , 3 , limit);
                log.info("优惠券[{}]原为未过期，但当前时间已过期，更新使用状态状态为3" , couponEntity.getId());
            }
        }

    }

    /**
     * 查看优惠券使用明细列表
     */
    @RequestMapping("/useDetailList")
    
    public Result useDetailList(@RequestBody Map<String, Object> params) {
        if(!params.containsKey("couponId")){
            return Result.failure("缺失必要参数couponId");
        }
        //查询列表数据
        Query query = new Query(params);
        PageHelper.startPage(query.getPage(), query.getLimit());
        List<CouponEntity> couponList = couponService.queryUseDetailList(query);
        int total = couponService.queryUseDetailTotal(query);
        PageUtils pageUtil = new PageUtils(couponList ,1, query.getLimit() , query.getPage());

        return Result.success( pageUtil);
    }


    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    
    public Result info(@PathVariable("id") Integer id) {
        CouponEntity coupon = couponService.queryObject(id);

        return Result.success(coupon);
    }

    /**
     * 保存
     */
    @CanUserUpdateRecord
    @RequestMapping("/save")
    
    public Result save(@RequestBody CouponEntity coupon) {

        if(StringUtils.isBlank(coupon.getName())){
            return Result.failure("优惠券名称不能为空");
        }
        if(null == coupon.getBrandId() || StringUtils.isBlank(coupon.getBrandName())){
            return Result.failure("优惠券所属店铺ID或者名称不能为空");
        }
        if(null == coupon.getUseStartDate() || null == coupon.getUseEndDate()){
            return Result.failure("优惠券有效起始日期不能为空");
        }

        Map<String , Object> param = new HashMap<>();
        param.put("name", coupon.getName());
        param.put("brandName", coupon.getBrandName());
        List<CouponEntity> getList = couponService.queryList(param);
        if(!CollectionUtils.isEmpty(getList)){
            return Result.failure("该店铺下同名的优惠券已经存在");
        }
        Date currTime = new Date();
        //优惠券状态 1 未生效 2 生效中 3 已失效 4 停止发放
        if(null == coupon.getCouponStatus()){
            if(coupon.getUseStartDate().after(currTime)){
                coupon.setCouponStatus(1);
            }else if(currTime.after(coupon.getUseStartDate()) && currTime.before(coupon.getUseEndDate())){
                coupon.setCouponStatus(2);
            }else if(currTime.after(coupon.getUseEndDate())){
                coupon.setCouponStatus(3);
            }else{
                log.error("优惠券状态异常，当前日期:{},优惠券使用起始日期:{},优惠券使用截止日期:{}" , currTime,coupon.getUseStartDate() , coupon.getUseEndDate());
            }
        }
        coupon.setEnable(1);
        coupon.setCreateTime(LocalDateTime.now());
        coupon.setUpdateTime(LocalDateTime.now());
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String dateStr = dateTimeFormatter.format(LocalDateTime.now());
        int ramNum = 100 + (int) (Math.random() * 900);
        String couponSn = "HY" + dateStr + ramNum;
        coupon.setCouponSn(couponSn);
        int insert = couponService.save(coupon);
        if(insert !=  1){
            throw new CommonBaseException(ResultCodeEnum.D101 , "新增优惠券失败");
        }

        return Result.success();
    }


    /**
     * 修改
     */
    @CanUserUpdateRecord
    @PostMapping("/update")
    
    public Result update(@RequestBody CouponEntity coupon) {
        couponService.update(coupon);

        return Result.success();
    }

    /**
     * 修改优惠券的状态
     */
    @CanUserUpdateRecord
    @GetMapping("/updateStatus")
    
    public Result updateStatus(@RequestParam(name = "couponId") Integer couponId,
                    @RequestParam(name = "status") Integer status) {
        couponService.updateStatus(couponId , status);

        return Result.success();
    }

    /**
     * 修改优惠券的状态
     */
    @CanUserUpdateRecord
    @PostMapping("/deleteCoupons")
    
    @ResponseBody
    public Result updateStatus(@RequestBody CouponRequestVo couponRequestVo) {

        if(null != couponRequestVo && !CollectionUtils.isEmpty(couponRequestVo.getIdList())){
           int deleteNum =  couponService.deleteCouponBatch(couponRequestVo.getIdList());
           if(deleteNum != couponRequestVo.getIdList().size()){
               log.error("删除的成功的数量跟上送的id数量不一致，回滚");
               throw new CommonBaseException(ResultCodeEnum.D101 , "删除不完整");
           }
        }else{
            return Result.failure("需要删除的id为空");
        }

        return Result.success();
    }



    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public Result queryAll(@RequestBody Map<String, Object> params) {

        List<CouponEntity> list = couponService.queryList(params);

        return Result.success(list);
    }

    /**
     * 按用户、商品下发优惠券
     *
     * @param params
     * @return
     */
    
    @RequestMapping(value = "publish", method = RequestMethod.POST)
    public Result publish(@RequestBody Map<String, Object> params) {
        return couponService.publish(params);
    }
}
