package com.cirle.scientific.service.impl;

import com.cirle.scientific.constants.CheckWindowIdTypeConsts;
import com.cirle.scientific.constants.SaveYsAndSmConsts;
import com.cirle.scientific.dao.*;
import com.cirle.scientific.dto.CheckWindowDto;
import com.cirle.scientific.po.*;
import com.cirle.scientific.pojo.BizCodeEnum;
import com.cirle.scientific.pojo.Result;
import com.cirle.scientific.service.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
@Slf4j
public class PopuWindowServiceImpl implements PopuWindowService {


    @Autowired
    QkjTqcourseDao qkjTqcourseDao;
    @Autowired
    QkjLiveDao qkjLiveDao;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private QkjQuestionAnswerDao questionAnswerDao;
    @Autowired
    private QkjBrandProductDao qkjBrandProductDao;
    @Autowired
    private QkjMemberPersonalAuthDao qkjMemberPersonalAuthDao;

    @Autowired
    private QkjAuditingDao qkjAuditingDao;


    @Override
    public Result<CheckWindowDto> checkWindow(Long id, Integer idType, String memCard) {

        log.info("checkWindow id:{} idType:{} memCard:{}", id, idType, memCard);

        //1。查询是否需要弹实名认证弹窗
        boolean realName = false;
        //2。判断是否需要弹医师认证弹窗
        boolean physician = false;
        //3。判断是否需要弹调查问卷弹窗
        boolean question = false;

        CheckWindowDto checkWindowDto = CheckWindowDto.builder().realName(realName).physician(physician).question(question).build();

        try {
            if (Objects.isNull(id) || Objects.isNull(idType)) {
                return Result.success(checkWindowDto);
            }

            //是否需要实名认证
            boolean needRealName = false;
            //是否需要医师认证
            boolean needPhysician = false;
            //是否需要调查问卷
            boolean needQuestion = false;

            if (idType == 1) {//直播
                // id是id不是liveId
                Optional<QkjLive> byId = qkjLiveDao.findById(id);

                if (Objects.nonNull(byId)) {
                    QkjLive qkjLive = byId.get();
                    Integer isRealAuth = qkjLive.getSmrzFlag();
                    needRealName = Objects.nonNull(isRealAuth) && isRealAuth == 1;
                    Integer isDocAuth = qkjLive.getYsrzFlag();
                    needPhysician = Objects.nonNull(isDocAuth) && isDocAuth == 1;
                    Integer questionFlag = qkjLive.getQuestionFlag();
                    needQuestion = Objects.nonNull(questionFlag) && questionFlag == 1;
                }
            } else if (idType == 0) {//课程
                QkjTqcourse tqcourse = qkjTqcourseDao.findById(id).orElse(null);

                if (Objects.nonNull(tqcourse)) {
                    String isRealAuth = tqcourse.getIsRealAuth();
                    needRealName = StringUtils.isNoneBlank(isRealAuth) && StringUtils.equals("0", isRealAuth);
                    String isDocAuth = tqcourse.getIsDocAuth();
                    needPhysician = StringUtils.isNoneBlank(isDocAuth) && StringUtils.equals("0", isDocAuth);
                    Integer questionFlag = tqcourse.getQuestionFlag();
                    needQuestion = Objects.nonNull(questionFlag) && questionFlag == 1;
                }
            }
            // 如果没有登录，只需要判断当前专区是否需要弹框
            if (StringUtils.isBlank(memCard)) {
                checkWindowDto = CheckWindowDto.builder().realName(needRealName).physician(needPhysician).question(question).build();
                return Result.success(checkWindowDto);
            }

            QkjMember qkjMember = memberDao.findByMemCard(memCard);
            if (Objects.isNull(qkjMember)) {
                return Result.success(checkWindowDto);
            }

            //是否完成了实名认证 数据库0是没有完成  所以false是已完成
            boolean finishRealName = qkjMember.getSmrzFlag() == 1;

            //是否完成了医师认证
            boolean finishPhysician = qkjMember.getYsrzFlag() == 1;

            //是否完成了医师认证
            boolean finishQuestion = false;

            //是否完成了该直播间或者课程对应的调查问卷
            Integer objType;
            switch (idType) {
                case 0:
                    objType = 3;
                    break;
                case 1:
                    objType = 1;
                    break;
                case 2:
                    objType = 2;
                    break;
                default:
                    objType = null;
            }
            //List<QkjQuestionAnswer> qkjQuestionAnswers = questionAnswerDao.findByCardAndTypeAndId(memCard, objType, id.intValue());
            List<QkjAuditing> auditingList = qkjAuditingDao.getQkjAuditingList(memCard, objType, id.intValue());

            Integer auditingStatus = null;
            String refusalReason = "";
            if (CollectionUtils.isNotEmpty(auditingList)) {
                finishQuestion = true;
                auditingStatus = auditingList.get(0).getAuditingStatus();
                refusalReason = auditingList.get(0).getRefusalReason();
            }
            //需要true 且 未完成true
            realName = needRealName && !finishRealName;
            physician = needPhysician && !finishPhysician;
            question = needQuestion && !finishQuestion;
            checkWindowDto = CheckWindowDto.builder()
                    .realName(realName)
                    .physician(physician)
                    .question(question)
                    .auditingStatus(auditingStatus)
                    .refusalReason(refusalReason)
                    .build();
            log.info("checkWindow Result memcard:{} checkWindowDto:{}", memCard, checkWindowDto);
            return Result.success(checkWindowDto);
        } catch (Exception e) {
            log.error("checkWindow 接口异常 :{}", e);
        }

        return Result.success(checkWindowDto);
    }

