package com.xiaoniu.system.operation.coupon.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoniu.common.core.constant.Constants;
import com.xiaoniu.common.core.exception.ServiceException;
import com.xiaoniu.common.core.resdata.RowsData;
import com.xiaoniu.common.core.utils.DateUtils;
import com.xiaoniu.common.core.utils.StringUtils;
import com.xiaoniu.common.core.utils.bean.BeanUtils;
import com.xiaoniu.common.security.utils.SecurityUtils;
import com.xiaoniu.system.operation.coupon.domain.TbCoupon;
import com.xiaoniu.system.operation.coupon.dto.AddCouponDTO;
import com.xiaoniu.system.operation.coupon.dto.CouponListQueryDTO;
import com.xiaoniu.system.operation.coupon.dto.EditCouponDTO;
import com.xiaoniu.system.operation.coupon.mapper.TbCouponMapper;
import com.xiaoniu.system.operation.coupon.service.ITbCouponService;
import com.xiaoniu.system.operation.coupon.vo.CouponDetailsVO;
import com.xiaoniu.system.operation.coupon.vo.CouponListVO;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author haoxuyang
 * @since 2024-10-17 02:30:09
 */
@Service
public class TbCouponServiceImpl extends ServiceImpl<TbCouponMapper, TbCoupon> implements ITbCouponService {

