package com.rf.psychological.miniapp.collect.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.collect.model.CollectEntity;
import com.rf.psychological.miniapp.collect.repository.CollectRepository;
import com.rf.psychological.miniapp.collect.service.CollectService;
import com.rf.psychological.scale.dao.model.SubjectEntity;
import com.rf.psychological.scale.service.CognitiveTaskService;
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/19
 */
@Service
public class CollectServiceImpl implements CollectService {

    @Autowired
    private CollectRepository repository;

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private CognitiveTaskService cognitiveTaskService;

    @Autowired
    private PromotionInfoService promotionInfoService;


    /**
     * 保存收藏
      * @param entity
     * @return
     */
    @Override
    public CollectEntity save(CollectEntity entity) {
        entity.setCreateTime(DateUtil.now());
        entity.setStatus(Constant.DEFAULT_VALUE_ONE);
        return repository.save(entity);
    }

    /**
     * 根据id获取
     * @param id
     * @return
     */
    @Override
    public CollectEntity findById(String id) {
        return repository.findById(id).orElse(null);
    }


    /**
     * 取消收藏
     * @param entity
     * @return
     */
    @Override
    public CollectEntity cancel(CollectEntity entity) {
        entity.setUpdateTime(DateUtil.now());
        entity.setStatus(Constant.DEFAULT_VALUE_ZERO);
        return repository.save(entity);
    }

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

    @Override
    public Page<CollectEntity> queryByUserId(String userId, String type, 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));
            }
            if (StringUtils.isNotEmpty(type)){
                list.add(criteriaBuilder.equal(root.get("type"),type));
            }
            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("createTime")));
            return query.getRestriction();
        });
        Page<CollectEntity> entityPage = repository.findAll(specification, PageRequestUtil.of(page,pageSize));
        //封装其他暂时信息
        if (CollectionUtils.isNotEmpty(entityPage.getContent())){
            entityPage.getContent().forEach(entity -> {
                PromotionInfo info = promotionInfoService.findInfoBySubjectId(entity.getBusinessId());
                String busType = entity.getType();
                if(Constant.DEFAULT_VALUE_ZERO.equals(busType)){
                    SubjectEntity subjectEntity = subjectService.findById(entity.getBusinessId()).orElse(null);
                    entity.setName(subjectEntity.getName());
                    entity.setDescription(subjectEntity.getDescription());
                    entity.setFlag(subjectEntity.getFlag());
                    entity.setTestNum(subjectEntity.getTestNum());
                    entity.setPrice(info!=null?info.getPrice():0);
                }else {
                    CognitiveTaskEntity cognitiveTaskEntity = cognitiveTaskService.getAllById(entity.getBusinessId()).orElse(null);
                    entity.setName(cognitiveTaskEntity.getName());
                    entity.setDescription(cognitiveTaskEntity.getDescription());
                    entity.setFlag(cognitiveTaskEntity.getTaskCode());
                    entity.setTestNum(cognitiveTaskEntity.getTestNum());
                    entity.setPrice(info!=null?info.getPrice():0);
                }
            });
        }
        return entityPage;
    }
}