    @Override
    public Result checkWindowNew(Long id, Integer idType, String memCard) {
        log.info("checkWindowNew id:{} idType:{} memCard:{}", id, idType, memCard);
        //1。判断是否需要弹调查问卷弹窗
        boolean question = false;
        //需要进行的认证的类型 如果没有则不需要 1:以前的医师认证 2：以前的实名认证 3：欧佳龙医师认证 4：欧佳龙实名 5：不需要
        Integer attestType = 5;
        Integer needAuditing = 0;


        //如果参数为空返回默认
        CheckWindowDto.CheckWindowDtoBuilder checkWindowDtoBuilder = CheckWindowDto.builder().question(question).attestType(attestType).needAuditing(needAuditing);
        if (Objects.isNull(id) || Objects.isNull(idType)) {
            return Result.success(checkWindowDtoBuilder.build());
        }
        //需要什么类型的验证
        Integer needAttestType = 5;
        //是否需要调查问卷
        boolean needQuestion = false;

        switch (idType) {
            case CheckWindowIdTypeConsts.ID_TYPE_LIVE:
                // id是id不是liveId
                QkjLive qkjLive = qkjLiveDao.findById(id).orElse(null);

                if (Objects.nonNull(qkjLive)) {
                    needAttestType = qkjLive.getAttestType();
                    Integer questionFlag = qkjLive.getQuestionFlag();
                    needQuestion = Objects.nonNull(questionFlag) && questionFlag == 1;
                    needAuditing = Objects.nonNull(qkjLive.getNeedAuditing()) ? qkjLive.getNeedAuditing() : 0;
                }
                break;
            case CheckWindowIdTypeConsts.ID_TYPE_BRAND:
                QkjBrandProduct brandProduct = qkjBrandProductDao.findById(id).orElse(null);
                if (Objects.nonNull(brandProduct)) {
                    needAttestType = brandProduct.getAttestType();
                }
                break;
            case CheckWindowIdTypeConsts.ID_TYPE_COURSE:
                QkjTqcourse tqcourse = qkjTqcourseDao.findById(id).orElse(null);

                if (Objects.nonNull(tqcourse)) {
                    needAttestType = tqcourse.getAttestType();
                    Integer questionFlag = tqcourse.getQuestionFlag();
                    needQuestion = Objects.nonNull(questionFlag) && questionFlag == 1;
                }
                break;
            default:
                break;
        }
//        if(Objects.isNull(needAttestType)){
//             needAttestType = 5;
//        }

        QkjMember qkjMember = memberDao.findByMemCard(memCard);
        if (Objects.isNull(qkjMember)) {
            checkWindowDtoBuilder.needAuditing(needAuditing);
            return Result.success(checkWindowDtoBuilder.build());
        }
        //是否完成了实名认证 数据库0是没有完成  所以1是已完成
        boolean finishRealName = qkjMember.getSmrzFlag() == 1;

        //是否完成了医师认证
        boolean finishPhysician = qkjMember.getYsrzFlag() == 1;

        switch (needAttestType) {
            case SaveYsAndSmConsts.ATTEST_TYPE_A://想要进行的验证类型
                if (!finishPhysician) {//是否需要弹窗 没完成弹窗
                    attestType = SaveYsAndSmConsts.ATTEST_TYPE_A;
                }
                break;
            case SaveYsAndSmConsts.ATTEST_TYPE_B:
                if (!finishRealName) {
                    attestType = SaveYsAndSmConsts.ATTEST_TYPE_B;
                }
                break;
            case SaveYsAndSmConsts.ATTEST_TYPE_C:
                QkjMemberPersonalAuth personalAuth = qkjMemberPersonalAuthDao.findByMemCard(memCard);

                if (!(finishPhysician && Objects.nonNull(personalAuth)) && Objects.equals(0, qkjMember.getIsWhitelist())) {
                    attestType = SaveYsAndSmConsts.ATTEST_TYPE_C;
                }
                break;
            case SaveYsAndSmConsts.ATTEST_TYPE_D:
                if (!(finishRealName && finishPhysician)) {
                    attestType = SaveYsAndSmConsts.ATTEST_TYPE_D;
                }
                break;
            default:
                break;
        }


        //是否完成了调查问卷
        boolean finishQuestion = false;

        //是否完成了该直播间或者课程对应的调查问卷
        Integer objType;
        switch (idType) {
            case CheckWindowIdTypeConsts.ID_TYPE_LIVE:
                objType = 1;
                break;
            case CheckWindowIdTypeConsts.ID_TYPE_MEETING:
                objType = 2;
                break;
            case CheckWindowIdTypeConsts.ID_TYPE_COURSE:
                objType = 3;
                break;
            default:
                objType = null;
        }
//        List<QkjQuestionAnswer> qkjQuestionAnswers = questionAnswerDao.findByCardAndTypeAndId(memCard, objType, id.intValue());
//
//        if (CollectionUtils.isNotEmpty(qkjQuestionAnswers)) {
//            finishQuestion = true;
//        }
//        question = needQuestion && !finishQuestion;
//        checkWindowDto = CheckWindowDto.builder().question(question).attestType(attestType).build();

        List<QkjAuditing> auditingList = qkjAuditingDao.getQkjAuditingList(memCard, objType, id.intValue());
        Integer auditingStatus = null;
        String refusalReason = "";
        if (CollectionUtils.isNotEmpty(auditingList)) {
            finishQuestion = true;
            auditingStatus = auditingList.get(0).getAuditingStatus();
            refusalReason = auditingList.get(0).getRefusalReason();
        }
        //需要true 且 未完成true
        question = needQuestion && !finishQuestion;
        CheckWindowDto checkWindowDto = CheckWindowDto.builder()
                .attestType(attestType)
                .question(question)
                .auditingStatus(auditingStatus)
                .refusalReason(refusalReason)
                .needAuditing(needAuditing)
                .build();
        log.info("checkWindowNew Result memcard:{} checkWindowDto:{}", memCard, checkWindowDto);


        return Result.success(checkWindowDto);
    }

