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.OrderUtil;
import com.hfkj.dao.CouponDiscountPackageDetailsMapper;
import com.hfkj.dao.CouponDiscountPackageMapper;
import com.hfkj.dao.CouponDiscountPackageRecordMapper;
import com.hfkj.entity.*;
import com.hfkj.service.discount.CouponDiscountPackageService;
import com.hfkj.service.discount.CouponDiscountService;
import com.hfkj.service.discount.CouponDiscountUserRelService;
import com.hfkj.service.user.BsUserService;
import com.hfkj.sysenum.UserStatusEnum;
import io.swagger.models.auth.In;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

@Service("couponDiscountPackageService")
public class CouponDiscountPackageServiceImpl implements CouponDiscountPackageService {

    @Resource
    private CouponDiscountPackageMapper couponDiscountPackageMapper;

    @Resource
    private CouponDiscountPackageRecordMapper couponDiscountPackageRecordMapper;

    @Resource
    private CouponDiscountPackageDetailsMapper couponDiscountPackageDetailsMapper;

    @Resource
    private CouponDiscountUserRelService discountUserRelService;

    @Resource
    private BsUserService bsUserService;

    @Resource
    private CouponDiscountService discountService;

    @Override
    public void create(CouponDiscountPackage discountPackage) {
        couponDiscountPackageMapper.insert(discountPackage);
    }

    @Override
    public void update(CouponDiscountPackage discountPackage) {
        couponDiscountPackageMapper.updateByPrimaryKeySelective(discountPackage);
    }

    @Override
    public void delete(Long id, Boolean fullDelete) {

        if (fullDelete) {
            couponDiscountPackageMapper.deleteByPrimaryKey(id);
        } else {
            CouponDiscountPackage discountPackage = queryDetail(id);
            discountPackage.setStatus(0);
            discountPackage.setUpdatedTime(new Date());
            update(discountPackage);
        }
    }

    @Override
    public CouponDiscountPackage queryDetail(Long id) {
        return couponDiscountPackageMapper.selectByPrimaryKey(id);
    }

    @Override
    public CouponDiscountPackage queryDetailByMap(Map<String, Object> map) {
        return null;
    }

    @Override
    public List<CouponDiscountPackage> getList(Map<String, Object> map) {

        CouponDiscountPackageExample example = new CouponDiscountPackageExample();
        CouponDiscountPackageExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(MapUtils.getString(map, "title"))) {
            criteria.andTitleLike("%"+MapUtils.getString(map, "title")+"%");
        }
        if (StringUtils.isNotBlank(MapUtils.getString(map, "key"))) {
            criteria.andKeyEqualTo(MapUtils.getString(map, "key"));
        }
        if (MapUtils.getInteger(map, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(map, "status"));
        } else {
            criteria.andStatusNotEqualTo(0);
        }