    @Override
    public RowsData<CouponListVO> couponList(CouponListQueryDTO dto) {
        try (Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize())) {
            List<CouponListVO> list = baseMapper.getCouponList(dto);
            if (StringUtils.isNotNull(list)) {
                for (CouponListVO couponListVO : list) {
                    String discountResult = couponListVO.getDiscountResult();
                    if (StringUtils.isNotEmpty(discountResult)) {
                        if (Constants.ONE.equals(couponListVO.getDiscountMethod())) {
                            couponListVO.setDiscountResult(discountResult);
                        } else if (Constants.TWO.equals(couponListVO.getDiscountMethod())) {
                            JSONObject parse = JSONObject.parse(discountResult);
                            couponListVO.setDiscountResult("满" + parse.getBigDecimal("full") + "减" + parse.getBigDecimal("minus"));
                        } else if (Constants.THREE.equals(couponListVO.getDiscountMethod())) {
                            JSONObject parse = JSONObject.parse(discountResult);
                            couponListVO.setDiscountResult(parse.getString("discount") + "折");
                        }
                    }
                }

            }
            return new RowsData<>(list, page.getTotal(), dto.getPageNum());
        }
    }

    @Override
    public void addCoupon(AddCouponDTO dto) {
        TbCoupon tbCoupon = new TbCoupon();
        BeanUtils.copyProperties(dto, tbCoupon);
        if (Constants.ONE.equals(dto.getDiscountMethod())) {
            if (StringUtils.isNull(dto.getDiscountAmount())) {
                throw new ServiceException("优惠金额（时长）不能为空");
            }
            tbCoupon.setDiscountResult(String.valueOf(dto.getDiscountAmount()));
        } else if (Constants.TWO.equals(dto.getDiscountMethod())) {
            if (StringUtils.isNull(dto.getFull()) || StringUtils.isNull(dto.getMinus())) {
                throw new ServiceException("满减金额不能为空");
            }
            JSONObject json = new JSONObject();
            json.put("full", dto.getFull());
            json.put("minus", dto.getMinus());
            tbCoupon.setDiscountResult(json.toJSONString());
        } else if (Constants.THREE.equals(dto.getDiscountMethod())) {
            if (StringUtils.isNull(dto.getDiscount())) {
                throw new ServiceException("折扣不能为空");
            }
            JSONObject json = new JSONObject();
            json.put("discount", dto.getDiscount());
            json.put("discountStatus", dto.getDiscountStatus());
            json.put("maximumReduction", dto.getMaximumReduction());
            tbCoupon.setDiscountResult(json.toJSONString());
        }
        try {
            tbCoupon.setCreateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            log.error("获取用户信息失败");
        }
        tbCoupon.setCreateTime(new Date());
        tbCoupon.setDistributionTime(DateUtils.parseDate(dto.getDistributionTime()));
        tbCoupon.setEndTime(DateUtils.parseDate(dto.getEndTime()));
        tbCoupon.setRemainingQuantity(dto.getMaximumQuantity());
        baseMapper.insert(tbCoupon);
    }

    @Override
    public void editCoupon(EditCouponDTO dto) {
        TbCoupon tbCoupon = baseMapper.selectById(dto.getId());
        if (StringUtils.isNull(tbCoupon)) {
            throw new ServiceException("当前信息不存在");
        }
        if (Constants.TWO.equals(tbCoupon.getDelFlag())) {
            throw new ServiceException("当前信息已被删除");
        }
        BeanUtils.copyProperties(dto, tbCoupon);
        if (Constants.ONE.equals(dto.getDiscountMethod())) {
            if (StringUtils.isNull(dto.getDiscountAmount())) {
                throw new ServiceException("优惠金额（时长）不能为空");
            }
            tbCoupon.setDiscountResult(String.valueOf(dto.getDiscountAmount()));
        } else if (Constants.TWO.equals(dto.getDiscountMethod())) {
            if (StringUtils.isNull(dto.getFull()) || StringUtils.isNull(dto.getMinus())) {
                throw new ServiceException("满减金额不能为空");
            }
            JSONObject json = new JSONObject();
            json.put("full", dto.getFull());
            json.put("minus", dto.getMinus());
            tbCoupon.setDiscountResult(json.toJSONString());
        } else if (Constants.THREE.equals(dto.getDiscountMethod())) {
            if (StringUtils.isNull(dto.getDiscount())) {
                throw new ServiceException("折扣不能为空");
            }
            JSONObject json = new JSONObject();
            json.put("discount", dto.getDiscount());
            json.put("discountStatus", dto.getDiscountStatus());
            json.put("maximumReduction", dto.getMaximumReduction());
            tbCoupon.setDiscountResult(json.toJSONString());
        }
        try {
            tbCoupon.setUpdateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            log.error("获取用户信息失败");
        }
        tbCoupon.setUpdateTime(new Date());
        tbCoupon.setDistributionTime(DateUtils.parseDate(dto.getDistributionTime()));
        tbCoupon.setEndTime(DateUtils.parseDate(dto.getEndTime()));
        tbCoupon.setRemainingQuantity(dto.getMaximumQuantity());
        baseMapper.updateById(tbCoupon);
    }

    @Override
    public CouponDetailsVO details(Long id) {
        TbCoupon tbCoupon = baseMapper.selectById(id);
        if (StringUtils.isNull(tbCoupon)) {
            throw new ServiceException("当前信息不存在");
        }
        if (Constants.TWO.equals(tbCoupon.getDelFlag())) {
            throw new ServiceException("当前信息已被删除");
        }
        CouponDetailsVO couponDetailsVO = new CouponDetailsVO();
        BeanUtils.copyProperties(tbCoupon, couponDetailsVO);
        String discountResult = tbCoupon.getDiscountResult();
        if (StringUtils.isNotEmpty(discountResult)) {
            if (Constants.ONE.equals(tbCoupon.getDiscountMethod())) {
                couponDetailsVO.setDiscountAmount(new BigDecimal(tbCoupon.getDiscountResult()));
            } else if (Constants.TWO.equals(tbCoupon.getDiscountMethod())) {
                JSONObject parse = JSONObject.parse(discountResult);
                couponDetailsVO.setFull(parse.getBigDecimal("full"));
                couponDetailsVO.setMinus(parse.getBigDecimal("minus"));
            } else if (Constants.THREE.equals(tbCoupon.getDiscountMethod())) {
                JSONObject parse = JSONObject.parse(discountResult);
                couponDetailsVO.setDiscount(parse.getDouble("discount"));
                couponDetailsVO.setDiscountStatus(parse.getString("discountStatus"));
                couponDetailsVO.setMaximumReduction(parse.getBigDecimal("maximumReduction"));
            }
        }
        return couponDetailsVO;
    }

    @Override
    public void delCoupon(Long id) {
        baseMapper.update(new LambdaUpdateWrapper<TbCoupon>().eq(TbCoupon::getId, id).set(TbCoupon::getDelFlag, Constants.TWO));

    }
}
