package com.izouma.uwip.service;

import cn.hutool.core.bean.BeanUtil;
import com.izouma.uwip.domain.DomesticPatent;
import com.izouma.uwip.domain.Patent;
import com.izouma.uwip.dto.DomesticPatentDTO;
import com.izouma.uwip.dto.PageQuery;
import com.izouma.uwip.enums.CaseStage;
import com.izouma.uwip.enums.CaseType;
import com.izouma.uwip.enums.PatentType;
import com.izouma.uwip.exception.BusinessException;
import com.izouma.uwip.repo.DomesticPatentRepo;
import com.izouma.uwip.repo.PatentRepo;
import com.izouma.uwip.utils.JpaUtils;
import com.izouma.uwip.utils.ObjUtils;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class DomesticPatentService {

    private final DomesticPatentRepo domesticPatentRepo;
    private final AttachmentService  attachmentService;
    private final PatentRepo         patentRepo;
    private final PartnerService     partnerService;

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

    public DomesticPatent saveDTO(DomesticPatentDTO record, Long userId) {
        if (record.getDid() != null) {
            DomesticPatent orig = domesticPatentRepo.findById(record.getDid())
                    .orElseThrow(new BusinessException("无记录"));
            DomesticPatent dPatent = new DomesticPatent(record);
            ObjUtils.merge(orig, dPatent);
            orig = domesticPatentRepo.save(orig);

            Patent orig1 = patentRepo.findById(record.getPatentId()).orElseThrow(new BusinessException("无记录"));
            Patent patent = new Patent();
            BeanUtil.copyProperties(record, patent);
            ObjUtils.merge(orig1, patent);
            patentRepo.save(orig1);

            // 保存附件
            if (CollectionUtils.isNotEmpty(record.getAttachments())) {
                attachmentService.batchSave(record.getAttachments(), userId, record.getDid());
            }

            return orig;
        }

        Patent patent = new Patent();
        BeanUtil.copyProperties(record, patent);
        patent.setSort(patentRepo.findMax());

        //寰球案号
        PatentType type = patent.getType();
        patent.setUwNo(partnerService.getUwNo(patent.getClientPartnerId(), CaseType.valueOf(type.name()), CaseStage.DOMESTIC, patent
                .getSort()));
        patent = patentRepo.save(patent);

        DomesticPatent dPatent = new DomesticPatent(record);
        dPatent.setPatentId(patent.getId());
        dPatent = domesticPatentRepo.save(dPatent);

        // 保存附件
        if (CollectionUtils.isNotEmpty(record.getAttachments())) {
            attachmentService.batchSave(record.getAttachments(), userId, record.getDid());
        }
        return dPatent;
    }
}
