package com.yonge.cooleshow.biz.dal.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dao.MemberPriceSettingsDao;
import com.yonge.cooleshow.biz.dal.dao.UserOrderDao;
import com.yonge.cooleshow.biz.dal.dto.ActivityPlanRewardDto;
import com.yonge.cooleshow.biz.dal.dto.req.OrderReq;
import com.yonge.cooleshow.biz.dal.dto.search.MemberPriceSettingsSearch;
import com.yonge.cooleshow.biz.dal.dto.search.OrderSearch;
import com.yonge.cooleshow.biz.dal.entity.*;
import com.yonge.cooleshow.biz.dal.enums.*;
import com.yonge.cooleshow.biz.dal.mapper.DiscountCardRecordMapper;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.*;
import com.yonge.cooleshow.biz.dal.vo.res.OrderCreateRes;
import com.yonge.cooleshow.biz.dal.wrapper.MemberPriceSettingsWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.UserPaymentOrderWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.VipCardRecordWrapper;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.ActivityShareEnum;
import com.yonge.cooleshow.common.enums.ActivityTypeEnum;
import com.yonge.cooleshow.common.enums.EDiscountType;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.thirdparty.message.MessageSenderPluginContext;
import com.yonge.toolset.utils.date.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class MemberPriceSettingsServiceImpl extends ServiceImpl<MemberPriceSettingsDao, MemberPriceSettings> implements MemberPriceSettingsService {
    private final static Logger log = LoggerFactory.getLogger(MemberPriceSettingsServiceImpl.class);
    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private VipCardRecordService vipCardRecordService;
    @Autowired
    private SysMessageService sysMessageService;

    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private ActivityPlanService activityPlanService;

    @Autowired
    private UserOrderService userOrderService;

    @Autowired
    private UserOrderDao userOrderDao;

    @Autowired
    private DiscountCardRecordMapper discountCardRecordMapper;

    @Autowired
    private UserOrderDetailService orderDetailService;

    @Autowired
    private MemberPriceSettingsService memberPriceSettingsService;

    @Override
    public MemberPriceSettingsVo detail(Long id) {
        return baseMapper.detail(id);
    }

    @Override
    public IPage<MemberPriceSettingsVo> selectPage(IPage<MemberPriceSettingsVo> page, MemberPriceSettingsSearch query) {
        return page.setRecords(baseMapper.selectPage(page, query));
    }

    @Override
    public List<MemberPriceSettingsVo> selectList(MemberPriceSettingsSearch query) {
        return baseMapper.selectList(query);
    }


    @Override
    public HttpResponseResult<OrderCreateRes> orderCreate(OrderReq.OrderReqInfo orderReqInfo) {
        MemberPriceSettingsVo detail = detail(Long.parseLong(orderReqInfo.getBizContent().toString()));
        if (null == detail) {
            return HttpResponseResult.failed("产品信息已更新，请重新选择");
        }

        if (!orderReqInfo.getOrderType().name().equals(detail.getVipType().name())) {
            return HttpResponseResult.failed("产品信息已更新，请重新选择");
        }

        if (Boolean.FALSE.equals(detail.getStatus())) {
            return HttpResponseResult.failed("产品信息已更新，请重新选择");
        }


        // 判断是否有待支付订单 如果有返回不可下单
        checkOrder(orderReqInfo.getOrderClient(), orderReqInfo.getOrderType().name(), orderReqInfo.getUserId());


        checkVip(detail, orderReqInfo.getVipEndDays(), orderReqInfo.getUserId(), orderReqInfo.getOrderClient(), orderReqInfo.getGoodsNum(),orderReqInfo.getBizPrice());

        OrderCreateRes orderCreateRes = new OrderCreateRes();
        BigDecimal couponAmount = BigDecimal.ZERO;
        ActivityPlanVo activityPlanVo = activityPlanService.detail(orderReqInfo.getActivityId());

        if (activityPlanVo != null && activityPlanVo.getActivityState() == 1) {
            for (ActivityPlanRewardDto activityPlanRewardDto : activityPlanVo.getActivityRewardList()) {
                if (activityPlanRewardDto.getActivityReward().getRewardType().getCode().equals(detail.getVipType().getCode())
                && activityPlanRewardDto.getActivityReward().getUnit().getCode().equals(detail.getPeriod().getCode())) {
                    couponAmount = activityPlanRewardDto.getActivityReward().getDiscountPrice();
                    orderCreateRes.setActivityId(activityPlanVo.getId());
                    orderCreateRes.setRewardId(activityPlanRewardDto.getActivityReward().getId());
                    break;
                }
            }
        }

        orderCreateRes.setRes(true);
        orderCreateRes.setMerchId(0l);
        orderCreateRes.setBizId(detail.getId());
        orderCreateRes.setBizContent("会员卡购买-" + detail.getPeriod().getMsg());
        orderCreateRes.setGoodNum(orderReqInfo.getGoodsNum());
        orderCreateRes.setOriginalPrice(detail.getOriginalPrice().multiply(new BigDecimal(orderReqInfo.getGoodsNum())));
        orderCreateRes.setCouponAmount(couponAmount.multiply(new BigDecimal(orderReqInfo.getGoodsNum())));
        orderCreateRes.setExpectPrice(detail.getSalePrice().multiply(new BigDecimal(orderReqInfo.getGoodsNum())));
        orderCreateRes.setSourceType(SourceTypeEnum.PLATFORM);
        UserPaymentOrderWrapper.VipDays vipDays = new UserPaymentOrderWrapper.VipDays();
        vipDays.setVipEndDays(orderReqInfo.getVipEndDays());
        orderCreateRes.setBizJson(JSON.toJSONString(vipDays));
        return HttpResponseResult.succeed(orderCreateRes);
    }

    private void checkVip(MemberPriceSettingsVo detail, Integer vipDays, Long userId, ClientEnum client, Integer num, BigDecimal bizPrice) {
        // 判断会员剩余天数是否改变
        if (detail.getVipType() == EVipType.SVIP && vipDays != null && vipDays > 0) {
            VipCardRecordWrapper.UserVip userVip = vipCardRecordService.userVipInfo(userId, client);
            if (!userVip.getVipEndDays().equals(vipDays)) {
                throw new BizException(998, "您当前VIP天数更新，请刷新后尝试");
            }
            // 判断能不能升级
            // 按时间区分 个数
            int days = getSvipDays(detail, num, userVip);
            if (days < userVip.getVipEndDays()) {
                throw new BizException(998, "您当前VIP天数更新，请刷新后尝试");
            }
        }
        if (bizPrice !=null && detail.getSalePrice().compareTo(bizPrice) !=0) {
            throw new BizException(999, "产品信息已更新，请重新选择");

        }
    }

    private int getSvipDays(MemberPriceSettingsVo detail, Integer num, VipCardRecordWrapper.UserVip userVip) {
        Integer timeNum = num;

        // 判断当前时间 加 一段时间后，和当前天数比较
        Date svipStartDate = new Date();
        if (userVip.getSvipEndDate() != null) {
            svipStartDate = userVip.getSvipEndDate();
        }

        DateTime dateTime = DateTime.parse(DateUtil.format(svipStartDate, "yyyy-MM-dd"))
            .withHourOfDay(23)
            .withMinuteOfHour(59)
            .withSecondOfMinute(59)
            .withMillisOfSecond(0);
        if (PeriodEnum.DAY.equals(detail.getPeriod())) {
            dateTime=dateTime.plusDays(timeNum);
        } else if (PeriodEnum.MONTH.equals(detail.getPeriod())) {
            dateTime=dateTime.plusMonths(timeNum);
        } else if (PeriodEnum.QUARTERLY.equals(detail.getPeriod())) {
            dateTime=dateTime.plusMonths(3 * timeNum);
        } else if (PeriodEnum.YEAR_HALF.equals(detail.getPeriod())) {
            dateTime=dateTime.plusMonths(6 * timeNum);
        } else if (PeriodEnum.YEAR.equals(detail.getPeriod())) {
            dateTime=dateTime.plusYears(timeNum);
        } else if (PeriodEnum.PERPETUAL.equals(detail.getPeriod())) {
            dateTime=dateTime.plusYears(100);
        }
        Date date = dateTime.toDate();
        // 比较两个时间 天数差
        int days = DateUtil.daysBetween(svipStartDate, date);
        return days;
    }

    @Override
    public void orderSuccess(UserOrderDetailVo orderDetailVo) {
        orderSuccess(orderDetailVo,true);
    }

    @Override
    public void orderSuccess(UserOrderDetailVo orderDetailVo,boolean messageFlag) {

        if (null == orderDetailVo) {
            return;
        }
        MemberPriceSettingsVo detail = detail(orderDetailVo.getBizId());


        VipCardRecordWrapper.AddVipCardRecord addVipCardRecord = new VipCardRecordWrapper.AddVipCardRecord();

        addVipCardRecord.setUserId(orderDetailVo.getUserId());
        addVipCardRecord.setClientType(orderDetailVo.getOrderClient());
        addVipCardRecord.setStatus(EVipRecordStatus.ADD);
        addVipCardRecord.setVipType(detail.getVipType());
        addVipCardRecord.setType(detail.getPeriod());
        addVipCardRecord.setTimes(orderDetailVo.getGoodNum());
        addVipCardRecord.setSendMsg(false);
        addVipCardRecord.setSourceType(SourceTypeEnum.ORDER);
        addVipCardRecord.setCreateBy(orderDetailVo.getUserId());
        addVipCardRecord.setOrderNo(orderDetailVo.getOrderNo());
        addVipCardRecord.setSubOrderNo(orderDetailVo.getSubOrderNo());
        addVipCardRecord.setVipCardId(orderDetailVo.getBizId());
        addVipCardRecord.setOrderFlag(true);

        // 判断转换天数

        // 赠送商品，不可转换
        boolean giftFlag = orderDetailVo.getGiftFlag() != null && orderDetailVo.getGiftFlag();
        if (!giftFlag) {
            VipCardRecordWrapper.UserVip userVip = vipCardRecordService.userVipInfo(orderDetailVo.getUserId(), orderDetailVo.getOrderClient());
            int svipDays = getSvipDays(detail, orderDetailVo.getGoodNum(), userVip);
            if (detail.getVipType() == EVipType.SVIP && userVip.getVipEndDays() != null && svipDays >= userVip.getVipEndDays()) {
                addVipCardRecord.setVipDays(userVip.getVipEndDays());
                if (userVip.getVipType() == EVipType.VIP) {
                    addVipCardRecord.setVipDays(Math.max(userVip.getVipEndDays() - 1, 0));
                }
            }
        }

        addVipCardRecord.setReason("会员购买");
        vipCardRecordService.add(addVipCardRecord);

        //会员购买消息推送
        if (messageFlag && !giftFlag) {

            SysUser sysUser = sysUserFeignService.queryUserById(orderDetailVo.getUserId());
            if (sysUser == null) {
                return;
            }

            // 按时间区分 个数
            Integer timeNum = 0;
            PeriodEnum periodType  = null;
            if (PeriodEnum.DAY.equals(detail.getPeriod())) {
                timeNum = 1;
                periodType = PeriodEnum.DAY;
            } else if (PeriodEnum.MONTH.equals(detail.getPeriod())) {
                timeNum = 1;
                periodType = PeriodEnum.MONTH;
            } else if (PeriodEnum.QUARTERLY.equals(detail.getPeriod())) {
                timeNum = 3;
                periodType = PeriodEnum.MONTH;
            } else if (PeriodEnum.YEAR_HALF.equals(detail.getPeriod())) {
                timeNum = 6;
                periodType = PeriodEnum.MONTH;
            } else if (PeriodEnum.YEAR.equals(detail.getPeriod())) {
                timeNum = 1;
                periodType = PeriodEnum.YEAR;
            } else if (PeriodEnum.PERPETUAL.equals(detail.getPeriod())) {
                timeNum = 1;
                periodType = PeriodEnum.PERPETUAL;
            }
            if (periodType == null) {
                return;
            }
            String s = timeNum + periodType.getMsg() + addVipCardRecord.getVipType().getName();
            if (PeriodEnum.PERPETUAL.equals(detail.getPeriod())) {
                s =addVipCardRecord.getVipType().getName();
            }
            authSend(sysUser.getId(), sysUser.getPhone(), s, orderDetailVo.getOrderClient());
        }
    }


    /**
     * 优惠卡创建检查
     *
     */
    @Override
    public void discountCreate(UserPaymentOrderWrapper.OrderGoodsInfo orderGoodsInfo) {
        MemberPriceSettingsVo detail = detail(Long.parseLong(orderGoodsInfo.getBizContent().toString()));
        if (null == detail) {
            throw new BizException(999,"产品信息已更新，请重新选择");
        }

        if (!orderGoodsInfo.getGoodType().name().equals(detail.getVipType().name())) {
            throw new BizException(999,"产品信息已更新，请重新选择");
        }
        if (Boolean.FALSE.equals(detail.getStatus())) {
            throw new BizException(999,"产品信息已更新，请重新选择");
        }

        BigDecimal couponAmount = BigDecimal.ZERO;

        UserOrderDetail userOrderDetail = JSON.parseObject(JSON.toJSONString(orderGoodsInfo), UserOrderDetail.class);

        userOrderDetail.setGoodUrl(userOrderService.getGoodUrlByType(orderGoodsInfo.getGoodType()));
        userOrderDetail.setMerchId(0l);
        userOrderDetail.setBizId(detail.getId());
        userOrderDetail.setBizContent("畅学卡购买-" + detail.getPeriod().getMsg());
        userOrderDetail.setGoodNum(orderGoodsInfo.getGoodNum());
        userOrderDetail.setOriginalPrice(detail.getOriginalPrice().multiply(new BigDecimal(orderGoodsInfo.getGoodNum())));
        userOrderDetail.setCouponAmount(couponAmount.multiply(new BigDecimal(orderGoodsInfo.getGoodNum())));
        userOrderDetail.setExpectPrice(orderGoodsInfo.getGiftFlag()?BigDecimal.ZERO:detail.getSalePrice().multiply(new BigDecimal(orderGoodsInfo.getGoodNum())));
        userOrderDetail.setActualPrice(userOrderDetail.getExpectPrice().subtract(couponAmount));
        orderGoodsInfo.setUserOrderDetail(userOrderDetail);

        // 设置金额入账去向
        userOrderDetail.setAccountConfig( teacherService.teacherSettlementFrom(null,orderGoodsInfo.getRecomUserId()).jsonString());
    }


    /**
     * 获取畅学卡信息
     *
     * @param userId 用户id
     */
    @Override
    public MemberPriceSettingsWrapper.UserDiscount getDiscount(Long userId) {
        MemberPriceSettings one = this.lambdaQuery()
                .eq(MemberPriceSettings::getVipType, "DISCOUNT")
                .eq(MemberPriceSettings::getStatus, true)
                .orderByDesc(MemberPriceSettings::getCreateTime)
                .last("limit 1").one();
        if (one == null) {
            return null;
        }
        MemberPriceSettingsWrapper.UserDiscount userDiscount = JSON.parseObject(JSON.toJSONString(one), MemberPriceSettingsWrapper.UserDiscount.class);
        if (userId !=null) {
            Student student = studentService.getById(userId);
            if (student != null) {
                userDiscount.setDiscountEndTime(student.getDiscountEndTime());
                userDiscount.setDiscountStartTime(student.getDiscountStartTime());
            }
        }
        return userDiscount;

    }

    @Override
    public MemberPriceSettingsWrapper.UserDiscount getDiscountByOrder(Long userId, Long orderDetilId) {
        MemberPriceSettingsWrapper.UserDiscount result = null;
        MemberPriceSettings detail = discountCardRecordMapper.detail(userId,orderDetilId);
        if (detail == null && null != userId) {
            detail = new MemberPriceSettings();
            UserOrderDetailVo orderDetailVo = orderDetailService.detail(orderDetilId);

            if (null == orderDetailVo) {
                return null;
            }
            detail = memberPriceSettingsService.detail(orderDetailVo.getBizId());
            if (null == detail) {
                return null;
            }
            result = JSON.parseObject(JSON.toJSONString(detail), MemberPriceSettingsWrapper.UserDiscount.class);
            // 按时间区分 个数
            Integer timeNum = orderDetailVo.getGoodNum();
            String periodType = null;

            if (PeriodEnum.DAY.equals(detail.getPeriod())) {
                periodType = PeriodEnum.DAY.getCode();
            } else if (PeriodEnum.MONTH.equals(detail.getPeriod())) {
                periodType = PeriodEnum.MONTH.getCode();
            } else if (PeriodEnum.QUARTERLY.equals(detail.getPeriod())) {
                timeNum = timeNum * 3;
                periodType = PeriodEnum.MONTH.getCode();
            } else if (PeriodEnum.YEAR_HALF.equals(detail.getPeriod())) {
                timeNum = timeNum * 6;
                periodType = PeriodEnum.MONTH.getCode();
            } else if (PeriodEnum.YEAR.equals(detail.getPeriod())) {
                periodType = PeriodEnum.YEAR.getCode();
            } else {
                periodType = PeriodEnum.PERPETUAL.getCode();
            }


            Student student = studentService.getById(userId);

            Date startTime = student.getDiscountEndTime();


            boolean flag = false;
            if (startTime == null) {
                startTime = new Date();
                flag = true;
            }
            Calendar cal = Calendar.getInstance();
            cal.setTime(startTime);

            if (PeriodEnum.DAY.getCode().equals(periodType)) {
                cal.add(Calendar.DAY_OF_MONTH, timeNum);
            } else if (PeriodEnum.MONTH.getCode().equals(periodType)) {
                cal.add(Calendar.MONTH, timeNum);
            } else if (PeriodEnum.YEAR.getCode().equals(periodType)) {
                cal.add(Calendar.YEAR, timeNum);
            }
            Date endTime = cal.getTime();
            if (flag) {
                DateTime dateTime = DateTime.parse(DateUtil.format(startTime, "yyyy-MM-dd"))
                        .plusDays(1)
                        .withHourOfDay(0)
                        .withMinuteOfHour(0)
                        .withSecondOfMinute(0)
                        .withMillisOfSecond(0);
                startTime = dateTime.toDate();
            }
            result.setDiscountStartTime(startTime);
            result.setDiscountEndTime(endTime);

        } else {
            result = JSON.parseObject(JSON.toJSONString(detail), MemberPriceSettingsWrapper.UserDiscount.class);
        }

        return result;
    }

    @Override
    public Map<Long, MemberPriceSettings> getMapByIds(List<Long> memberPriceSettingsIds) {
        if (CollectionUtils.isEmpty(memberPriceSettingsIds)) {
            return new HashMap<>();
        }
        Collection<MemberPriceSettings> memberPriceSettings = listByIds(memberPriceSettingsIds);
        return memberPriceSettings.stream().collect(Collectors.toMap(MemberPriceSettings::getId, a -> a));
    }


    @Override
    @Transactional
    public void activityReward(Long userId, ClientEnum client, ActivityReward activityReward, Long activityId,String activityName) {

        VipCardRecordWrapper.AddVipCardRecord addVipCardRecord = new VipCardRecordWrapper.AddVipCardRecord();

        addVipCardRecord.setUserId(userId);
        addVipCardRecord.setClientType(client);
        addVipCardRecord.setStatus(EVipRecordStatus.ADD);
        addVipCardRecord.setVipType(EVipType.valueOf(activityReward.getRewardType().name()));
        addVipCardRecord.setType(PeriodEnum.valueOf(activityReward.getUnit().name()));
        addVipCardRecord.setTimes(activityReward.getNum());
        addVipCardRecord.setSendMsg(false);
        addVipCardRecord.setCreateBy(userId);
        addVipCardRecord.setSourceType(SourceTypeEnum.ACTIVITY);
        vipCardRecordService.add(addVipCardRecord);

    }

    private UserVipInfoVo getUserVipInfoVo(VipCardRecord vipCardRecord) {
        UserVipInfoVo userVipInfoVo = getVipInfo(vipCardRecord.getClientType(), vipCardRecord.getUserId());

        if (userVipInfoVo == null) {
            log.error("未找到用户信息");
            throw new BizException("未找到用户信息");
        }

        if (null == userVipInfoVo.getMembershipEndTime() || userVipInfoVo.getMembershipEndTime().before(new Date())) {
            //没有会员、会员已过期 会员卡生效时间为当前时间
            userVipInfoVo.setMembershipStartTime(vipCardRecord.getStartTime());
            userVipInfoVo.setMembershipEndTime(vipCardRecord.getEndTime());
        } else {
            userVipInfoVo.setMembershipEndTime(vipCardRecord.getEndTime());
        }
        userVipInfoVo.setMemberRankSettingId(1l);
        userVipInfoVo.setUpdateTime(new Date());

        updateUser(userVipInfoVo);

        //会员购买记录入库
        vipCardRecordService.save(vipCardRecord);
        return userVipInfoVo;
    }

    private void updateUser(UserVipInfoVo userVipInfoVo) {
        if (ClientEnum.STUDENT.equals(userVipInfoVo.getUserType())) {
            studentService.lambdaUpdate()
                    .eq(Student::getUserId,userVipInfoVo.getUserId())
                    .set(Student::getMemberRankSettingId,userVipInfoVo.getMemberRankSettingId())
                    .set(Student::getMembershipStartTime,userVipInfoVo.getMembershipStartTime())
                    .set(Student::getMembershipEndTime,userVipInfoVo.getMembershipEndTime())
                    .set(Student::getUpdateTime,userVipInfoVo.getUpdateTime())
                    .update();
        } else {
            teacherService.lambdaUpdate()
                          .eq(Teacher::getUserId, userVipInfoVo.getUserId())
                          .set(Teacher::getMemberRankSettingId,userVipInfoVo.getMemberRankSettingId())
                          .set(Teacher::getMembershipStartTime,userVipInfoVo.getMembershipStartTime())
                          .set(Teacher::getMembershipEndTime,userVipInfoVo.getMembershipEndTime())
                          .set(Teacher::getUpdateTime,userVipInfoVo.getUpdateTime())
                          .update();
        }
    }

    @Override
    public ShareProfitVo shareVipProfit(SysUser sysUser, Long vipId) {

        ShareProfitVo result = new ShareProfitVo();

        MemberPriceSettingsSearch memberPriceSettingsSearch = new MemberPriceSettingsSearch();
        YesOrNoEnum discount = YesOrNoEnum.NO;
        ActivityPlanVo activityPlanVo = activityPlanService.activityShare(ActivityShareEnum.VIP, sysUser.getId());
        if (activityPlanVo != null) {
            result.setActivityId(activityPlanVo.getId());
            discount = YesOrNoEnum.YES;
            memberPriceSettingsSearch.setActivityId(activityPlanVo.getId());
        }
        memberPriceSettingsSearch.setUserId(sysUser.getId());
        MemberPriceVo vipShare = getVipShare(memberPriceSettingsSearch);
        result.setDiscount(discount);
        result.setVip(vipShare.getList());
        return result;
    }

//    @Deprecated
//    @Override
//    public Boolean addVip(VipSubmitReq vipSubmitReq, ClientEnum client, SysUser sysUser) {
//
//        VipCardRecord vipCardRecord = vipCardRecordService.getVipCardRecord(vipSubmitReq.getUserId(), client, null, null, vipSubmitReq.getType().toString(),
//                            null, vipSubmitReq.getTimes(),SourceTypeEnum.PLATFORM, sysUser.getId(), vipSubmitReq.getReason());
//
//        getUserVipInfoVo(vipCardRecord);
//
//        // 发消息
//        sendAddVipMessage(vipSubmitReq.getUserId(),sysUser.getPhone(),client,vipSubmitReq.getTimes(),vipSubmitReq.getType(),vipSubmitReq.getReason());
//
//        return true;
//    }

    @Override
    public MemberPriceVo getVipShare(MemberPriceSettingsSearch query) {
        MemberPriceVo memberPriceVo = new MemberPriceVo();
        List<MemberPriceSettingsVo> memberPriceSettingsVos = baseMapper.selectList(query);

        memberPriceVo.setList(memberPriceSettingsVos);
        ActivityPlanVo activityPlan = activityPlanService.detail(query.getActivityId());

        if (activityPlan == null || activityPlan.getActivityState() != 1 || query.getUserId() == null) {
            return memberPriceVo;
        }

        SysUser user = sysUserFeignService.queryUserById(query.getUserId());
        if (user == null) {
            throw new BizException("未找到用户信息");
        }
        memberPriceVo.setDiscount(YesOrNoEnum.YES);
        memberPriceVo.setAvatar(user.getAvatar());
        memberPriceVo.setUsername(user.getUsername());

        for (ActivityPlanRewardDto activityPlanRewardDto : activityPlan.getActivityRewardList()) {
            for (MemberPriceSettingsVo memberPriceSettingsVo : memberPriceSettingsVos) {
                if (activityPlanRewardDto.getActivityReward().getRewardType().getCode().equals(memberPriceSettingsVo.getVipType().getCode())
                    && activityPlanRewardDto.getActivityReward().getUnit().getCode().equals(memberPriceSettingsVo.getPeriod().getCode())) {
                    memberPriceSettingsVo.setDiscount(YesOrNoEnum.YES);
                    memberPriceSettingsVo.setDiscountPrice(activityPlanRewardDto.getActivityReward().getDiscountPrice());
                }
            }
        }
        return memberPriceVo;
    }

    @Override
    public void orderCreate(UserPaymentOrderWrapper.OrderGoodsInfo orderGoodsInfo) {
        MemberPriceSettingsVo detail = detail(Long.parseLong(orderGoodsInfo.getBizContent().toString()));
        if (null == detail) {
            throw new BizException(999,"产品信息已更新，请重新选择");
        }

        if (!orderGoodsInfo.getGoodType().name().equals(detail.getVipType().name())) {
            throw new BizException(999,"产品信息已更新，请重新选择");
        }
        if (Boolean.FALSE.equals(detail.getStatus())) {
            throw new BizException(999,"产品信息已更新，请重新选择");
        }


        checkOrder(orderGoodsInfo.getPaymentClient(), detail.getVipType().name(), orderGoodsInfo.getUserId());

        // 判断会员剩余天数是否改变
        checkVip(detail, orderGoodsInfo.getVipEndDays(), orderGoodsInfo.getUserId(), orderGoodsInfo.getPaymentClient(), orderGoodsInfo.getGoodNum(), orderGoodsInfo.getBizPrice());

        BigDecimal couponAmount = BigDecimal.ZERO;
        BigDecimal expectPrice = detail.getSalePrice();
        ActivityPlanVo activityPlanVo = activityPlanService.detail(orderGoodsInfo.getActivityId());


        if (activityPlanVo != null && activityPlanVo.getActivityState() == 1 ) {
            if ( activityPlanVo.getActivityType() == ActivityTypeEnum.SHARE) {
                for (ActivityPlanRewardDto activityPlanRewardDto : activityPlanVo.getActivityRewardList()) {
                    if (activityPlanRewardDto.getActivityReward().getRewardType().getCode().equals(detail.getVipType().getCode())
                            && activityPlanRewardDto.getActivityReward().getUnit().getCode().equals(detail.getPeriod().getCode())) {
                        couponAmount = activityPlanRewardDto.getActivityReward().getDiscountPrice();
                        if (couponAmount.compareTo(expectPrice) >= 0) {
                            couponAmount = expectPrice;
                        }
                        break;
                    }
                }
            } else if (activityPlanVo.getActivityType() == ActivityTypeEnum.MEMBER && !orderGoodsInfo.getGiftFlag()) {
                expectPrice = activityPlanVo.getRegistrationPrice();

            }
        }

        UserOrderDetail userOrderDetail = JSON.parseObject(JSON.toJSONString(orderGoodsInfo), UserOrderDetail.class);

        userOrderDetail.setGoodUrl(userOrderService.getGoodUrlByType(orderGoodsInfo.getGoodType()));
        userOrderDetail.setMerchId(0l);
        userOrderDetail.setBizId(detail.getId());
        userOrderDetail.setBizContent("会员卡购买-" + detail.getPeriod().getMsg());
        userOrderDetail.setGoodNum(orderGoodsInfo.getGoodNum());
        userOrderDetail.setOriginalPrice(detail.getOriginalPrice().multiply(new BigDecimal(orderGoodsInfo.getGoodNum())));
        userOrderDetail.setCouponAmount(couponAmount.multiply(new BigDecimal(orderGoodsInfo.getGoodNum())));
        userOrderDetail.setExpectPrice(orderGoodsInfo.getGiftFlag()?BigDecimal.ZERO:expectPrice.subtract(couponAmount).multiply(new BigDecimal(orderGoodsInfo.getGoodNum())));
        userOrderDetail.setActualPrice(userOrderDetail.getExpectPrice());
        userOrderDetail.setDiscountJson(userOrderService.discountJson(EDiscountType.ACTIVATY,
                couponAmount.multiply(new BigDecimal(orderGoodsInfo.getGoodNum())),userOrderDetail.getDiscountJson()));
        orderGoodsInfo.setUserOrderDetail(userOrderDetail);

        UserPaymentOrderWrapper.VipDays vipDays = new UserPaymentOrderWrapper.VipDays();
        vipDays.setVipEndDays(orderGoodsInfo.getVipEndDays());
        userOrderDetail.setBizJson(JSON.toJSONString(vipDays));
        userOrderDetail.setAccountConfig( teacherService.teacherSettlementFrom(null,orderGoodsInfo.getRecomUserId()).jsonString());

    }

    private void checkOrder(ClientEnum orderGoodsInfo, String orderType, Long userId) {
        // 判断是否有待支付订单 如果有返回不可下单
        OrderSearch search = new OrderSearch();
        search.setOrderClient(orderGoodsInfo.name());
        search.setGoodType(Lists.newArrayList(GoodTypeEnum.VIP, GoodTypeEnum.SVIP).stream().map(GoodTypeEnum::name).collect(Collectors.joining(",")));
        search.setUserId(userId);

        UserOrderVo userOrderVo = userOrderDao.getPendingOrder(search);
        if (null != userOrderVo) {
            throw new BizException(997, "您有未支付订单，请先支付");
        }
    }

    private void sendAddVipMessage(Long userId,String phone, ClientEnum client, Integer times, PeriodEnum type, String reason) {
        try {
            Map<Long, String> receivers = new HashMap<>();
            receivers.put(userId, phone);
            Student student = studentService.getById(userId);
            if (client.equals(ClientEnum.STUDENT) && student != null && student.getTenantId() != null && student.getTenantId() >0) {
                try {
                    sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.TENANT_PLATFORM_ADD_VIP,
                            receivers, null, 0, null, ClientEnum.TENANT_STUDENT.getCode(), times +type.getMsg(), reason);
                } catch (Exception e) {
                    log.error("会员赠送消息发送失败", e);
                }
            } else {
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.PLATFORM_ADD_VIP,
                        receivers, null, 0, null, client.getCode(), times, type.getMsg(), reason);
            }
        } catch (Exception e) {
            log.error("会员赠送消息发送失败 ： {}",e.getMessage());
        }
    }

    private UserVipInfoVo getVipInfo(ClientEnum userType, Long userId) {

        UserVipInfoVo userVipInfoVo = new UserVipInfoVo();
        userVipInfoVo.setUserType(userType);
        if (userType.equals(ClientEnum.STUDENT)) {
            StudentVo studentVo = studentService.detail(userId);
            if (studentVo == null) {
                return null;
            }

            BeanUtils.copyProperties(studentVo,userVipInfoVo);
            return userVipInfoVo;
        } else if (userType.equals(ClientEnum.TEACHER)) {
            TeacherVo teacherVo = teacherService.detail(userId);
            if (teacherVo == null) {
                return null;
            }

            BeanUtils.copyProperties(teacherVo,userVipInfoVo);
            return userVipInfoVo;
        }
        return null;
    }


    // 发送会员购买消息推送
    private void authSend(Long userId,String phone, String param1,ClientEnum clientEnum) {
        Map<Long, String> receivers = new HashMap<>();
        receivers.put(userId, phone);

        // 判断是否是机构学生 机构学生推送走另一个

        try {
            MessageTypeEnum messageTypeEnum = MessageTypeEnum.NEW_VIP_BUY_SUCCESS;
            if (clientEnum == ClientEnum.TEACHER) {
                messageTypeEnum= MessageTypeEnum.NEW_TEACHER_VIP_BUY_SUCCESS;
            }
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG,
                    messageTypeEnum,
                    receivers,
                    null,
                    0,
                    null,
                    clientEnum.getCode(),
                    param1);
        } catch (Exception e) {
            log.error("会员购买极光消息推送异常,userId={}", userId);
        }

        try {

            MessageTypeEnum messageTypeEnum = MessageTypeEnum.SMS_NEW_VIP_BUY_SUCCESS;
            if (clientEnum == ClientEnum.TEACHER) {
                messageTypeEnum= MessageTypeEnum.SMS_TEACHER_NEW_VIP_BUY_SUCCESS;
            }
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, messageTypeEnum,
                    receivers, null, 0, null, clientEnum.getCode(), param1);
        } catch (Exception e) {
            log.error("会员购买短信消息推送异常,userId={}", userId);
        }

    }

}