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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dao.TeacherDao;
import com.yonge.cooleshow.biz.dal.dto.req.AuthOperaReq;
import com.yonge.cooleshow.biz.dal.dto.search.AuthEntryRecordSearch;
import com.yonge.cooleshow.biz.dal.entity.Teacher;
import com.yonge.cooleshow.biz.dal.enums.AuthStatusEnum;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.MessageTypeEnum;
import com.yonge.cooleshow.biz.dal.service.SysMessageService;
import com.yonge.cooleshow.biz.dal.vo.MusicianAuthEntryRecordVo;
import com.yonge.cooleshow.biz.dal.vo.TeacherVo;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.base.string.StringPool;
import com.yonge.toolset.base.util.StringUtil;
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.TeacherAuthMusicianRecord;
import com.yonge.cooleshow.biz.dal.dao.TeacherAuthMusicianRecordDao;
import com.yonge.cooleshow.biz.dal.service.TeacherAuthMusicianRecordService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
public class TeacherAuthMusicianRecordServiceImpl extends ServiceImpl<TeacherAuthMusicianRecordDao, TeacherAuthMusicianRecord> implements TeacherAuthMusicianRecordService {
    private static final Logger log = LoggerFactory.getLogger(TeacherAuthMusicianRecordServiceImpl.class);

    @Autowired
    private SysMessageService sysMessageService;

    @Autowired
    private TeacherDao teacherDao;

    @Override
    public IPage<MusicianAuthEntryRecordVo> selectPage(IPage<MusicianAuthEntryRecordVo> page, AuthEntryRecordSearch authEntryRecordSearch) {
        return page.setRecords(baseMapper.selectPage(page, authEntryRecordSearch));
    }

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

    @Override
    public AuthStatusEnum getMusicianAuthStatus(Long id) {
        TeacherAuthMusicianRecord lastRecordByUserId = getLastRecordByUserId(id);
        return null == lastRecordByUserId ? null : lastRecordByUserId.getTeacherAuthStatus();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult<Boolean> doApply(Long userId) {
        //判断用户是否已经提交申请
        if (hasApply(userId)) {
            return HttpResponseResult.failed("已经提交过申请");
        }
        //判断用户是否已经通过申请
        Teacher teacher = teacherDao.selectById(userId);
        if (YesOrNoEnum.YES.equals(teacher.getMusicianFlag())) {
            return HttpResponseResult.failed("已经通过审批");
        }

        TeacherAuthMusicianRecord record = new TeacherAuthMusicianRecord();
        record.setUserId(userId);
        record.setTeacherAuthStatus(AuthStatusEnum.DOING);
        return HttpResponseResult.status(baseMapper.insert(record) > 0);
    }

    @Override
    public TeacherAuthMusicianRecord getLastRecordByUserId(Long userId) {
        return baseMapper.getLastRecordByUserId(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult<Boolean> doAuth(AuthOperaReq authOperaReq, SysUser sysUser) throws Exception {
        Long[] ids = StringUtil.toLongArray(StringPool.COMMA, authOperaReq.getId());
        for (Long id : ids) {
            TeacherAuthMusicianRecord build = baseMapper.selectById(id);
            if (null == build || !AuthStatusEnum.DOING.equals(build.getTeacherAuthStatus())) {
                continue;
            }

            build.setTeacherAuthStatus(authOperaReq.getPass() ? AuthStatusEnum.PASS : AuthStatusEnum.UNPASS);
            build.setReason(authOperaReq.getReason());
            build.setVerifyUserId(sysUser.getId());
            build.setUpdateTime(new Date());

            //修改teacher表
            TeacherVo teacher = teacherDao.detail(build.getUserId());
            if (null == teacher) {
                continue;
            }
            if (YesOrNoEnum.YES.equals(teacher.getMusicianFlag())) {
                continue;
            }

            teacher.setMusicianFlag(authOperaReq.getPass() ? YesOrNoEnum.YES : YesOrNoEnum.NO);
            teacher.setMusicianDate(new Date());
            teacher.setUpdateTime(new Date());

            Teacher newTeacher = new Teacher();
            BeanUtils.copyProperties(teacher, newTeacher);
            teacherDao.updateById(newTeacher);

            // 发送审核通知
            authSend(teacher.getUserId(), teacher.getPhone(), authOperaReq.getPass(), authOperaReq.getReason());
            baseMapper.updateById(build);
        }
        return HttpResponseResult.succeed(true);
    }

    // 发送审核通知
    private void authSend(Long userId, String phone, Boolean isPass, String reason) {
        Map<Long, String> receivers = new HashMap<>();
        receivers.put(userId, phone);
        if (isPass) {
            try {
                String url = sysMessageService.selectConfigUrl(MessageTypeEnum.MUSICIAN_AUTH_PASS.getCode());
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.MUSICIAN_AUTH_PASS,
                        receivers, null, 0, url, ClientEnum.TEACHER.getCode());
            } catch (Exception e) {
                log.error("音乐人认证极光消息推送异常,userId={}", userId);
            }
            try {
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.SMS_MUSICIAN_AUTH_PASS,
                        receivers, null, 0, null, ClientEnum.TEACHER.getCode());
            } catch (Exception e) {
                log.error("音乐人认证短信消息推送异常,userId={}", userId);
            }
        } else {
            try {
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.MUSICIAN_AUTH_FAIL,
                        receivers, null, 0, null, ClientEnum.TEACHER.getCode(), reason);
            } catch (Exception e) {
                log.error("音乐人认证极光消息推送异常,userId={}", userId);
            }

            try {
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.SMS_MUSICIAN_AUTH_FAIL,
                        receivers, null, 0, null, ClientEnum.TEACHER.getCode(), reason);
            } catch (Exception e) {
                log.error("音乐人认证短信消息推送异常,userId={}", userId);
            }
        }
    }

    /***
     * 判断用户是否已经提交申请
     * @author liweifan
     * @param: userId
     * @updateTime 2022/3/21 11:37
     * @return: java.lang.Boolean
     */
    private boolean hasApply(Long userId) {
        TeacherAuthMusicianRecord teacherAuthMusicianRecord = baseMapper.selectOne(Wrappers.<TeacherAuthMusicianRecord>query().lambda()
                .eq(TeacherAuthMusicianRecord::getUserId, userId)
                .eq(TeacherAuthMusicianRecord::getTeacherAuthStatus, 1));
        return teacherAuthMusicianRecord != null;
    }

}