package com.ssm.manage.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.BaseDao;
import com.ssm.manage.dto.CouponShareDto;
import com.ssm.manage.entity.CouponShare;
import com.ssm.manage.entity.PlatformCoupon;
import com.ssm.manage.entity.SmsException;
import com.ssm.manage.mapper.CouponShareMapper;
import com.ssm.manage.mapper.PlatformCouponMapper;
import com.ssm.manage.query.CouponShareRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.CouponShareService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * (CouponShare)表服务实现类
 *
 * @author makejava
 * @since 2022-06-11 15:00:06
 */
@Service("couponShareService")
public class CouponShareServiceImpl extends BaseServiceImpl<CouponShare> implements CouponShareService {

    @Autowired
    private CouponShareMapper couponShareDao;
    @Autowired
    private PlatformCouponMapper platformCouponMapper;



    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return
     */
    @Override
    public CouponShare queryById(Serializable id) {
        return couponShareDao.selectByPrimaryKey(id);
    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageInfo<CouponShare> queryByPage(CouponShareDto dto) {
        Example example = new Example(CouponShare.class);
        Example.Criteria criteria = example.createCriteria();


        if (null !=dto.getCouponName()){
            criteria.andLike("coupon_name","%"+dto.getCouponName()+"%");
        }
        if (null !=dto.getStoreName()){
            criteria.andLike("store_name","%"+dto.getStoreName()+"%");
        }
        if (null !=dto.getCouponNum()){
            criteria.andLike("coupon_num","%"+dto.getCouponNum()+"%");
        }
        if (null !=dto.getSharePhone()){
            criteria.andLike("share_phone","%"+dto.getSharePhone()+"%");
        }
        if (null !=dto.getGetPhone()){
            criteria.andLike("get_phone","%"+dto.getGetPhone()+"%");
        }
        if (null !=dto.getUseNum()){
            criteria.andLike("use_num","%"+dto.getUseNum()+"%");
        }
        if (null !=dto.getCurrentDate()){//andXxxLessThanOrEqualTo。。。。。
            criteria.andLessThanOrEqualTo("validity",dto.getCurrentDate());
        }
        if (null !=dto.getIsUse()){
            criteria.andLike("is_use","%"+dto.getIsUse()+"%");
        }
        if (null != dto.getDocMerchandiserName()) {
            criteria.andLike("docMerchandiserName", "%" + dto.getDocMerchandiserName() + "%");
        }
        if (null != dto.getIsUse()) {
            criteria.andEqualTo("is_use",dto.getIsUse());
        }
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize(),dto.getOrderAndSort());
        List<CouponShare> list = couponShareDao.selectByExample(example);

        BigDecimal sumFixedAmoun = new BigDecimal(0.0000);
        for (CouponShare couponShare : list) {
            if (couponShare.getShareCommissionRules()==0){
                //当前条是否使用
                if (couponShare.getIsUse()==1){
                    // 再加上
                    couponShare.setUseCommission(couponShare.getFixedAmoun());
                    couponShareDao.updateByPrimaryKeySelective(couponShare);
                }

            }else if (couponShare.getShareCommissionRules()==1){
                //查询本人下的分享
                if (couponShare.getIsUse()==1){
                    // 再加上
                    double v = couponShare.getOrderCommission() * couponShare.getDocMoney();
                    couponShare.setUseCommission(v);
                    couponShareDao.updateByPrimaryKeySelective(couponShare);
                }
            }
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
//            Date validity = couponShare.getValidity();
//            String time = sdf.format(validity);
//            Date date = new Date(time);
//            couponShare.setValidity(date);

        }

        Example examples = new Example(CouponShare.class);
        Example.Criteria criterias = examples.createCriteria();

        if (null !=dto.getCouponName()){
            criterias.andLike("couponName","%"+dto.getCouponName()+"%");
        }
        if (null !=dto.getStoreName()){
            criterias.andLike("storeName","%"+dto.getStoreName()+"%");
        }
        if (null !=dto.getCouponNum()){
            criterias.andLike("couponNum","%"+dto.getCouponNum()+"%");
        }
        if (null !=dto.getSharePhone()){
            criterias.andLike("sharePhone","%"+dto.getSharePhone()+"%");
        }
        if (null !=dto.getGetPhone()){
            criterias.andLike("getPhone","%"+dto.getGetPhone()+"%");
        }
        if (null !=dto.getUseNum()){
            criterias.andLike("useNum","%"+dto.getUseNum()+"%");
        }
        if (null !=dto.getCurrentDate()){//andXxxLessThanOrEqualTo。。。。。
            criterias.andLessThanOrEqualTo("validity",dto.getCurrentDate());
        }
        if (null !=dto.getIsUse()){
            criterias.andLike("isUse","%"+dto.getIsUse()+"%");
        }
        if (null != dto.getDocMerchandiserName()) {
            criterias.andLike("docMerchandiserName", "%" + dto.getDocMerchandiserName() + "%");
        }
        if (null != dto.getIsUse()) {
            criterias.andEqualTo("isUse",dto.getIsUse());
        }
        int size = couponShareDao.selectByExample(examples).size();

        PageInfo<CouponShare> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(size);
        return pageInfo;

    }

