package com.izouma.uwip.service;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.uwip.domain.Handle;
import com.izouma.uwip.domain.LogoPatent;
import com.izouma.uwip.domain.Partner;
import com.izouma.uwip.dto.PageQuery;
import com.izouma.uwip.enums.*;
import com.izouma.uwip.exception.BusinessException;
import com.izouma.uwip.repo.LogoPatentRepo;
import com.izouma.uwip.repo.PartnerRepo;
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;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Service
@AllArgsConstructor
public class LogoPatentService {

    private LogoPatentRepo    logoPatentRepo;
    private PartnerRepo       partnerRepo;
    private AttachmentService attachmentService;

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

    public String getUwNo(LogoPatent patent) {
//        客户编码（由客户经理填写）+年份+案件类型+连接符+案件阶段[+国家]+序列号
        Partner partner = partnerRepo.findById(patent.getClientPartnerId()).orElseThrow(new BusinessException("客户不存在"));
        int y = LocalDate.now().getYear() - 2000;
        return partner.getCode() + y + CaseType.LOGO.getValue() + "——" + CaseStage.DOMESTIC.getValue() + String.format("%03d", patent
                .getSort());
    }

    public Handle saveHandle(LogoWorkflow workflow, Long userId) {
        return Handle.builder()
                .logoWorkflow(workflow)
                .userId(userId)
                .checkAt(LocalDateTime.now())
                .build();
    }

    public LogoPatent save(LogoPatent record, Long id) {
        if (record.getId() != null) {
            LogoWorkflow workflow = record.getLogoWorkflow();
            if (ObjectUtil.isNull(workflow)) {
                throw new BusinessException("流程为空");
            }
            LogoPatent orig = logoPatentRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            // 保存附件
            if (CollectionUtils.isNotEmpty(record.getAttachments())) {
                attachmentService.batchSave(record.getAttachments(), id, record.getId());
            }
            ObjUtils.merge(orig, record);
//            orig.getHandle().add(this.saveHandle(workflow, id));
            orig.setApplyStatus(this.getApplyStatus(workflow));
            return logoPatentRepo.save(orig);
        }
        if (record.getSort() == 0) {
            record.setSort(logoPatentRepo.findMax());
        }
        record.setUwNo(this.getUwNo(record));
        record.setLogoWorkflow(LogoWorkflow.IS_CONTRACT);
        record.setApplyStatus(ApplyStatus.APPLY_STAGE);
        record = logoPatentRepo.save(record);
        // 保存附件
        if (CollectionUtils.isNotEmpty(record.getAttachments())) {
            attachmentService.batchSave(record.getAttachments(), id, record.getId());
        }
        return record;
    }

    public ApplyStatus getApplyStatus(LogoWorkflow logoWorkflow) {
        switch (logoWorkflow) {
            case IS_CONTRACT:
            case TO_BE_MAINTAINED:
            case PENDING:
                return ApplyStatus.APPLY_STAGE;
            case PENDING_REVIEW:
            case DISMISS:
            case ANNOUNCEMENTS:
                return ApplyStatus.REVIEW_STAGE;
            case HANDLE:
                return ApplyStatus.GRANT_STAGE;
            default:
                return ApplyStatus.COMPLETED;
        }
    }
}
