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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dto.ActivityPlanRewardDto;
import com.yonge.cooleshow.biz.dal.dto.VipSubmitReq;
import com.yonge.cooleshow.biz.dal.dto.req.OrderReq;
import com.yonge.cooleshow.biz.dal.entity.*;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.MessageTypeEnum;
import com.yonge.cooleshow.biz.dal.entity.VipCardRecord;
import com.yonge.cooleshow.biz.dal.enums.PeriodEnum;
import com.yonge.cooleshow.biz.dal.enums.SourceTypeEnum;
import com.yonge.cooleshow.biz.dal.service.*;

import com.yonge.cooleshow.biz.dal.vo.ShareProfitVo;
import com.yonge.cooleshow.biz.dal.vo.StudentVo;
import com.yonge.cooleshow.biz.dal.vo.UserOrderDetailVo;

import com.yonge.cooleshow.biz.dal.vo.*;

import com.yonge.cooleshow.biz.dal.vo.res.OrderCreateRes;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.ActivityShareEnum;
import com.yonge.cooleshow.common.enums.RewardTypeEnum;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.string.MessageFormatter;
import com.yonge.toolset.thirdparty.message.MessageSenderPluginContext;
import com.yonge.toolset.utils.date.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yonge.cooleshow.biz.dal.dto.search.MemberPriceSettingsSearch;
import com.yonge.cooleshow.biz.dal.dao.MemberPriceSettingsDao;

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


@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;

    @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("未找到会员卡信息");
        }

        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().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(1);
        orderCreateRes.setOriginalPrice(detail.getOriginalPrice());
        orderCreateRes.setCouponAmount(couponAmount);
        orderCreateRes.setExpectPrice(detail.getSalePrice());
        return HttpResponseResult.succeed(orderCreateRes);
    }


    @Override
    public void orderSuccess(UserOrderDetailVo orderDetailVo) {

        VipCardRecord vipCardRecord = vipCardRecordService.buildVipCardRecordByOrderDetail(orderDetailVo);

        UserVipInfoVo userVipInfoVo = getUserVipInfoVo(vipCardRecord);
        //会员购买消息推送
        authSend(userVipInfoVo.getUserId(), userVipInfoVo.getPhone(), DateUtil.format(vipCardRecord.getEndTime(), DateUtil.DEFAULT_PATTERN),orderDetailVo.getOrderClient());
    }


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

        VipCardRecord vipCardRecord = vipCardRecordService.buildVipCardRecordByOrderDetail(userId,client,activityReward,activityId,activityName);
        if (vipCardRecord == null) {
            return;
        }

        getUserVipInfoVo(vipCardRecord);
    }

    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;
    }

    @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(),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 (memberPriceSettingsVo.getPeriod().getCode().equals( activityPlanRewardDto.getActivityReward().getUnit().getCode())) {
                    memberPriceSettingsVo.setDiscount(YesOrNoEnum.YES);
                    memberPriceSettingsVo.setDiscountPrice(activityPlanRewardDto.getActivityReward().getDiscountPrice());
                }
            }
        }
        return memberPriceVo;
    }

    private void sendAddVipMessage(Long userId, ClientEnum client, Integer times, PeriodEnum type, String reason) {
        try {
            SysUser user = sysUserFeignService.queryUserById(userId);

            if (user == null) {
                return;
            }

            Map<Long, String> receivers = new HashMap<>();
            receivers.put(userId, user.getPhone());
            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 {
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.VIP_BUY_SUCCESS,
                    receivers, null, 0, null, clientEnum.getCode(), param1);
        } catch (Exception e) {
            log.error("会员购买极光消息推送异常,userId={}", userId);
        }

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

    }

}