package com.zhongzheng.modules.grade.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.modules.goods.service.IGoodsService;
import com.zhongzheng.modules.goods.vo.GoodsVo;
import com.zhongzheng.modules.grade.domain.ClassGradeUser;
import com.zhongzheng.modules.grade.domain.UserPeriodStatus;
import com.zhongzheng.modules.grade.service.IClassGradeUserService;
import com.zhongzheng.modules.grade.service.IUserPeriodStatusService;
import com.zhongzheng.modules.inform.bo.InformUserAddBo;
import com.zhongzheng.modules.inform.service.IInformRemindService;
import com.zhongzheng.modules.inform.service.IInformUserService;
import com.zhongzheng.modules.inform.vo.InformRemindVo;
import com.zhongzheng.modules.user.service.IUserService;
import com.zhongzheng.modules.user.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.zhongzheng.modules.grade.bo.UserPeriodAddBo;
import com.zhongzheng.modules.grade.bo.UserPeriodQueryBo;
import com.zhongzheng.modules.grade.bo.UserPeriodEditBo;
import com.zhongzheng.modules.grade.domain.UserPeriod;
import com.zhongzheng.modules.grade.mapper.UserPeriodMapper;
import com.zhongzheng.modules.grade.vo.UserPeriodVo;
import com.zhongzheng.modules.grade.service.IUserPeriodService;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2021-11-22
 */
@Service
public class UserPeriodServiceImpl extends ServiceImpl<UserPeriodMapper, UserPeriod> implements IUserPeriodService {

    @Autowired
    private IUserPeriodStatusService userPeriodStatusService;

    @Autowired
    private IInformRemindService informRemindService;

    @Autowired
    private IGoodsService iGoodsService;

    @Autowired
    private IInformUserService iInformUserService;

    @Autowired
    private IClassGradeUserService iClassGradeUserService;

    @Autowired
    private IUserService iUserService;

    @Value("${aliyun.sms.schoolHoursCode}")
    private String schoolHoursCode;

    @Value("${aliyun.sms.auditFailedCode}")
    private String auditFailedCode;

    @Value("${aliyun.sms.ReminderApproval}")
    private String ReminderApproval;

    @Value("${aliyun.sms.passTheReminder}")
    private String passTheReminder;

    @Autowired
    private com.zhongzheng.modules.alisms.service.IAliSmsService IAliSmsService;


    @Override
    public UserPeriodVo queryById(Long id){
        UserPeriod db = this.baseMapper.selectById(id);
        return BeanUtil.toBean(db, UserPeriodVo.class);
    }

