package com.izouma.wenlvju.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.izouma.wenlvju.domain.TrainingInstitution;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.dto.TrainingInstitutionDTO;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.TrainingInstitutionRepo;
import com.izouma.wenlvju.service.sms.NjwlSmsService;
import com.izouma.wenlvju.utils.JpaUtils;
import com.izouma.wenlvju.utils.excel.UploadDataListener;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class TrainingInstitutionService {

    private TrainingInstitutionRepo trainingInstitutionRepo;
    private NjwlSmsService          njwlSmsService;

    public Page<TrainingInstitution> all(PageQuery pageQuery) {
        return trainingInstitutionRepo.findAll(JpaUtils.toSpecification(pageQuery, TrainingInstitution.class), JpaUtils.toPageRequest(pageQuery));
    }

    public Page<TrainingInstitution> fillIn(PageQuery pageQuery) {
        pageQuery.setSort("firstWrite,desc");
        return trainingInstitutionRepo.findAll(((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> and = JpaUtils.toPredicates(pageQuery, TrainingInstitution.class, root, criteriaQuery, criteriaBuilder);
            and.add(criteriaBuilder.isNotNull(root.get("firstWrite")));
            return criteriaBuilder.and(and.toArray(new Predicate[0]));
        }), JpaUtils.toPageRequest(pageQuery));
    }

    public void batchSend(List<String> phones) throws InterruptedException {

        int count = phones.size() / 980;
        String body = "尊敬的调研对象：\n" +
                "您好，为贯彻落实国家、省、市关于“双减”工作相关文件精神，了解和掌握我市文化艺术类校外培训机构相关情况，市文旅局决定开展全市文化艺术类校外培训机构网上问卷调查，如从事文化艺术类校外培训，请登录：http://wljtest.izouma.com/h5/trainingInstitution，填写调查问卷，如不从事文化艺术类校外培训，请忽略本条信息，谢谢。\n";
        for (int i = 0; i <= count; i++) {
            int start = i * 980;
            int end = start + 980;
            if (end > phones.size()) {
                end = phones.size();
            }
            List<String> result = phones.subList(start, end);
            String sendPhone = String.join(",", result);
//            System.out.println(sendPhone);
            njwlSmsService.sendSms(sendPhone, body);
//            System.out.println("start:" + start + ",end:" + end);
            // 睡眠5分钟
            Thread.sleep(2 * 60 * 1000);
        }

    }

    @Transactional(rollbackOn = Exception.class)
    public void upload(MultipartFile file) throws IOException, InterruptedException {
        UploadDataListener<TrainingInstitutionDTO> listener = new UploadDataListener<>();
        List<TrainingInstitutionDTO> dtos = EasyExcel.read(file.getInputStream(), TrainingInstitutionDTO.class, listener)
                .sheet()
                .doReadSync();
        List<Long> ids = dtos.stream().map(TrainingInstitutionDTO::getId).collect(Collectors.toList());
        List<TrainingInstitution> all = trainingInstitutionRepo.findAllById(ids);
        Map<Long, TrainingInstitution> tiMap = all
                .stream()
                .collect(Collectors.toMap(TrainingInstitution::getId, trainingInstitution -> trainingInstitution));

        dtos.forEach(dto -> {
            TrainingInstitution trainingInstitution = tiMap.get(dto.getId());
            if (ObjectUtil.isNotNull(trainingInstitution)) {
                trainingInstitution.setPhone(dto.getPhone());
                trainingInstitutionRepo.save(trainingInstitution);
            }
        });

        // 发送短信
        this.batchSend(dtos.stream().map(TrainingInstitutionDTO::getPhone).collect(Collectors.toList()));

    }

    public List<String> byName(PageQuery pageQuery) {
        String name = "%" + pageQuery.getSearch() + "%";
        PageRequest pageRequest = JpaUtils.toPageRequest(pageQuery);
        return trainingInstitutionRepo.findAllByNameLike(name, pageRequest.getPageNumber(), pageRequest.getPageSize());
    }

    public TrainingInstitution byUscc(String name, String uscc) {
        TrainingInstitution byUscc = trainingInstitutionRepo.findByUscc(uscc.trim());
        if (ObjectUtil.isNotNull(byUscc)) {
            if (byUscc.getName().equals(name.trim())) {
                return byUscc;
            }
        }
        throw new BusinessException("企业名称或税号不正确");
    }
}
