package com.yida.data.school.health.service.impl;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.entity.constant.AppConstant;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.health.EduHealthStudentPhysicalExaminationGroup;
import com.yida.data.common.core.entity.health.EduProject;
import com.yida.data.common.core.entity.health.EduStudentPhysicalExaminationGradeResults;
import com.yida.data.common.core.entity.health.EduStudentProjectTestResult;
import com.yida.data.common.core.entity.notice.EduNoticeBuyReceiver;
import com.yida.data.common.core.entity.notice.qywx.NewsSchoolNotice;
import com.yida.data.common.core.entity.notice.qywx.TextSchoolNotice;
import com.yida.data.common.core.entity.notice.qywx.inside.Article;
import com.yida.data.common.core.entity.notice.qywx.inside.News;
import com.yida.data.common.core.entity.notice.qywx.inside.Text;
import com.yida.data.common.core.entity.system.EduApp;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.utils.WxUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.school.health.mapper.EduHealthStudentPhysicalExaminationGroupMapper;
import com.yida.data.school.health.service.EduHealthStudentPhysicalExaminationGroupService;
import com.yida.data.school.health.service.EduStudentPhysicalExaminationGradeResultsService;
import com.yida.data.school.health.service.EduStudentProjectTestResultService;
import com.yida.data.user.dto.ListStudentDTO;
import com.yida.data.user.feign.RemoteStudentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.QueryRequest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.yida.data.common.core.entity.constant.imageConstant.HEALTH_IMAGE_URL;
import static com.yida.data.common.core.entity.constant.imageConstant.SCORE_IMAGE_URL;

/**
 * 体质健康对应组别表 Service实现
 *
 * @author zhanghaijun
 * @date 2021-11-10 17:16:54
 */
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class EduHealthStudentPhysicalExaminationGroupServiceImpl extends ServiceImpl
        <EduHealthStudentPhysicalExaminationGroupMapper, EduHealthStudentPhysicalExaminationGroup> implements EduHealthStudentPhysicalExaminationGroupService {

    private final EduHealthStudentPhysicalExaminationGroupMapper eduHealthStudentPhysicalExaminationGroupMapper;
    private final EduStudentPhysicalExaminationGradeResultsService resultsService;
    private final EduStudentProjectTestResultService testResultService;

    private final RemoteStudentService remoteStudentService;
    private final WxUtil wxUtil;
    private final CommonService commonService;

    @Value("${febs.healthUrl}")
    private String healthUrl;

    @Override
    public void saveOrUpdateHealthGroup(EduHealthStudentPhysicalExaminationGroup examinationGroup) {
        saveOrUpdate(examinationGroup);
    }

    @Override
    public void removeHealthGroup(Long groupId) {
        List<EduStudentPhysicalExaminationGradeResults> gradeResults = resultsService.list(Wrappers.lambdaQuery(new EduStudentPhysicalExaminationGradeResults())
                .eq(EduStudentPhysicalExaminationGradeResults::getGroupId, groupId));
        List<Long> gradeResultsId = new ArrayList<>();
        for (EduStudentPhysicalExaminationGradeResults gradeResult : gradeResults) {
            gradeResultsId.add(gradeResult.getId());
        }
        if(CollectionUtil.isNotEmpty(gradeResultsId)){
            testResultService.remove(Wrappers.lambdaQuery(new EduStudentProjectTestResult())
                    .in(EduStudentProjectTestResult::getGradeResultId,gradeResultsId));
        }

        resultsService.remove(Wrappers.lambdaQuery(new EduStudentPhysicalExaminationGradeResults())
                .eq(EduStudentPhysicalExaminationGradeResults::getGroupId,groupId));
        removeById(groupId);
    }

    @Override
    public void sendHealthNotice(Long groupId,Long schoolId) {
        List<Long> studentId = baseMapper.findStudentId(groupId);
        EduHealthStudentPhysicalExaminationGroup group = getById(groupId);
        EduApp app = commonService.getAppByCodeAndSchool(AppConstant.INDEX_PARENT, null,
                schoolId);
        String accessToken = wxUtil.getAccessToken(app.getWxCorpId(), app.getWxSecret());

        for (Long stuId : studentId) {

            List<Long> list = new ArrayList<>();
            list.add(stuId);
            List<String> parentWxId = remoteStudentService.findParentWxId(list).getData();
            EduStudent data = remoteStudentService.getStudentNoPermission(stuId).getData();
            String title = data.getStuName() + "有1份新的体质健康报告，请查阅！";
            String url = healthUrl+stuId+"&appId="+app.getWxCorpId()+"&type=1";
            Article article = new Article();
            article.setTitle(title);
            article.setUrl(url);
            article.setPicurl(HEALTH_IMAGE_URL);
            article.setDescription(group.getGroupName());
            News news = new News(Arrays.asList(article));
            NewsSchoolNotice newsSchoolNotice = new NewsSchoolNotice();
            newsSchoolNotice.setNews(news);
            newsSchoolNotice.setAgentid(app.getWxAgentId());
            newsSchoolNotice.setTo_parent_userid(parentWxId);
            wxUtil.pushSchoolNotice(accessToken, newsSchoolNotice);
        }
        update(Wrappers.lambdaUpdate(new EduHealthStudentPhysicalExaminationGroup())
                .eq(EduHealthStudentPhysicalExaminationGroup::getId,groupId)
                .set(EduHealthStudentPhysicalExaminationGroup::getStatus,1));
    }

    @Override
    public Page<EduHealthStudentPhysicalExaminationGroup> findHealthGroup(Page<EduHealthStudentPhysicalExaminationGroup> page, Long schoolId, String groupName, Integer status) {

        return baseMapper.findHealthGroup(page,schoolId,groupName,status);
    }
}
