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.dto.search.VipRecordSearch;
import com.yonge.cooleshow.biz.dal.entity.ActivityReward;
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.enums.SourceTypeEnum;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.*;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.mybatis.support.PageUtil;
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;
        }
        // 按时间区分 个数
        Integer timeNum = 0;
        String periodType  = null;

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

        return getVipCardRecord(orderDetailVo.getUserId(),orderDetailVo.getOrderClient(),orderDetailVo.getOrderNo(),
                                orderDetailVo.getSubOrderNo(),periodType,detail.getId(),timeNum,SourceTypeEnum.ORDER,orderDetailVo.getUserId(),"会员购买");
    }

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

        return getVipCardRecord(userId,client,activityId.toString(),null,activityReward.getUnit().toString(),
                                null,activityReward.getNum(),SourceTypeEnum.ACTIVITY,userId,activityName);
    }

    @Override
    public VipCardRecord getVipCardRecord(Long userId, ClientEnum client, String orderNo, String subOrderNo, String periodType,
                                          Long memberPriceSettingsId, Integer timeNum, SourceTypeEnum sourceType, Long createBy, String reason) {
        //修改用户会员时长
        Date membershipEndTime = null;
        if (client.equals(ClientEnum.STUDENT)) {
            StudentVo studentVo = studentService.detail(userId);
            if (null == studentVo) {
                return null;
            }
            membershipEndTime = studentVo.getMembershipEndTime();
        } else if (client.equals(ClientEnum.TEACHER)){
            TeacherVo teacherVo = teacherService.detail(userId);
            if (null == teacherVo) {
                return null;
            }
            membershipEndTime = teacherVo.getMembershipEndTime();
        } else {
            return null;
        }

        VipCardRecord vipCardRecord = new VipCardRecord();
        vipCardRecord.setUserId(userId);
        vipCardRecord.setOrderNo(orderNo);
        vipCardRecord.setSubOrderNo(subOrderNo);
        vipCardRecord.setVipCardId(memberPriceSettingsId);
        vipCardRecord.setMsgStatus(0);
        vipCardRecord.setSourceType(sourceType);
        vipCardRecord.setClientType(client);
        vipCardRecord.setTimes(timeNum);
        vipCardRecord.setType(PeriodEnum.valueOf(periodType));
        vipCardRecord.setCreateBy(createBy);
        vipCardRecord.setReason(reason);

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

    }

    @Override
    public PageInfo<VipRecordVo> vipRecord(VipRecordSearch recordSearch) {
        return PageUtil.pageInfo(baseMapper.selectVipRecord(PageUtil.getPage(recordSearch),recordSearch));


    }

    // 发送会员到期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);
        }
    }
}