        return couponDiscountPackageMapper.selectByExample(example);
    }

    @Override
    public List<CouponDiscountPackageRecord> getListRecordByMap(Map<String, Object> map) {

        CouponDiscountPackageRecordExample example = new CouponDiscountPackageRecordExample();
        CouponDiscountPackageRecordExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getInteger(map, "discountPackageId") != null) {
            criteria.andDiscountPackageIdEqualTo(MapUtils.getInteger(map, "discountPackageId"));
        }
        if (MapUtils.getInteger(map, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(map, "status"));
        } else {
            criteria.andStatusNotEqualTo(0);
        }

        return couponDiscountPackageRecordMapper.selectByExample(example);
    }

    @Override
    public void createRecord(CouponDiscountPackageRecord discountPackageRecord) {
        couponDiscountPackageRecordMapper.insert(discountPackageRecord);
    }

    @Override
    public void createDetail(CouponDiscountPackageDetails discountPackageDetails) {
        couponDiscountPackageDetailsMapper.insert(discountPackageDetails);
    }

    @Override
    public void updateDetail(CouponDiscountPackageDetails discountPackageDetails) {
        couponDiscountPackageDetailsMapper.updateByPrimaryKeySelective(discountPackageDetails);
    }

    @Override
    public List<CouponDiscountPackageDetails> getDetailList(Integer discountPackageId) {
        CouponDiscountPackageDetailsExample example = new CouponDiscountPackageDetailsExample();
        example.createCriteria().andStatusEqualTo(1).andDiscountPackageIdEqualTo(discountPackageId);

        return couponDiscountPackageDetailsMapper.selectByExample(example);
    }

    @Override
    public CouponDiscountPackageDetails discountPackageDetail(Integer discountPackageId , Integer discountId) {
        CouponDiscountPackageDetailsExample example = new CouponDiscountPackageDetailsExample();
        example.createCriteria().andDiscountPackageIdEqualTo(discountPackageId).andDiscountIdEqualTo(discountId).andStatusEqualTo(1);

        List<CouponDiscountPackageDetails> list = couponDiscountPackageDetailsMapper.selectByExample(example);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    @Override
    public void deleteDetail(Integer id) {
        couponDiscountPackageDetailsMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void giveDiscountPackage(Integer discountPackageId, String phone) {
        CouponDiscountPackage discountPackage = queryDetail(Long.valueOf(discountPackageId));

        BsUser bsUser = bsUserService.getUser(phone);
        if (bsUser == null) {
            bsUser = new BsUser();
            bsUser.setPhone(phone);
            bsUser.setStatus(UserStatusEnum.status1.getCode());
            bsUserService.editData(bsUser);
        }

        if (discountPackage == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前券包不存在！");
        }

        CouponDiscountUserRel discountUserRel;

        List<CouponDiscountPackageDetails> details = getDetailList(discountPackageId);

        for (CouponDiscountPackageDetails detail : details) {
            CouponDiscount discount = discountService.queryDetail(Long.valueOf(detail.getDiscountId()));
            for (int i = 0; i < detail.getNum(); i++) {
                discountUserRel = new CouponDiscountUserRel();
                discountUserRel.setDiscountId(Long.valueOf(detail.getDiscountId()));
                discountUserRel.setDiscountImg(detail.getDiscountImg());
                discountUserRel.setPlatformCode(discount.getPlatformCode());
                discountUserRel.setDiscountName(detail.getDiscountName());
                discountUserRel.setDiscountCondition(discount.getCondition());
                discountUserRel.setDiscountPrice(discount.getPrice());
                discountUserRel.setDiscountType(discount.getType());
                discountUserRel.setDiscountPercentage(discount.getPercentage());
                discountUserRel.setUserId(bsUser.getId());
                discountUserRel.setStatus(1);
                discountUserRel.setCreateTime(new Date());

                // 计算使用有效期
                Calendar userEndTime = Calendar.getInstance();
                userEndTime.setTime(new Date());
                userEndTime.set(Calendar.HOUR_OF_DAY, 23);
                userEndTime.set(Calendar.MINUTE, 59);
                userEndTime.set(Calendar.SECOND, 59);
                userEndTime.add(Calendar.DATE, discount.getEffectiveDay());

                if (userEndTime.getTime().compareTo(discount.getSalesEndTime()) > 0) {
                    discountUserRel.setUseEndTime(discount.getSalesEndTime());
                } else {
                    discountUserRel.setUseEndTime(userEndTime.getTime());
                }

                discountUserRelService.create(discountUserRel);
            }
        }

        CouponDiscountPackageRecord discountPackageRecord = new CouponDiscountPackageRecord();
        discountPackageRecord.setDiscountPackageId(discountPackageId);
        discountPackageRecord.setDiscountPackageTitle(discountPackage.getTitle());
        discountPackageRecord.setType(2);
        discountPackageRecord.setSerialNo(OrderUtil.generateOrderNo());
        discountPackageRecord.setUserId(bsUser.getId().intValue());
        discountPackageRecord.setUserPhone(bsUser.getPhone());
        discountPackageRecord.setCreatedTime(new Date());
        discountPackageRecord.setStatus(1);

        createRecord(discountPackageRecord);


        discountPackage.setSurplusStock(discountPackage.getSurplusStock() - 1);

        update(discountPackage);

    }
}
