package com.izouma.zhirongip.service.demand;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.izouma.zhirongip.domain.Information;
import com.izouma.zhirongip.domain.Setting;
import com.izouma.zhirongip.domain.demand.PatentDemand;
import com.izouma.zhirongip.domain.supply.Patent;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.dto.PatentDemandExcelDto;
import com.izouma.zhirongip.dto.PatentExcelDto;
import com.izouma.zhirongip.dto.excel.PatentExcel;
import com.izouma.zhirongip.enums.ApplyStatus;
import com.izouma.zhirongip.enums.OwnerType;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.InformationRepo;
import com.izouma.zhirongip.repo.SettingRepo;
import com.izouma.zhirongip.repo.demand.PatentDemandRepo;
import com.izouma.zhirongip.service.SettingService;
import com.izouma.zhirongip.utils.JpaUtils;
import com.izouma.zhirongip.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class PatentDemandService {

    private final PatentDemandRepo patentDemandRepo;
    private final SettingRepo      settingRepo;
    private final InformationRepo  informationRepo;
    private final SettingService   settingService;

    public Page<PatentDemand> all(PageQuery pageQuery) {
        Map<Long, String> settingMap = settingRepo.findAllByFlagIn(CollUtil.list(false, 1, 13, 24, 25, 26)).stream()
                                                  .collect(Collectors.toMap(Setting::getId, Setting::getName));
        return patentDemandRepo
                .findAll(JpaUtils.toSpecification(pageQuery, PatentDemand.class), JpaUtils.toPageRequest(pageQuery))
                .map(cd -> {
                    if (cd.getPatentStatusId() != null) {
                        cd.setPatentStatus(settingMap.get(cd.getPatentStatusId()));
                    }
                    if (cd.getPatentTypeId() != null) {
                        cd.setPatentType(settingMap.get(cd.getPatentTypeId()));
                    }
                    if (cd.getModeId() != null) {
                        cd.setMode(settingMap.get(cd.getModeId()));
                    }
                    cd.setIndustryName(settingMap.get(cd.getIndustryClass()));
                    return cd;
                });
    }

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

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

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

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

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

    @Transactional(rollbackOn = Exception.class)
    public void upload1(InputStream is) throws IOException {
        List<PatentDemandExcelDto> dtos = EasyExcel.read(is).head(PatentDemandExcelDto.class).sheet().doReadSync();
        List<PatentDemand> patents = dtos.stream().map(PatentDemandExcelDto::toPatentDemand)
                                         .collect(Collectors.toList());
        List<Setting> settings = settingService.getTree(settingRepo.findAllByFlag(1));
        patents.forEach(d -> {
            d.setIndustryClass(settings.stream().filter(s -> s.getName().equals(d.getIndustryName())).findFirst()
                                       .map(Setting::getId).orElse(null));
        });
        patentDemandRepo.saveAll(patents);
    }

}
