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.biz.dal.dao.MemberPriceSettingsDao;
import com.yonge.cooleshow.biz.dal.entity.MemberPriceSettings;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.MessageTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.PeriodEnum;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.*;
import com.yonge.toolset.thirdparty.message.MessageSenderPluginContext;
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 com.yonge.cooleshow.biz.dal.entity.VipCardRecord;
import com.yonge.cooleshow.biz.dal.dto.search.VipCardRecordSearch;
import com.yonge.cooleshow.biz.dal.dao.VipCardRecordDao;

import java.util.*;


@Service
public class VipCardRecordServiceImpl extends ServiceImpl<VipCardRecordDao, VipCardRecord> implements VipCardRecordService {
    private final static Logger log = LoggerFactory.getLogger(VipCardRecordServiceImpl.class);

    @Autowired
    private SysMessageService sysMessageService;
    @Autowired
    private MemberPriceSettingsDao memberPriceSettingsDao;
    @Autowired
    private StudentService studentService;


    @Autowired
    private TeacherService teacherService;

    @Autowired
    private MemberPriceSettingsService memberPriceSettingsService;
    @Autowired
    private UserOrderDetailService orderDetailService;

    @Override
    public VipCardRecordVo detail(Long orderDetilId) {
        return baseMapper.detail(orderDetilId, null);
    }

    @Override
    public VipCardRecordVo detail(Long orderDetilId, Long userId) {
        VipCardRecordVo detail = baseMapper.detail(orderDetilId, userId);
        if (null == detail && null != userId) {
            detail = new VipCardRecordVo();

            UserOrderDetailVo orderDetailVo = orderDetailService.detail(orderDetilId);
            VipCardRecord vipCardRecord = buildVipCardRecordByOrderDetail(orderDetailVo);
            if (null == vipCardRecord) {
                return detail;
            }
            BeanUtils.copyProperties(vipCardRecord, detail);
            MemberPriceSettings memberPrice = memberPriceSettingsDao.getMemberPriceByOrderDetilId(orderDetilId);
            detail.setOriginalPrice(memberPrice.getOriginalPrice());
            detail.setSalePrice(memberPrice.getSalePrice());
            detail.setPeriod(memberPrice.getPeriod());
        }
        return detail;
    }