    /**
     * 新增
     *
     * @param couponShare
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int add(CouponShare couponShare) throws SmsException {
        CouponShare couponShare1 = new CouponShare();
        couponShare1.setCouponId(couponShare.getCouponId());
        couponShare1.setCouponNum(couponShare.getCouponNum());
        if(couponShareDao.choiceRepeat(couponShare)>0){
            return 0;
        }
        if (couponShareDao.selCount(couponShare1)>=platformCouponMapper.selectByPrimaryKey(couponShare.getCouponId()).getCouponNumber()){
            throw new SmsException(ResponseCode.FAILED,"优惠券已领完！");
        }
        //每人只能领取一张
//        if (couponShareDao.selectOne(couponShare)!=null){
//            throw new SmsException(ResponseCode.MSG,"每人只能领取一张"+couponShare.getCouponName()+"优惠卷！");
//        }
        couponShare.setUseNum(getString());
        Long refundId1 = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        couponShare.setId(refundId1);
        couponShare.setIsUse(0);
        couponShare.setShareExtract(0);
        couponShare.setGetDate(new Date());
        PlatformCoupon platformCoupon = platformCouponMapper.selectByPrimaryKey(couponShare.getCouponId());
        if (platformCoupon.getIndateType()==0){
            Date d = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String currdate = format.format(d);
//            System.out.println("现在的日期是：" + currdate);
            Calendar ca = Calendar.getInstance();
            ca.setTime(d);
            ca.add(Calendar.DATE, platformCoupon.getEndDay());//  platformCoupon.getEndDay()为增加的天数，可以改变的
            d = ca.getTime();
//            String enddate = format.format(d);
//            System.out.println("增加天数以后的日期：" + enddate);
            couponShare.setValidity(d);
        }else {
            couponShare.setValidity(platformCoupon.getEndDate());
        }
//        couponShare.setValidity();
        return couponShareDao.insert(couponShare);
    }
    /**
     * 生成随机编码
     * @return
     */
    private String getString() {
        //生成随机优惠券编码
        int i = UUID.randomUUID().toString().hashCode();
        if (i<0){
            i = -i;
        }
        String substring = String.format("%012d", i).substring(0, 12);
        return substring;
    }



    /**
     * 编辑
     *
     * @param couponShare
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int edit(CouponShare couponShare) {
        return couponShareDao.updateByPrimaryKeySelective(couponShare);
    }

    /**
     * 根据主键删除
     *
     * @param id 主键
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int delete(Serializable id) {
        return couponShareDao.deleteByPrimaryKey(id);
    }

    @Override
    public int share(CouponShareDto dto) {
        CouponShare couponShare = new CouponShare();
        //新增分享数据
        BeanUtils.copyProperties(dto,couponShare);

        //新增 add(couponShare);
        return 0;
    }

    @Override
    public List<CouponShareRequest> personalPage(CouponShareDto dto) {
        Example example = new Example(CouponShare.class);
        Example.Criteria criteria = example.createCriteria();


//        if (null !=dto.getSharePhone()){
//            criteria.andLike("share_phone","%"+dto.getSharePhone()+"%");
//        }
        if (null !=dto.getGetPhone()){//领取人手机
            criteria.andLike("getPhone","%"+dto.getGetPhone()+"%");
        }
        if (null!=dto.getGetOpenid()){//领取人微信id
            criteria.andEqualTo("getOpenid",dto.getGetOpenid());
        }
        if (null != dto.getIsUse()) {//使用编码唯一
            criteria.andEqualTo("isUse",dto.getIsUse());
        }
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize(),dto.getOrderAndSort());//分页
        List<CouponShare> list = couponShareDao.selectByExample(example);//查询
        Example examples = new Example(CouponShare.class);
        Example.Criteria criterias = example.createCriteria();
        if (null !=dto.getGetPhone()){
            criterias.andLike("sharePhone","%"+dto.getGetPhone()+"%");
        }
        if (null!=dto.getGetOpenid()){//领取人微信id
            criteria.andEqualTo("shareOpenid",dto.getGetOpenid());
        }
        List<CouponShare> lists = couponShareDao.selectByExample(examples);//查询自己分享出去的
        //固定提成  先判断是否使用，是否已提取分润，分润方式，最后计算合计
        Double sum = lists.stream().filter(couponShare -> couponShare.getIsUse() == 1).
                filter(couponShare -> couponShare.getShareExtract() == 0).
                filter(couponShare -> couponShare.getShareCommissionRules() == 0).
                mapToDouble(CouponShare::getFixedAmoun).sum();
        //百分比提成   先判断是否使用，是否已提取分润，分润方式，最后计算合计
        Double reduce = lists.stream().filter(couponShare -> couponShare.getIsUse() == 1).
                filter(couponShare -> couponShare.getShareExtract() == 0).
                filter(couponShare -> couponShare.getShareCommissionRules() == 1).
                reduce(0.00, (x, y) -> x + (y.getOrderCommission() * y.getDocMoney() / 100), Double::sum);

        List<CouponShareRequest> couponShareRequests = new ArrayList<>();
        for (CouponShare couponShare : list) {//复制类，本类无法新增字段
            CouponShareRequest couponShareRequest = new CouponShareRequest();
            BeanUtils.copyProperties(couponShare,couponShareRequest);
            couponShareRequests.add(couponShareRequest);
        }
        //添加对应的信息和可提现额度
        for (CouponShareRequest couponShareRequest : couponShareRequests) {
            PlatformCoupon platformCoupon = platformCouponMapper.selectByPrimaryKey(couponShareRequest.getCouponId());
            couponShareRequest.setPlatformCoupon(platformCoupon);
            couponShareRequest.setPersonalFenRun(sum+reduce);
        }
        return couponShareRequests;
    }

    @Override
    public BaseDao<CouponShare> getDao() {
        return null;
    }
}