    @Override
    public Result checkWindowQuestion(Long id, Integer idType, String memCard) {
        log.info("checkWindowQuestion id:{} idType:{} memCard:{}", id, idType, memCard);
        //1。判断是否需要弹调查问卷弹窗
        boolean question = false;

        //如果参数为空返回默认
        CheckWindowDto checkWindowDto = CheckWindowDto.builder().question(question).build();
        if (Objects.isNull(id) || Objects.isNull(idType)) {
            return Result.success(checkWindowDto);
        }
        //是否需要调查问卷
        boolean needQuestion = false;
        switch (idType) {
            case CheckWindowIdTypeConsts.ID_TYPE_LIVE:
                // id是id不是liveId
                QkjLive qkjLive = qkjLiveDao.findById(id).orElse(null);

                if (Objects.nonNull(qkjLive)) {
                    Integer questionFlag = qkjLive.getQuestionFlag();
                    needQuestion = Objects.nonNull(questionFlag) && questionFlag == 1;
                }
                break;
            case CheckWindowIdTypeConsts.ID_TYPE_COURSE:
                QkjTqcourse tqcourse = qkjTqcourseDao.findById(id).orElse(null);

                if (Objects.nonNull(tqcourse)) {
                    Integer questionFlag = tqcourse.getQuestionFlag();
                    needQuestion = Objects.nonNull(questionFlag) && questionFlag == 1;
                }
                break;
            default:
                break;
        }
        QkjMember qkjMember = memberDao.findByMemCard(memCard);
        if (Objects.isNull(qkjMember)) {
            return Result.success(checkWindowDto);
        }
        //是否完成了调查问卷
        boolean finishQuestion = false;

        //是否完成了该直播间或者课程对应的调查问卷
        Integer objType;
        switch (idType) {
            case CheckWindowIdTypeConsts.ID_TYPE_LIVE:
                objType = 1;
                break;
            case CheckWindowIdTypeConsts.ID_TYPE_MEETING:
                objType = 2;
                break;
            case CheckWindowIdTypeConsts.ID_TYPE_COURSE:
                objType = 3;
                break;
            default:
                objType = null;
        }
        List<QkjQuestionAnswer> qkjQuestionAnswers = questionAnswerDao.findByCardAndTypeAndId(memCard, objType, id.intValue());

        if (CollectionUtils.isNotEmpty(qkjQuestionAnswers)) {
            finishQuestion = true;
        }
        question = needQuestion && !finishQuestion;
        checkWindowDto = CheckWindowDto.builder().question(question).build();
        log.info("checkWindowQuestion Result memcard:{} checkWindowDto:{}", memCard, checkWindowDto);
        return Result.success(checkWindowDto);
    }


}
