package com.hfkj.service.discount.impl;

import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.RedisUtil;
import com.hfkj.dao.BsDiscountMapper;
import com.hfkj.entity.BsDiscount;
import com.hfkj.entity.BsDiscountExample;
import com.hfkj.entity.BsDiscountUseMer;
import com.hfkj.service.discount.BsDiscountService;
import com.hfkj.service.discount.BsDiscountUseMerService;
import com.hfkj.sysenum.discount.DiscountStatusEnum;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @className: BsDiscountServiceImpl
 * @author: HuRui
 * @date: 2024/3/18
 **/
@Service("discountService")
public class BsDiscountServiceImpl implements BsDiscountService {
    @Resource
    private BsDiscountMapper discountMapper;
    @Resource
    private BsDiscountUseMerService discountUseMerService;
    @Resource
    private RedisUtil redisUtil;
    // 缓存优惠券
    private final static String CACHE_DISCOUNT_KEY = "DISCOUNT:";

    @Override
    public void editData(BsDiscount data) {
        if (data.getId() == null) {
            data.setCreateTime(new Date());
            data.setUpdateTime(new Date());
            discountMapper.insert(data);

            data.setDiscountNo("D"+(10000+data.getId()));
            discountMapper.updateByPrimaryKey(data);
        } else {
            data.setUpdateTime(new Date());
            discountMapper.updateByPrimaryKey(data);
        }
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW,rollbackFor= {RuntimeException.class})
    public void editDiscount(BsDiscount discount) {
        editData(discount);

        // 创建人类型  1：运营   2：商户【油站】
        if (discount.getCreateUserType().equals(2)) {
            if (StringUtils.isNotBlank(discount.getCreateUserMerNo())) {
                discountUseMerService.configUseMer(discount.getDiscountNo(), Collections.singletonList(discount.getCreateUserMerNo()));
            }
        }
        // 加入缓存
        redisUtil.set(CACHE_DISCOUNT_KEY+discount.getDiscountNo(), discount);
    }

    @Override
    public void online(String discountNo) {
        // 查询优惠券详情
        BsDiscount discount = getDetail(discountNo);
        if (discount == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        }
        if (!discount.getStatus().equals(DiscountStatusEnum.status1.getCode())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前状态无法上线");
        }
        discount.setStartTime(new Date());
        discount.setStatus(DiscountStatusEnum.status2.getCode());
        editDiscount(discount);
    }

    @Override
    public void done(String discountNo) {
        // 查询优惠券详情
        BsDiscount discount = getDetail(discountNo);
        if (discount == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        }
        if (!discount.getStatus().equals(DiscountStatusEnum.status2.getCode())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前状态无法下线");
        }
        discount.setRealityEndTime(new Date());
        discount.setStatus(DiscountStatusEnum.status3.getCode());
        editDiscount(discount);
    }

    @Override
    public void delete(String discountNo) {
        // 查询优惠券详情
        BsDiscount discount = getDetail(discountNo);
        if (discount == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        }
        if (!discount.getStatus().equals(DiscountStatusEnum.status1.getCode())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "状态错误");
        }
        discount.setStatus(DiscountStatusEnum.status0.getCode());
        editData(discount);
        // 删除缓存
        redisUtil.del(CACHE_DISCOUNT_KEY+discount.getDiscountNo());
    }

    @Override
    public BsDiscount getDetail(Long id) {
        return discountMapper.selectByPrimaryKey(id);
    }

    @Override
    public BsDiscount getDetail(String discountNo) {
        Object obj = redisUtil.get(CACHE_DISCOUNT_KEY + discountNo);
        if (obj != null) {
            return (BsDiscount) obj;
        }
        BsDiscountExample example = new BsDiscountExample();
        example.createCriteria().andDiscountNoEqualTo(discountNo).andStatusNotEqualTo(DiscountStatusEnum.status0.getCode());
        List<BsDiscount> list = discountMapper.selectByExample(example);
        if (!list.isEmpty()) {
            BsDiscount discount = list.get(0);
            redisUtil.set(CACHE_DISCOUNT_KEY + discountNo, discount);
            return discount;
        }
        return null;
    }

    @Override
    public List<BsDiscount> getList(Map<String, Object> param) {
        BsDiscountExample example = new BsDiscountExample();
        BsDiscountExample.Criteria criteria = example.createCriteria().andStatusNotEqualTo(DiscountStatusEnum.status0.getCode());

        if (StringUtils.isNotBlank(MapUtils.getString(param, "discountName"))) {
            criteria.andDiscountNameLike("%"+MapUtils.getString(param, "discountName")+"%");
        }

        if (MapUtils.getInteger(param, "discountType") != null) {
            criteria.andDiscountTypeEqualTo(MapUtils.getInteger(param, "discountType"));
        }

        if (MapUtils.getInteger(param, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(param, "status") );
        }

        if (MapUtils.getInteger(param, "createUserType") != null) {
            criteria.andCreateUserTypeEqualTo(MapUtils.getInteger(param, "createUserType"));
        }

        if (MapUtils.getInteger(param, "createUserId") != null) {
            criteria.andCreateUserIdEqualTo(MapUtils.getLong(param, "createUserId") );
        }

        if (MapUtils.getLong(param, "endTimeE") != null) {
            criteria.andEndTimeLessThanOrEqualTo(new Date(MapUtils.getLong(param, "endTimeE")));
        }

        example.setOrderByClause("create_time desc");
        return discountMapper.selectByExample(example);
    }
}
