package com.fs.his.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.StringUtils;
import com.fs.his.config.CouponConfig;
import com.fs.his.domain.FsCoupon;
import com.fs.his.domain.FsUser;
import com.fs.his.mapper.FsCouponMapper;
import com.fs.his.param.FsUserCouponParam;
import com.fs.his.param.FsUserCouponSendParam;
import com.fs.his.param.FsUserCouponUParam;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.vo.FsUserCouponCountUVO;
import com.fs.his.vo.FsUserCouponListUVO;
import com.fs.his.vo.FsUserCouponListVO;
import com.fs.system.service.ISysConfigService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.his.mapper.FsUserCouponMapper;
import com.fs.his.domain.FsUserCoupon;
import com.fs.his.service.IFsUserCouponService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 会员优惠券Service业务层处理
 *
 * @author fs
 * @date 2023-09-04
 */
@Service
public class FsUserCouponServiceImpl implements IFsUserCouponService
{
    @Autowired
    private FsUserCouponMapper fsUserCouponMapper;

    @Autowired
    private FsCouponMapper fsCouponMapper;

    @Autowired
    private ISysConfigService configService;

    /**
     * 查询会员优惠券
     *
     * @param id 会员优惠券主键
     * @return 会员优惠券
     */
    @Override
    public FsUserCoupon selectFsUserCouponById(Long id)
    {
        return fsUserCouponMapper.selectFsUserCouponById(id);
    }

    /**
     * 查询会员优惠券列表
     *
     * @param fsUserCoupon 会员优惠券
     * @return 会员优惠券
     */
    @Override
    public List<FsUserCoupon> selectFsUserCouponList(FsUserCoupon fsUserCoupon)
    {
        return fsUserCouponMapper.selectFsUserCouponList(fsUserCoupon);
    }

    /**
     * 新增会员优惠券
     *
     * @param fsUserCoupon 会员优惠券
     * @return 结果
     */
    @Override
    public int insertFsUserCoupon(FsUserCoupon fsUserCoupon)
    {
        fsUserCoupon.setCreateTime(DateUtils.getNowDate());
        return fsUserCouponMapper.insertFsUserCoupon(fsUserCoupon);
    }

    /**
     * 修改会员优惠券
     *
     * @param fsUserCoupon 会员优惠券
     * @return 结果
     */
    @Override
    public int updateFsUserCoupon(FsUserCoupon fsUserCoupon)
    {
        fsUserCoupon.setUpdateTime(DateUtils.getNowDate());
        return fsUserCouponMapper.updateFsUserCoupon(fsUserCoupon);
    }

    /**
     * 批量删除会员优惠券
     *
     * @param ids 需要删除的会员优惠券主键
     * @return 结果
     */
    @Override
    public int deleteFsUserCouponByIds(Long[] ids)
    {
        return fsUserCouponMapper.deleteFsUserCouponByIds(ids);
    }

    /**
     * 删除会员优惠券信息
     *
     * @param id 会员优惠券主键
     * @return 结果
     */
    @Override
    public int deleteFsUserCouponById(Long id)
    {
        return fsUserCouponMapper.deleteFsUserCouponById(id);
    }

    @Override
    public List<FsUserCouponListVO> selectFsUserCouponListVO(FsUserCouponParam fsUserCoupon) {
        String phone = fsUserCoupon.getPhone();
        if (StringUtils.isNotBlank(phone)){
            fsUserCoupon.setPhone(PhoneUtil.encryptPhone(phone));
        }
        return fsUserCouponMapper.selectFsUserCouponListVO(fsUserCoupon);
    }

    @Override
    public List<FsUserCouponListUVO> selectFsUserCouponListUVO(FsUserCouponUParam param) {
        return fsUserCouponMapper.selectFsUserCouponListUVO(param);
    }