    @Override
    public VipCardRecord buildVipCardRecordByOrderDetail(UserOrderDetailVo orderDetailVo) {
        if (null == orderDetailVo) {
            return null;
        }
        MemberPriceSettingsVo detail = memberPriceSettingsService.detail(orderDetailVo.getBizId());
        if (null == detail) {
            return null;
        }

        //修改用户会员时长
        Date membershipEndTime = null;
        if (orderDetailVo.getOrderClient().equals(ClientEnum.STUDENT)) {
            StudentVo studentVo = studentService.detail(orderDetailVo.getUserId());
            if (null == studentVo) {
                return null;
            }
            membershipEndTime = studentVo.getMembershipEndTime();
        } else if (orderDetailVo.getOrderClient().equals(ClientEnum.TEACHER)){
            TeacherVo teacherVo = teacherService.detail(orderDetailVo.getUserId());
            if (null == teacherVo) {
                return null;
            }
            membershipEndTime = teacherVo.getMembershipEndTime();
        } else {
            return null;
        }

        VipCardRecord vipCardRecord = new VipCardRecord();
        vipCardRecord.setUserId(orderDetailVo.getUserId());
        vipCardRecord.setOrderNo(orderDetailVo.getOrderNo());
        vipCardRecord.setSubOrderNo(orderDetailVo.getSubOrderNo());
        vipCardRecord.setVipCardId(detail.getId());
        vipCardRecord.setMsgStatus(0);
        vipCardRecord.setClientType(orderDetailVo.getOrderClient());

        if (null == membershipEndTime || membershipEndTime.before(new Date())) {
            //没有会员、会员已过期 会员卡生效时间为当前时间
            vipCardRecord.setStartTime(new Date());
        } else {
            vipCardRecord.setStartTime(membershipEndTime);
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(vipCardRecord.getStartTime());

        if (PeriodEnum.DAY.equals(detail.getPeriod())) {
            cal.add(Calendar.DAY_OF_MONTH, 1);
        } else if (PeriodEnum.MONTH.equals(detail.getPeriod())) {
            cal.add(Calendar.MONTH, 1);
        } else if (PeriodEnum.QUARTERLY.equals(detail.getPeriod())) {
            cal.add(Calendar.MONTH, 3);
        } else if (PeriodEnum.YEAR_HALF.equals(detail.getPeriod())) {
            cal.add(Calendar.MONTH, 6);
        } else if (PeriodEnum.YEAR.equals(detail.getPeriod())) {
            cal.add(Calendar.YEAR, 1);
        }
        vipCardRecord.setEndTime(cal.getTime());
        return vipCardRecord;
    }

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

    @Override
    public void pollExpireMsg() {
        //提前三天提示
        List<VipCardRecordVo> temporaryRecords = baseMapper.selectTemporaryRecord();
        //标识
        Map<Long, Long> temporaryFlagMap = new HashMap<>();
        for (VipCardRecordVo record : temporaryRecords) {
            if (null != temporaryFlagMap.get(record.getUserId())) {
                continue;
            }
            temporaryFlagMap.put(record.getUserId(), record.getUserId());
            //发送消息
            temporary3DaysSend(record.getUserId(), record.getPhone());
            record.setMsgStatus(1);
            record.setUpdateTime(new Date());

            VipCardRecord vipCardRecord = new VipCardRecord();
            BeanUtils.copyProperties(record, vipCardRecord);
            baseMapper.updateById(vipCardRecord);
        }

        //到期提示
        List<VipCardRecordVo> expireRecords = baseMapper.selectExpireRecord();
        //标识
        Map<Long, Long> expireFlagMap = new HashMap<>();
        for (VipCardRecordVo record : expireRecords) {
            if (null != expireFlagMap.get(record.getUserId())) {
                continue;
            }
            expireFlagMap.put(record.getUserId(), record.getUserId());
            //发送消息
            expireSend(record.getUserId(), record.getPhone(),record.getClientType());
            record.setMsgStatus(2);
            record.setUpdateTime(new Date());

            VipCardRecord vipCardRecord = new VipCardRecord();
            BeanUtils.copyProperties(record, vipCardRecord);
            baseMapper.updateById(vipCardRecord);
        }

    }

    // 发送会员到期3天消息推送
    private void temporary3DaysSend(Long userId, String phone) {
        Map<Long, String> receivers = new HashMap<>();
        receivers.put(userId, phone);
        try {
            String url = sysMessageService.selectConfigUrl(MessageTypeEnum.VIP_EXPIRE_THIRTY_DAY.getCode());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.VIP_EXPIRE_THIRTY_DAY,
                    receivers, null, 0, url, ClientEnum.STUDENT.getCode());
        } catch (Exception e) {
            log.error("会员到期3天极光消息推送异常,userId={}", userId);
        }

        try {
            String url = sysMessageService.selectConfigUrl(MessageTypeEnum.SMS_VIP_EXPIRE_THIRTY_DAY.getCode());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.SMS_VIP_EXPIRE_THIRTY_DAY,
                    receivers, null, 0, null, ClientEnum.STUDENT.getCode(), url);
        } catch (Exception e) {
            log.error("会员到期3天短信消息推送异常,userId={}", userId);
        }
    }

    // 发送会员到期消息推送
    private void expireSend(Long userId, String phone,ClientEnum userType) {
        Map<Long, String> receivers = new HashMap<>();
        receivers.put(userId, phone);
        try {
            String url = sysMessageService.selectConfigUrl(MessageTypeEnum.VIP_EXPIRE.getCode());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.VIP_EXPIRE,
                    receivers, null, 0, url, userType.getCode());
        } catch (Exception e) {
            log.error("会员到期3天极光消息推送异常,userId={}", userId);
        }

        try {
            String url = sysMessageService.selectConfigUrl(MessageTypeEnum.SMS_VIP_EXPIRE.getCode());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.SMS_VIP_EXPIRE,
                    receivers, null, 0, null, userType.getCode(), url);
        } catch (Exception e) {
            log.error("会员到期3天短信消息推送异常,userId={}", userId);
        }
    }
}