    @Override
    public List<UserPeriodVo> queryList(UserPeriodQueryBo bo) {
        LambdaQueryWrapper<UserPeriod> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, UserPeriod::getUserId, bo.getUserId());
        lqw.eq(bo.getCourseId() != null, UserPeriod::getCourseId, bo.getCourseId());
        lqw.eq(bo.getSectionId() != null, UserPeriod::getSectionId, bo.getSectionId());
        lqw.eq(bo.getGoodsId() != null, UserPeriod::getGoodsId, bo.getGoodsId());
        lqw.eq(bo.getType() != null, UserPeriod::getType, bo.getType());
        lqw.eq(bo.getExamId() != null, UserPeriod::getExamId, bo.getExamId());
        lqw.eq(bo.getModuleId() != null, UserPeriod::getModuleId, bo.getModuleId());
        lqw.eq(bo.getChapterId() != null, UserPeriod::getChapterId, bo.getChapterId());
        return entity2Vo(this.list(lqw));
    }

    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<UserPeriodVo> entity2Vo(Collection<UserPeriod> collection) {
        List<UserPeriodVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, UserPeriodVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<UserPeriod> page = (Page<UserPeriod>)collection;
            Page<UserPeriodVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(UserPeriodAddBo bo) {
        UserPeriod add = BeanUtil.toBean(bo, UserPeriod.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        return this.save(add);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(UserPeriodEditBo bo) {
        List<UserPeriodStatus> list = new ArrayList<>();
        for (Long aLong : bo.getId()) {
            UserPeriodStatus userPeriodStatus = new UserPeriodStatus();
            userPeriodStatus.setPeriodStatus(1);
            userPeriodStatus.setStatus(bo.getStatus());
            userPeriodStatus.setUpdateTime(DateUtils.getNowTime());
            LambdaQueryWrapper<UserPeriodStatus> lqw = Wrappers.lambdaQuery();
            lqw.eq( UserPeriodStatus::getPeriodId, aLong);
            lqw.eq( UserPeriodStatus::getPeriodStatus, 1);
            userPeriodStatusService.update(userPeriodStatus,lqw);
            list = userPeriodStatusService.list(lqw);
        }
        if (!CollectionUtils.isEmpty(list)){
            UserPeriodStatus userPeriodStatus = list.get(0);
            UserPeriodVo userPeriodVo = this.queryById(userPeriodStatus.getPeriodId());

            LambdaQueryWrapper<UserPeriod> lqw = Wrappers.lambdaQuery();
            lqw.eq(userPeriodVo.getUserId() != null, UserPeriod::getUserId, userPeriodVo.getUserId());
            lqw.eq(userPeriodVo.getGoodsId() != null, UserPeriod::getGoodsId, userPeriodVo.getGoodsId());
            lqw.eq(userPeriodVo.getGradeId() != null, UserPeriod::getGradeId, userPeriodVo.getGradeId());
            List<UserPeriod> listPeriodVo = this.list(lqw);
            for (UserPeriod userPeriod : listPeriodVo) {
                LambdaQueryWrapper<UserPeriodStatus> userPeriods = Wrappers.lambdaQuery();
                userPeriods.eq(UserPeriodStatus::getPeriodId, userPeriod.getId());
                userPeriods.eq(UserPeriodStatus::getPeriodStatus, 1);
                userPeriods.eq(UserPeriodStatus::getStatus, 1);
                List<UserPeriodStatus> list1 = userPeriodStatusService.list(userPeriods);
                if (CollectionUtils.isEmpty(list1)){
                    return true;
                }
            }
            UserPeriodEditBo userPeriodEditBo = new UserPeriodEditBo();
            userPeriodEditBo.setUserId(userPeriodVo.getUserId());
            userPeriodEditBo.setGoodsId(userPeriodVo.getGoodsId());
            userPeriodEditBo.setGradeId(userPeriodVo.getGradeId());
            sendPeriodSMS(userPeriodEditBo);
            sendPeriodSevenSMS(userPeriodEditBo);

            LambdaQueryWrapper<ClassGradeUser> classGradeUser = Wrappers.lambdaQuery();
            classGradeUser.eq( ClassGradeUser::getUserId, bo.getUserId());
            classGradeUser.eq( ClassGradeUser::getGradeId, bo.getGradeId());
            ClassGradeUser classGradeUser1 = new ClassGradeUser();
            classGradeUser1.setPeriodStatus(1);
            classGradeUser1.setUpdateTime(DateUtils.getNowTime());
            iClassGradeUserService.update(classGradeUser1,classGradeUser);
        }
        return true;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(UserPeriod entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editPeriodAll(UserPeriodEditBo bo) {
            LambdaQueryWrapper<UserPeriod> lqw = Wrappers.lambdaQuery();
            lqw.eq(bo.getUserId() != null, UserPeriod::getUserId, bo.getUserId());
            lqw.eq(bo.getGoodsId() != null, UserPeriod::getGoodsId, bo.getGoodsId());
            lqw.eq(bo.getGradeId() != null, UserPeriod::getGradeId, bo.getGradeId());
            List<UserPeriod> list = this.list(lqw);
            for (UserPeriod userPeriod : list) {
                UserPeriodStatus userPeriodStatus = new UserPeriodStatus();
                userPeriodStatus.setPeriodStatus(1);
                userPeriodStatus.setStatus(bo.getStatus());
                userPeriodStatus.setUpdateTime(DateUtils.getNowTime());
                LambdaQueryWrapper<UserPeriodStatus> userPeriods = Wrappers.lambdaQuery();
                userPeriods.eq( UserPeriodStatus::getPeriodId, userPeriod.getId());
                userPeriods.eq( UserPeriodStatus::getPeriodStatus, 1);
                userPeriods.eq( UserPeriodStatus::getStatus, 2);
                userPeriodStatusService.update(userPeriodStatus,userPeriods);
            }
        LambdaQueryWrapper<ClassGradeUser> classGradeUser = Wrappers.lambdaQuery();
        classGradeUser.eq( ClassGradeUser::getUserId, bo.getUserId());
        classGradeUser.eq( ClassGradeUser::getGradeId, bo.getGradeId());
        ClassGradeUser classGradeUser1 = new ClassGradeUser();
        classGradeUser1.setPeriodStatus(1);
        classGradeUser1.setUpdateTime(DateUtils.getNowTime());
        iClassGradeUserService.update(classGradeUser1,classGradeUser);
            sendPeriodSMS(bo);
            sendPeriodSevenSMS(bo);
        return true;
    }

    private void sendPeriodSMS(UserPeriodEditBo bo) {
        GoodsVo goodsVo1 = iGoodsService.queryById(bo.getGoodsId());
        if (bo.getStatus().equals(1)){
        InformRemindVo informRemindVo = informRemindService.queryById(9L);
        if (!CollectionUtils.isEmpty(informRemindVo.getInformRemindBusiness()) && !CollectionUtils.isEmpty(informRemindVo.getInformRemindBusiness().stream().filter(informRemindBusinessVo -> informRemindBusinessVo.getBusinessId().equals(goodsVo1.getBusinessId())).collect(Collectors.toList()))) {
            if (informRemindVo.getWayStatus().equals(1)) {
                InformUserAddBo informUserAddBo = new InformUserAddBo();
                informUserAddBo.setUserId(bo.getUserId());
                informUserAddBo.setSendStatus(1);
                informUserAddBo.setSendTime(DateUtils.getNowTime());
                informUserAddBo.setCreateTime(DateUtils.getNowTime());
                informUserAddBo.setUpdateTime(DateUtils.getNowTime());
                informUserAddBo.setRemindId(9L);
                informUserAddBo.setSystemStatus(1);
                informUserAddBo.setRemind("学时机构审核通过提醒");
                informUserAddBo.setGoodsId(bo.getGoodsId());
                informUserAddBo.setText("尊敬的用户：你已完成本课程的所有学时学习，经机构审核通过，需注册中心复审后即可获得继续教育学时，审核时间约15个工作日。");
                iInformUserService.insertByAddBo(informUserAddBo);
            }
            if (informRemindVo.getNoteStatus().equals(1)) {
                InformUserAddBo informUserAddBo = new InformUserAddBo();
                informUserAddBo.setUserId(bo.getUserId());
                informUserAddBo.setSendTime(DateUtils.getNowTime());
                informUserAddBo.setSendStatus(1);
                informUserAddBo.setCreateTime(DateUtils.getNowTime());
                informUserAddBo.setUpdateTime(DateUtils.getNowTime());
                informUserAddBo.setRemindId(9L);
                informUserAddBo.setSystemStatus(3);
                informUserAddBo.setRemind("学时机构审核通过提醒");
                informUserAddBo.setGoodsId(bo.getGoodsId());
                informUserAddBo.setText("尊敬的用户：你已完成本课程的所有学时学习，经机构审核通过，需注册中心复审后即可获得继续教育学时，审核时间约15个工作日。");
                iInformUserService.insertByAddBo(informUserAddBo);
                UserVo userVo = iUserService.queryById(bo.getUserId());
                Map<String, Object> param = new HashMap<>();
                IAliSmsService.sendInformSms(userVo.getTelphone(), JSON.toJSONString(param), schoolHoursCode);
            }
        }
    }else {
            InformRemindVo informRemindTwoVo = informRemindService.queryById(10L);
            if (!CollectionUtils.isEmpty(informRemindTwoVo.getInformRemindBusiness()) && !CollectionUtils.isEmpty(informRemindTwoVo.getInformRemindBusiness().stream().filter(informRemindBusinessVo -> informRemindBusinessVo.getBusinessId().equals(goodsVo1.getBusinessId())).collect(Collectors.toList()))) {

                if (informRemindTwoVo.getWayStatus().equals(1)) {
                    InformUserAddBo informUserAddBo = new InformUserAddBo();
                    informUserAddBo.setUserId(bo.getUserId());
                    informUserAddBo.setSendStatus(1);
                    informUserAddBo.setCreateTime(DateUtils.getNowTime());
                    informUserAddBo.setSendTime(DateUtils.getNowTime());
                    informUserAddBo.setUpdateTime(DateUtils.getNowTime());
                    informUserAddBo.setRemindId(10L);
                    informUserAddBo.setSystemStatus(1);
                    informUserAddBo.setRemind("学时机构审核不通过提醒");
                    informUserAddBo.setGoodsId(bo.getGoodsId());
                    informUserAddBo.setText("尊敬的用户：您购买的"+goodsVo1.getGoodsName()+"课程学时机构审核不通过，为了不影响您的学习进度，请点击立即重学进行重学。");
                    iInformUserService.insertByAddBo(informUserAddBo);
                }
                if (informRemindTwoVo.getNoteStatus().equals(1)) {
                    InformUserAddBo informUserAddBo = new InformUserAddBo();
                    informUserAddBo.setUserId(bo.getUserId());
                    informUserAddBo.setSendTime(DateUtils.getNowTime());
                    informUserAddBo.setSendStatus(1);
                    informUserAddBo.setCreateTime(DateUtils.getNowTime());
                    informUserAddBo.setUpdateTime(DateUtils.getNowTime());
                    informUserAddBo.setRemindId(10L);
                    informUserAddBo.setSystemStatus(3);
                    informUserAddBo.setRemind("学时机构审核不通过提醒");
                    informUserAddBo.setGoodsId(bo.getGoodsId());
                    informUserAddBo.setText("尊敬的用户：您购买的"+goodsVo1.getGoodsName()+"课程学时机构审核不通过，为了不影响您的学习进度，请点击立即重学进行重学。");
                    iInformUserService.insertByAddBo(informUserAddBo);
                    UserVo userVo = iUserService.queryById(bo.getUserId());
                    Map<String, Object> param = new HashMap<>();
                    param.put("goods", goodsVo1.getGoodsName());
                    IAliSmsService.sendInformSms(userVo.getTelphone(), JSON.toJSONString(param), auditFailedCode);
                }
            }
        }
    }

    private void sendPeriodSevenSMS(UserPeriodEditBo bo) {
        GoodsVo goodsVo1 = iGoodsService.queryById(bo.getGoodsId());
        if (bo.getStatus().equals(1)){
            InformRemindVo informRemindVo = informRemindService.queryById(11L);
            if (!CollectionUtils.isEmpty(informRemindVo.getInformRemindBusiness()) && !CollectionUtils.isEmpty(informRemindVo.getInformRemindBusiness().stream().filter(informRemindBusinessVo -> informRemindBusinessVo.getBusinessId().equals(goodsVo1.getBusinessId())).collect(Collectors.toList()))) {
                if (informRemindVo.getWayStatus().equals(1)) {
                    InformUserAddBo informUserAddBo = new InformUserAddBo();
                    informUserAddBo.setUserId(bo.getUserId());
                    informUserAddBo.setSendStatus(1);
                    informUserAddBo.setSendTime(DateUtils.getNowTime());
                    informUserAddBo.setCreateTime(DateUtils.getNowTime());
                    informUserAddBo.setUpdateTime(DateUtils.getNowTime());
                    informUserAddBo.setRemindId(11L);
                    informUserAddBo.setSystemStatus(1);
                    informUserAddBo.setRemind("学时机构审核通过提醒");
                    informUserAddBo.setGoodsId(bo.getGoodsId());
                    informUserAddBo.setText("尊敬的用户：你已完成本课程的所有学时机构审核通过。");
                    iInformUserService.insertByAddBo(informUserAddBo);
                }
                if (informRemindVo.getNoteStatus().equals(1)) {
                    InformUserAddBo informUserAddBo = new InformUserAddBo();
                    informUserAddBo.setUserId(bo.getUserId());
                    informUserAddBo.setSendTime(DateUtils.getNowTime());
                    informUserAddBo.setSendStatus(1);
                    informUserAddBo.setCreateTime(DateUtils.getNowTime());
                    informUserAddBo.setUpdateTime(DateUtils.getNowTime());
                    informUserAddBo.setRemindId(11L);
                    informUserAddBo.setSystemStatus(3);
                    informUserAddBo.setRemind("学时机构审核通过提醒");
                    informUserAddBo.setGoodsId(bo.getGoodsId());
                    informUserAddBo.setText("尊敬的用户：你已完成本课程的所有学时机构审核通过。");
                    iInformUserService.insertByAddBo(informUserAddBo);
                    UserVo userVo = iUserService.queryById(bo.getUserId());
                    Map<String, Object> param = new HashMap<>();
                    IAliSmsService.sendInformSms(userVo.getTelphone(), JSON.toJSONString(param), ReminderApproval);
                }
            }
        }else {
            InformRemindVo informRemindTwoVo = informRemindService.queryById(12L);
            if (!CollectionUtils.isEmpty(informRemindTwoVo.getInformRemindBusiness()) && !CollectionUtils.isEmpty(informRemindTwoVo.getInformRemindBusiness().stream().filter(informRemindBusinessVo -> informRemindBusinessVo.getBusinessId().equals(goodsVo1.getBusinessId())).collect(Collectors.toList()))) {

                if (informRemindTwoVo.getWayStatus().equals(1)) {
                    InformUserAddBo informUserAddBo = new InformUserAddBo();
                    informUserAddBo.setUserId(bo.getUserId());
                    informUserAddBo.setSendStatus(1);
                    informUserAddBo.setCreateTime(DateUtils.getNowTime());
                    informUserAddBo.setSendTime(DateUtils.getNowTime());
                    informUserAddBo.setUpdateTime(DateUtils.getNowTime());
                    informUserAddBo.setRemindId(12L);
                    informUserAddBo.setSystemStatus(1);
                    informUserAddBo.setRemind("学时机构审核不通过提醒");
                    informUserAddBo.setGoodsId(bo.getGoodsId());
                    informUserAddBo.setText("尊敬的用户：您购买的"+goodsVo1.getGoodsName()+"课程学时审核不通过，为了不影响您的学习进度，请点击立即重学进行重学。");
                    iInformUserService.insertByAddBo(informUserAddBo);
                }
                if (informRemindTwoVo.getNoteStatus().equals(1)) {
                    InformUserAddBo informUserAddBo = new InformUserAddBo();
                    informUserAddBo.setUserId(bo.getUserId());
                    informUserAddBo.setSendTime(DateUtils.getNowTime());
                    informUserAddBo.setSendStatus(1);
                    informUserAddBo.setCreateTime(DateUtils.getNowTime());
                    informUserAddBo.setUpdateTime(DateUtils.getNowTime());
                    informUserAddBo.setRemindId(12L);
                    informUserAddBo.setSystemStatus(3);
                    informUserAddBo.setRemind("学时机构审核不通过提醒");
                    informUserAddBo.setGoodsId(bo.getGoodsId());
                    informUserAddBo.setText("尊敬的用户：您购买的"+goodsVo1.getGoodsName()+"课程学时审核不通过，为了不影响您的学习进度，请点击立即重学进行重学。");
                    iInformUserService.insertByAddBo(informUserAddBo);
                    UserVo userVo = iUserService.queryById(bo.getUserId());
                    Map<String, Object> param = new HashMap<>();
                    param.put("goods", goodsVo1.getGoodsName());
                    IAliSmsService.sendInformSms(userVo.getTelphone(), JSON.toJSONString(param), passTheReminder);
                }
            }
        }
    }
}