    @Transactional
    @Override
    public int sendFsUserCoupon(FsUserCouponSendParam param) {
        if (param.getUserId()==null){
            throw new CustomException("用户不能为空");
        }
        FsCoupon coupon = fsCouponMapper.selectFsCouponByCouponId(param.getCouponId());
        if (coupon.getRemainNumber()<1){
            throw new CustomException("优惠劵剩余数量不足");
        }
        if (coupon.getCouponType()==2){
            Integer integer = fsUserCouponMapper.selectFsUserCouponByUserIdCount(param.getUserId(), coupon.getCouponType());
            if (integer>0){
                throw new CustomException("已经发送过同类型的优惠劵");
            }
        }else {
            Integer integer = fsUserCouponMapper.selectFsUserCouponByUserIdTypeCount(param.getUserId(), coupon.getCouponId());
            if (integer>0){
                throw new CustomException("已经发送过此优惠劵");
            }
        }

        FsUserCoupon fsUserCoupon = new FsUserCoupon();
        fsUserCoupon.setCouponId(coupon.getCouponId());
        fsUserCoupon.setCouponCode("C"+System.currentTimeMillis());
        fsUserCoupon.setUserId(param.getUserId());
        fsUserCoupon.setCreateTime(DateUtils.getNowDate());
        if (Boolean.TRUE.equals(param.getSystemSend())) {
            fsUserCoupon.setSendUserId(null);
            fsUserCoupon.setCompanyId(null);
            fsUserCoupon.setCompanyUserId(null);
        } else if (param.getCompanyUserId() == null && param.getCompanyId() == null){
            fsUserCoupon.setSendUserId(SecurityUtils.getUserId());
            fsUserCoupon.setCompanyId(null);
            fsUserCoupon.setCompanyUserId(null);
            System.out.println("发送人id:"+ fsUserCoupon.getSendUserId());
        } else {
            fsUserCoupon.setSendUserId(null);
            fsUserCoupon.setCompanyUserId(param.getCompanyUserId());
            fsUserCoupon.setCompanyId(param.getCompanyId());
            System.out.println("销售发送人id:"+ fsUserCoupon.getCompanyUserId());
        }
        fsUserCoupon.setStatus(0);
        int i = fsUserCouponMapper.insertFsUserCoupon(fsUserCoupon);
        coupon.setRemainNumber(coupon.getRemainNumber()-1);
        fsCouponMapper.updateFsCoupon(coupon);
        return i;
    }

    @Override
    public List<FsUserCouponListUVO> getMyEnableCouponList(FsUserCouponUParam param) {

        return fsUserCouponMapper.getMyEnableCouponList(param);
    }

    @Override
    public FsUserCouponCountUVO selectFsUserCouponCountUVO(FsUserCouponUParam param) {
        FsUserCouponCountUVO countUVO = new FsUserCouponCountUVO();
        if (param!=null&&param.getUserId()!=null){
            int[] countArray = new int[3];
            for (int i=0;i<3;i++){
                param.setStatus(i);
                List<FsUserCouponListUVO> list = fsUserCouponMapper.selectFsUserCouponListUVO(param);
                countArray[i] = list.size();
            }
            countUVO.setNotUsedCount(countArray[0]);
            countUVO.setUsedCount(countArray[1]);
            countUVO.setExpiredCount(countArray[2]);
        }
        return countUVO;
    }

    @Override
    public void sendRegisterCoupon(FsUser user) {
        Date createTime = user.getCreateTime();
        if (!isCreateTimeMoreThanOneDay(createTime)) {
            Long userId = user.getUserId();
            String json = configService.selectConfigByKey("his.coupon");
            CouponConfig config = JSONUtil.toBean(json, CouponConfig.class);
            Long[] registerCoupons = config.getRegisterCoupon();
            if (registerCoupons != null){
                for (Long registerCoupon : registerCoupons) {
                    FsUserCouponSendParam param = new FsUserCouponSendParam();
                    param.setCouponId(registerCoupon);
                    param.setUserId(userId);
                    sendFsUserCoupon(param);
                }
            }

        }
    }

    /**
     * 判断是否超过一天
     * @param createTime
     * @return
     */
    public static boolean isCreateTimeMoreThanOneDay(Date createTime) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime createTimeLocal = createTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

        // 判断是否超过一天
        return createTimeLocal.isBefore(now.minusDays(1));
    }
}
