package com.izouma.zhirongip.service.demand;

import cn.hutool.core.collection.CollUtil;
import com.izouma.zhirongip.domain.Information;
import com.izouma.zhirongip.domain.Setting;
import com.izouma.zhirongip.domain.demand.LogoDemand;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.enums.ApplyStatus;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.InformationRepo;
import com.izouma.zhirongip.repo.SettingRepo;
import com.izouma.zhirongip.repo.demand.LogoDemandRepo;
import com.izouma.zhirongip.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class LogoDemandService {

    private final LogoDemandRepo logoDemandRepo;
    private final SettingRepo     settingRepo;
    private final InformationRepo informationRepo;

    public Page<LogoDemand> all(PageQuery pageQuery) {
        Map<Long, String> settingMap = settingRepo.findAllByFlagIn(CollUtil.list(false, 2 ,24)).stream()
                .collect(Collectors.toMap(Setting::getId, Setting::getName));
        return logoDemandRepo.findAll(JpaUtils.toSpecification(pageQuery, LogoDemand.class), JpaUtils.toPageRequest(pageQuery))
                .map(cd -> {
                    if(cd.getModeId()!=null){
                        cd.setMode(settingMap.get(cd.getModeId()));
                    }
                    cd.setCategoryName(settingMap.get(cd.getCategory()));
                    return cd;
                });
    }

    public void audit(Long id, boolean pass, String remark) {
        LogoDemand record = logoDemandRepo.findById(id).orElseThrow(new BusinessException("无记录"));

        Information information = Information.builder()
                .receiveUserId(record.getUserId())
                .isRead(false)
                .build();

        if (pass) {
            record.setStatus(ApplyStatus.PASS);
            logoDemandRepo.save(record);

            information.setContent("您发布的商标需求侧已通过审核！");
            informationRepo.save(information);
            return;
        }
        record.setStatus(ApplyStatus.DENY);
        logoDemandRepo.save(record);

        information.setContent("您发布的的商标需求侧未通过审核，原因为：" + remark);
        informationRepo.save(information);
    }
}
