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.dao.BsDiscountPkStockBatchMapper;
import com.hfkj.entity.*;
import com.hfkj.service.discount.*;
import com.hfkj.sysenum.discount.DiscountPkStatusEnum;
import com.hfkj.sysenum.discount.DiscountPkStockCodeStatusEnum;
import com.hfkj.sysenum.discount.DiscountStockCodeStatusEnum;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @className: BsDiscountPkStockBatchServiceImpl
 * @author: HuRui
 * @date: 2024/9/2
 **/
@Service("discountPkStockBatchService")
public class BsDiscountPkStockBatchServiceImpl implements BsDiscountPkStockBatchService {
    @Resource
    private BsDiscountPkStockBatchMapper discountPkStockBatchMapper;
    @Resource
    private BsDiscountPkService discountPkService;
    @Resource
    private BsDiscountPkStockCodeService discountPkStockCodeService;
    @Resource
    private BsDiscountStockCodeService discountStockCodeService;

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

            data.setBatchNo(""+System.currentTimeMillis());
            discountPkStockBatchMapper.updateByPrimaryKey(data);
        } else {
            data.setUpdateTime(new Date());
            discountPkStockBatchMapper.updateByPrimaryKey(data);
        }
    }

    @Override
    public void addStock(String discountPkNo, Integer stockCount) {
        // 查询优惠券
        BsDiscountPk discountPk = discountPkService.getDetail(discountPkNo);
        if (discountPk == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的优惠券");
        }
        BsDiscountPkStockBatch batch = new BsDiscountPkStockBatch();
        batch.setDiscountPkId(discountPk.getId());
        batch.setDiscountPkNo(discountPk.getDiscountPkNo());
        batch.setDiscountPkName(discountPk.getDiscountPkName());
        batch.setBatchStockNum(stockCount);
        batch.setStatus(1);
        editData(batch);

        List<BsDiscountPkStockCode> stockCodeList = new ArrayList<>();
        BsDiscountPkStockCode discountPkCode;
        for (int i = 0;i < stockCount;i++) {
            discountPkCode = new BsDiscountPkStockCode();
            discountPkCode.setDiscountPkStockBatchId(batch.getId());
            discountPkCode.setDiscountPkStockBatchNo(batch.getBatchNo());
            discountPkCode.setDiscountPkId(discountPk.getId());
            discountPkCode.setDiscountPkNo(discountPk.getDiscountPkNo());
            discountPkCode.setDiscountPkName(discountPk.getDiscountPkName());
            discountPkCode.setStatus(DiscountPkStockCodeStatusEnum.status1.getCode());
            discountPkCode.setCreateTime(new Date());
            discountPkCode.setUpdateTime(new Date());
            stockCodeList.add(discountPkCode);
        }
        // 批量新增
        discountPkStockCodeService.insertList(stockCodeList);

        batch.setStartId(""+stockCodeList.get(0).getId());
        batch.setEndId(""+stockCodeList.get(stockCount-1).getId());
        editData(batch);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW, rollbackFor= {RuntimeException.class})
    public void recycle(Long stockCodeId) {
        // 查询优惠券包库存编号
        BsDiscountPkStockCode pkStockCode = discountPkStockCodeService.getDetail(stockCodeId);
        if (pkStockCode == null) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "未找到优惠券包库存编码");
        }
        if (!pkStockCode.getStatus().equals(DiscountPkStockCodeStatusEnum.status2.getCode())) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_COMMON, "优惠券包状态错误");
        }

        // 是否有已使用的优惠卷
        boolean isUse = false;
        // 查询优惠券包下的优惠券
        List<BsDiscountStockCode> discountStockCodeList = discountStockCodeService.getCodeListByPkStockId(pkStockCode.getId());
        for (BsDiscountStockCode discountStockCode : discountStockCodeList) {
            if (discountStockCode.getStatus().equals(DiscountStockCodeStatusEnum.status3.getCode())) {
                isUse = true;
            } else if (discountStockCode.getStatus().equals(DiscountStockCodeStatusEnum.status2.getCode())) {
                // 退回优惠券
                discountStockCodeService.recycle(discountStockCode.getId());
            }
        }

        if (!isUse) {
            pkStockCode.setObtainType(null);
            pkStockCode.setObtainTime(null);
            pkStockCode.setReceiveMerUserId(null);
            pkStockCode.setReceiveMerUserPhone(null);
            pkStockCode.setStatus(DiscountPkStockCodeStatusEnum.status1.getCode());
            pkStockCode.setAgentAppid(null);
            discountPkStockCodeService.update(pkStockCode);
        }
    }

    @Override
    public BsDiscountPkStockBatch getStockBatchDetail(String batchNo) {
        BsDiscountPkStockBatchExample example = new BsDiscountPkStockBatchExample();
        example.createCriteria().andBatchNoEqualTo(batchNo).andStatusNotEqualTo(0);
        List<BsDiscountPkStockBatch> list = discountPkStockBatchMapper.selectByExample(example);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<BsDiscountPkStockBatch> getStockBatchList(Map<String, Object> param) {
        BsDiscountPkStockBatchExample example = new BsDiscountPkStockBatchExample();
        BsDiscountPkStockBatchExample.Criteria criteria = example.createCriteria().andStatusNotEqualTo(0);

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

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

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

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