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.dao.TeacherStyleVideoDao;
import com.yonge.cooleshow.biz.dal.dto.req.AuthOperaReq;
import com.yonge.cooleshow.biz.dal.dto.search.TeacherStyleSearch;
import com.yonge.cooleshow.biz.dal.dto.search.TeacherStyleVideoSearch;
import com.yonge.cooleshow.biz.dal.entity.TeacherStyleVideo;
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.enums.TeacherTagEnum;
import com.yonge.cooleshow.biz.dal.service.SysMessageService;
import com.yonge.cooleshow.biz.dal.service.TeacherService;
import com.yonge.cooleshow.biz.dal.service.TeacherStyleVideoService;
import com.yonge.cooleshow.biz.dal.vo.TeacherStyleVideoVo;
import com.yonge.cooleshow.biz.dal.vo.TeacherVo;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
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.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


@Service
public class TeacherStyleVideoServiceImpl extends ServiceImpl<TeacherStyleVideoDao, TeacherStyleVideo> implements TeacherStyleVideoService {

    private static final Logger log = LoggerFactory.getLogger(TeacherStyleVideoService.class);

    @Autowired
    private SysMessageService sysMessageService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private SysUserFeignService sysUserFeignService;

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

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean doAuth(AuthOperaReq authOperaReq, SysUser sysUser) throws Exception {
        Long[] ids = StringUtil.toLongArray(StringPool.COMMA, authOperaReq.getId());
        for (Long id : ids) {
            TeacherStyleVideo build = baseMapper.selectById(id);
            if (!AuthStatusEnum.DOING.equals(build.getAuthStatus())) {
                continue;
            }
            build.setAuthStatus(authOperaReq.getPass() ? AuthStatusEnum.PASS : AuthStatusEnum.UNPASS);
            build.setReason(authOperaReq.getReason());
            build.setVerifyUserId(sysUser.getId());
            build.setUpdateTime(new Date());
            boolean b = baseMapper.updateById(build) > 0;
            if (b) {
                sendAuthMessage(authOperaReq.getPass(), build.getUserId(), authOperaReq.getReason());
                if (authOperaReq.getPass()) {
                    teacherService.setTeacherTag(build.getUserId(), TeacherTagEnum.STYLE);
                }
            }
        }
        return true;
    }

    /**
     * 发送个人风采审核
     *
     * @param pass 通过/失败
     */
    private void sendAuthMessage(Boolean pass, Long teacherId, String remark) {
        if (Boolean.TRUE.equals(pass)) {
            try {
                SysUser user = sysUserFeignService.queryUserById(teacherId);
                Map<Long, String> teacherReceivers = new HashMap<>();
                teacherReceivers.put(user.getId(), user.getPhone());
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.TEACHER_STYLE_VIDEO_SUCCESS,
                        teacherReceivers, null, 0, null, ClientEnum.TEACHER.getCode());
            } catch (Exception e) {
                log.warn("老师个人风采审核成功消息发送失败，{}", e.getMessage());
            }
        } else {
            try {
                SysUser user = sysUserFeignService.queryUserById(teacherId);
                Map<Long, String> teacherReceivers = new HashMap<>();
                teacherReceivers.put(user.getId(), user.getPhone());
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.TEACHER_STYLE_VIDEO_FAIL,
                        teacherReceivers, null, 0, null, ClientEnum.TEACHER.getCode(), remark);
            } catch (Exception e) {
                log.warn("老师个人风采审核失败消息发送失败，{}", e.getMessage());
            }
        }
    }

    @Override
    public List<TeacherStyleVideo> selectListByUserId(Long userId) {
        return baseMapper.selectListByUserId(userId);
    }

    @Override
    public Integer removeByUserIdAndOldIds(Long userId, List<Long> oldIds) {
        return baseMapper.removeByUserIdAndOldIds(userId, oldIds);
    }

    @Override
    public boolean batchAddStyleVideo(List<TeacherStyleVideo> createList) {
        return saveBatch(createList);
    }

    @Override
    public IPage<TeacherStyleVideoVo> stylePage(IPage<TeacherStyleVideoVo> page, TeacherStyleSearch query) {
        return page.setRecords(baseMapper.stylePage(page, query));
    }

    @Override
    public HttpResponseResult<Boolean> addVideoBrowse(Long videoId) {
        Integer num = baseMapper.addVideoBrowse(videoId);
        return HttpResponseResult.succeed(num > 0);
    }
}