package com.rf.psychological.miniapp.browse.service.impl;

import cn.hutool.core.date.DateUtil;
import com.rf.psychological.dao.model.CognitiveTaskEntity;
import com.rf.psychological.miniapp.browse.model.BrowseEntity;
import com.rf.psychological.miniapp.browse.repository.BrowseRepository;
import com.rf.psychological.miniapp.browse.service.BrowseService;
import com.rf.psychological.scale.dao.model.SubjectEntity;
import com.rf.psychological.scale.service.CognitiveTaskService;
import com.rf.psychological.scale.service.ScaleService;
import com.rf.psychological.scale.service.SubjectService;
import com.rf.psychological.utils.Constant;
import com.rf.psychological.utils.PageRequestUtil;
import com.rf.psychological.wxpay.model.PromotionInfo;
import com.rf.psychological.wxpay.service.PromotionInfoService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:浏览接口
 * @Author: mimang
 * @Date: 2023/5/16
 */
@Service
public class BrowseServiceImpl implements BrowseService {

    @Autowired
    private BrowseRepository repository;

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private CognitiveTaskService cognitiveTaskService;

    @Autowired
    private ScaleService scaleService;

    @Autowired
    private PromotionInfoService promotionInfoService;

    /**
     * 浏览信息保存
     * @param entity
     * @return
     */
    @Override
    public BrowseEntity save(BrowseEntity entity) {
        entity.setCreateTime(DateUtil.now());
        entity.setUpdateTime(DateUtil.now());
        entity.setStatus(Constant.DEFAULT_VALUE_ONE);
        return repository.save(entity);
    }

    @Override
    public Page<BrowseEntity> queryByUserId(String userId, int page, int pageSize) {
        Specification specification = ((root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (StringUtils.isNotEmpty(userId)){
                list.add( criteriaBuilder.equal(root.get("userId"),userId));
            }
            list.add( criteriaBuilder.equal(root.get("status"),Constant.DEFAULT_VALUE_ONE));
            query.where(criteriaBuilder.and(list.toArray(new Predicate[0])));
            query.orderBy(criteriaBuilder.desc(root.get("updateTime")));
            return query.getRestriction();
        });
        Page<BrowseEntity> entityPage = repository.findAll(specification,PageRequestUtil.of(page,pageSize));
        //封装其他暂时信息
        if (CollectionUtils.isNotEmpty(entityPage.getContent())){
            entityPage.getContent().forEach(entity -> {
                PromotionInfo info = promotionInfoService.findInfoBySubjectId(entity.getBusinessId());
                String type = entity.getType();
                if(Constant.DEFAULT_VALUE_ZERO.equals(type)){
                    SubjectEntity subjectEntity = subjectService.findById(entity.getBusinessId()).orElse(null);
                    entity.setName(subjectEntity.getName());
                    entity.setDescription(subjectEntity.getDescription());
                    entity.setTestNum(String.valueOf(subjectEntity.getTestNum()));
                    entity.setQuestionNum(String.valueOf(scaleService.getScaleByFlag(subjectEntity.getFlag()).size()));
                    entity.setPrice(info!=null?info.getPrice():0);
                    entity.setReportVersion(subjectEntity.getReportVersion().toString());
                    entity.setImageUrl(subjectEntity.getImageUrl());
                    entity.setFlag(subjectEntity.getFlag());
                }else {
                    CognitiveTaskEntity cognitiveTaskEntity = cognitiveTaskService.getAllById(entity.getBusinessId()).orElse(null);
                    entity.setName(cognitiveTaskEntity.getName());
                    entity.setDescription(cognitiveTaskEntity.getDescription());
                    entity.setTestNum(String.valueOf(cognitiveTaskEntity.getTestNum()));
                    entity.setPrice(info!=null?info.getPrice():0);
                    entity.setReportVersion(cognitiveTaskEntity.getReportVersion().toString());
                    entity.setImageUrl(cognitiveTaskEntity.getIllustratingPicture());
                    entity.setPageUrl(cognitiveTaskEntity.getPageUrl());
                    entity.setFlag(cognitiveTaskEntity.getTaskCode());
                }
            });
        }
        return entityPage;
    }

    @Override
    public void deleteByUserId(String id) {
        //获取到该用户下的搜索记录
        List<BrowseEntity> list = repository.findAllByUserIdAndStatus(id,Constant.DEFAULT_VALUE_ONE);
        if (CollectionUtils.isNotEmpty(list)){
            list.forEach(entity -> {
                entity.setUpdateTime(DateUtil.now());
                entity.setStatus(Constant.DEFAULT_VALUE_ZERO);
            });
        }
        repository.saveAll(list);
    }

    @Override
    public BrowseEntity findByUserIdAndBusinessId(String userId, String businessId) {
        return repository.findByUserIdAndBusinessIdAndStatus(userId,businessId,Constant.DEFAULT_VALUE_ONE);
    }

    @Override
    public BrowseEntity update(BrowseEntity entity) {
        entity.setUpdateTime(DateUtil.now());
        return repository.save(entity);
    }
}
