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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.req.TeacherApplyDetailReq;
import com.yonge.cooleshow.biz.dal.dto.search.AuthEntryRecordSearch;
import com.yonge.cooleshow.biz.dal.entity.Teacher;
import com.yonge.cooleshow.biz.dal.entity.TeacherStyleVideo;
import com.yonge.cooleshow.biz.dal.enums.*;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.support.WrapperUtil;
import com.yonge.cooleshow.biz.dal.vo.TeacherAuthEntryRecordVo;
import com.yonge.cooleshow.biz.dal.vo.TeacherVo;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.UserFirstTimeTypeEnum;
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 com.yonge.toolset.utils.string.ValueUtil;
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.TeacherAuthEntryRecord;
import com.yonge.cooleshow.biz.dal.dao.TeacherAuthEntryRecordDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TeacherAuthEntryRecordServiceImpl extends ServiceImpl<TeacherAuthEntryRecordDao, TeacherAuthEntryRecord> implements TeacherAuthEntryRecordService {

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

    @Autowired
    private SysMessageService sysMessageService;
    @Autowired
    private TeacherStyleVideoService teacherStyleVideoService;
    @Autowired
    private UserFirstTimeService userFirstTimeService;
    @Resource
    private TeacherDao teacherDao;

    @Autowired
    private TeacherService teacherService;

    @Override
    public TeacherAuthEntryRecordVo detail(Long id) {
        TeacherAuthEntryRecordVo detail = baseMapper.detail(id);
        //查询上一次的提交
        TeacherAuthEntryRecordVo lastDetil = baseMapper.lastDetil(id, detail.getUserId());
        detail.setLastDetil(lastDetil);
        return detail;
    }

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

    @Override
    public IPage<TeacherAuthEntryRecordVo> historyPage(IPage<TeacherAuthEntryRecordVo> page, AuthEntryRecordSearch search) {
        return page.setRecords(baseMapper.historyPage(page, search));
    }

    @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) {
            TeacherAuthEntryRecord 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.getEntryFlag())) {
                continue;
            }*/
            if (authOperaReq.getPass()) {
                teacher.setSubjectId(StringUtil.isEmpty(teacher.getSubjectId()) ? build.getSubjectId() : teacher.getSubjectId());
                teacher.setIntroduction(StringUtil.isEmpty(teacher.getIntroduction()) ? build.getIntroduction() : teacher.getIntroduction());
                teacher.setGraduateSchool(StringUtil.isEmpty(teacher.getGraduateSchool()) ? build.getGraduateSchool() : teacher.getGraduateSchool());
                teacher.setSubject(StringUtil.isEmpty(teacher.getSubject()) ? build.getSubject() : teacher.getSubject());
                teacher.setGradCertificate( StringUtil.isEmpty(build.getGradCertificate())?"":build.getGradCertificate());
                teacher.setDegreeCertificate(StringUtil.isEmpty( build.getDegreeCertificate())?"":build.getDegreeCertificate());
                teacher.setTeacherCertificate( StringUtil.isEmpty(build.getTeacherCertificate())?"":build.getTeacherCertificate());

                //老师风采视频
                String styleVideoJson = build.getStyleVideoJson();
                saveStyleVideo(styleVideoJson, build.getUserId(), sysUser.getId());

                setTag(authOperaReq, build, teacher);
                //记录达人认证时间
                userFirstTimeService.recordTime(build.getUserId(), ClientEnum.TEACHER, UserFirstTimeTypeEnum.ENTRY);

            }
            if (null == teacher.getEntryFlag() || YesOrNoEnum.NO.equals(teacher.getEntryFlag())) {
                teacher.setEntryFlag(authOperaReq.getPass() ? YesOrNoEnum.YES : YesOrNoEnum.NO);
            }
            teacher.setEntryAuthDate(new Date());
            teacher.setUpdateTime(new Date());

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

            if (authOperaReq.getPass()) {
                teacherService.setTeacherTag(build.getUserId(), TeacherTagEnum.STYLE);
            }

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

    private void setTag(AuthOperaReq authOperaReq, TeacherAuthEntryRecord build, TeacherVo teacher) {
        if (authOperaReq.getPass()) {
            if (!StringUtil.isEmpty(teacher.getTeacherCertificate())) {
                teacher.setTeacherDate(new Date());
                teacher.setTeacherFlag(YesOrNoEnum.YES);
            } else {
                teacher.setTeacherFlag(YesOrNoEnum.NO);
                teacher.setTeacherDate(null);
            }
        }
        if (authOperaReq.getPass()) {
            if (!StringUtil.isEmpty(teacher.getDegreeCertificate()) && !StringUtil.isEmpty(teacher.getGradCertificate())) {
                teacher.setDegreeFlag(YesOrNoEnum.YES);
                teacher.setDegreeDate(new Date());
            } else  {
                teacher.setDegreeFlag(YesOrNoEnum.NO);
                teacher.setDegreeDate(null);
            }
        }
    }

    /**
     * 保存老师风采视频
     *
     * @param styleVideoJson
     * @param userId
     * @param verifyUserId
     */
    private void saveStyleVideo(String styleVideoJson, Long userId, Long verifyUserId) {

        // 如果已经有认证审核的数据，就不在保存

        Integer count = teacherStyleVideoService.lambdaQuery()
                .eq(TeacherStyleVideo::getUserId,userId)
                .eq(TeacherStyleVideo::getEntryFlag, YesOrNoEnum.YES)
                .count();
        if (count > 0) {
            return;
        }

        if (!StringUtil.isEmpty(styleVideoJson)) {
            JSONArray jsonArray = JSONObject.parseArray(styleVideoJson);
            List<TeacherStyleVideo> batchVideoList = new ArrayList<>();

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                TeacherStyleVideo video = new TeacherStyleVideo();
                video.setUserId(userId);
                video.setCover(jsonObject.getString("cover"));
                video.setVideoUrl(jsonObject.getString("videoUrl"));
                video.setAuthStatus(AuthStatusEnum.PASS);
                video.setVerifyUserId(verifyUserId);
                video.setEntryFlag(YesOrNoEnum.YES);
                batchVideoList.add(video);
            }
            if (!CollectionUtils.isEmpty(batchVideoList)) {
                teacherStyleVideoService.batchAddStyleVideo(batchVideoList);
            }
        }
    }

    // 发送审核通知
    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.TEACHER_AUTH_PASS.getCode());
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.TEACHER_AUTH_PASS,
                        receivers, null, 0, url, ClientEnum.TEACHER.getCode());
            } catch (Exception e) {
                log.error("入驻审核极光消息推送异常,userId={}", userId);
            }
            try {
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.SMS_TEACHER_AUTH_PASS,
                        receivers, null, 0, null, ClientEnum.TEACHER.getCode());
            } catch (Exception e) {
                log.error("入驻审核短信消息推送异常,userId={}", userId);
            }
        } else {
            try {
                String url = sysMessageService.selectConfigUrl(MessageTypeEnum.TEACHER_AUTH_FAIL.getCode());
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.TEACHER_AUTH_FAIL,
                        receivers, null, 0, url, ClientEnum.TEACHER.getCode(), reason);
            } catch (Exception e) {
                log.error("入驻审核极光消息推送异常,userId={}", userId);
            }

            try {
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.SMS_TEACHER_AUTH_FAIL,
                        receivers, null, 0, null, ClientEnum.TEACHER.getCode(), reason);
            } catch (Exception e) {
                log.error("入驻审核短信消息推送异常,userId={}", userId);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult<Boolean> doApply(TeacherApplyDetailReq teacherApplyDetailDto, SysUser sysUser) throws Exception {
        teacherApplyDetailDto.setUserId(sysUser.getId());
        //判断用户是否已经提交申请
        if (hasApply(sysUser.getId())) {
            return HttpResponseResult.failed("已经提交过申请");
        }

        //新增申请记录
        TeacherAuthEntryRecord teacherAuthEntryRecord = new TeacherAuthEntryRecord();
        BeanUtils.copyProperties(teacherApplyDetailDto, teacherAuthEntryRecord);
        teacherAuthEntryRecord.setTeacherAuthStatus(AuthStatusEnum.DOING);
        teacherAuthEntryRecord.setTeacherAuthType(AuthTypeEnum.MODIFY);

        List<TeacherAuthEntryRecord> olds = baseMapper.selectList(Wrappers.<TeacherAuthEntryRecord>query().lambda()
                .eq(TeacherAuthEntryRecord::getUserId, sysUser.getId()));
        if (CollectionUtils.isEmpty(olds)) {
            teacherAuthEntryRecord.setTeacherAuthType(AuthTypeEnum.ADD);
        }
        return HttpResponseResult.status(baseMapper.insert(teacherAuthEntryRecord) > 0);
    }

    @Override
    public TeacherAuthEntryRecordVo getLastRecordByUserId(Long userId) {
        TeacherAuthEntryRecordVo authEntryRecordVo = baseMapper.getLastRecordByUserId(userId);
        if (null != authEntryRecordVo) {
            authEntryRecordVo.setIdCardNo(ValueUtil.fuzzyIdCard(authEntryRecordVo.getIdCardNo()));
            authEntryRecordVo.setPhone(ValueUtil.fuzzyMobile(authEntryRecordVo.getPhone()));
        }
        return authEntryRecordVo;
    }

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

}