package com.jeesharp.business.modules.finance.invoice.application;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.finance.invoice.convert.MemberInvoiceApplyConvert;
import com.jeesharp.business.modules.finance.invoice.dto.MemberInvoiceApplyCreateDTO;
import com.jeesharp.business.modules.finance.invoice.dto.MemberInvoiceApplySaveDTO;
import com.jeesharp.business.modules.finance.invoice.dto.MemberInvoiceAuditDTO;
import com.jeesharp.business.modules.finance.invoice.entity.MemberInvoiceApply;
import com.jeesharp.business.modules.finance.invoice.service.MemberInvoiceApplyService;
import com.jeesharp.business.modules.finance.invoice.vo.MemberInvoiceApplyInfoVO;
import com.jeesharp.business.modules.finance.invoice.vo.MemberInvoiceApplyListVO;
import com.jeesharp.business.modules.finance.invoice.vo.MemberInvoiceApplyQueryVO;
import com.jeesharp.business.modules.finance.invoice.enums.MemberInvoiceApplyBizTypeEnum;
import com.jeesharp.business.modules.finance.invoice.vo.MemberInvoiceApplyResultVO;
import com.jeesharp.business.modules.mall.api.MallOrderReadApi;
import com.jeesharp.business.modules.mall.api.dto.MallOrderInvoiceSummaryDTO;
import com.jeesharp.business.modules.member.service.MemberService;
import com.jeesharp.framework.exception.BizErrorException;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.pojo.query.PageRespVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * 发票申请应用服务：编排会员发票申请、审核及与商城订单校验。
 *
 * @author jeesharp
 * @since 2026-05-08
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class MemberInvoiceApplyApplicationService {

    private final MemberInvoiceApplyService memberInvoiceApplyService;
    private final MallOrderReadApi mallOrderReadApi;
    private final MemberService memberService;

    public MemberInvoiceApplyInfoVO get(String id) {
        MemberInvoiceApplyInfoVO vo = MemberInvoiceApplyConvert.INSTANCE.toInfoVO(memberInvoiceApplyService.get(id));
        memberService.enrichMemberDisplay(vo);
        return vo;
    }

    public PageRespVO<MemberInvoiceApplyListVO> findPage(Page<MemberInvoiceApply> page, MemberInvoiceApplyQueryVO query) {
        MemberInvoiceApplyQueryVO prepared = prepareQuery(query);
        if (prepared == null) {
            return emptyPage(page);
        }
        Page<MemberInvoiceApply> result = memberInvoiceApplyService.findPage(page, prepared);
        PageRespVO<MemberInvoiceApplyListVO> pageVo = MemberInvoiceApplyConvert.INSTANCE.toPageRespVO(result);
        memberService.enrichMemberDisplay(pageVo.getRecords());
        return pageVo;
    }

    @Transactional(readOnly = false)
    public void save(MemberInvoiceApplySaveDTO dto) {
        MemberInvoiceApply entity = MemberInvoiceApplyConvert.INSTANCE.toEntity(dto);
        if (StrUtil.isBlank(dto.getId())) {
            memberInvoiceApplyService.createApply(entity);
            return;
        }
        memberInvoiceApplyService.updateApply(entity);
    }

    @Transactional(readOnly = false)
    public void delete(String ids) {
        memberInvoiceApplyService.batchDelete(StrUtil.splitTrim(ids, ','));
    }

    @Transactional(readOnly = false)
    public MemberInvoiceApplyResultVO create(String memberId, MemberInvoiceApplyCreateDTO dto) {
        String tenantId = null;
        String tenantCode = null;
        if (MemberInvoiceApplyBizTypeEnum.MALL.getValue().equals(dto.getBizType())) {
            MallOrderInvoiceSummaryDTO order = mallOrderReadApi.getInvoiceSummary(dto.getOrderId());
            if (order == null) {
                throw new BizErrorException("订单不存在");
            }
            if (!dto.getOrderNo().equals(order.getOrderNo())) {
                throw new BizErrorException("订单信息不匹配");
            }
            tenantId = order.getTenantId();
            tenantCode = order.getTenantCode();
        }
        MemberInvoiceApplyQueryVO queryVO = new MemberInvoiceApplyQueryVO();
        queryVO.setMemberId(memberId);
        queryVO.setOrderId(dto.getOrderId());
        if (!memberInvoiceApplyService.findList(queryVO).isEmpty()) {
            throw new BizErrorException("该订单已申请发票");
        }
        return memberInvoiceApplyService.createInvoiceApply(memberId, dto, tenantId, tenantCode);
    }

    @Transactional(readOnly = false)
    public void audit(MemberInvoiceAuditDTO dto, String operatorId) {
        MemberInvoiceApply entity = memberInvoiceApplyService.get(dto.getId());
        if (entity == null) {
            throw new BizErrorException("申请单不存在");
        }
        entity.setAuditRemark(dto.getAuditRemark());
        entity.setAuditById(operatorId);
        entity.setAuditTime(LocalDateTime.now());
        entity.setInvoiceFileKey(dto.getInvoiceFileKey());
        entity.setInvoiceFileName(dto.getInvoiceFileName());
        entity.setInvoiceFileUrl(dto.getInvoiceFileUrl());
        entity.setStatus("approve".equals(dto.getAction()) ? "approved" : "rejected");
        memberInvoiceApplyService.updateApply(entity);
    }

    public MemberInvoiceApplyResultVO getResult(String id) {
        return memberInvoiceApplyService.getApplyResult(id);
    }

    public MemberInvoiceApplyResultVO getLatestByOrder(String memberId, String orderId) {
        MemberInvoiceApplyQueryVO queryVO = new MemberInvoiceApplyQueryVO();
        queryVO.setMemberId(memberId);
        return memberInvoiceApplyService.findList(queryVO).stream()
                .filter(item -> orderId.equals(item.getOrderId()))
                .findFirst()
                .map(item -> memberInvoiceApplyService.getApplyResult(item.getId()))
                .orElse(null);
    }

    public List<MemberInvoiceApplyResultVO> listByMember(String memberId, String status) {
        MemberInvoiceApplyQueryVO queryVO = new MemberInvoiceApplyQueryVO();
        queryVO.setMemberId(memberId);
        queryVO.setStatus(StrUtil.blankToDefault(status, null));
        return memberInvoiceApplyService.findList(queryVO).stream()
                .map(item -> memberInvoiceApplyService.getApplyResult(item.getId()))
                .toList();
    }

    /**
     * 会员关键词 → memberIdIn 筛选条件（编排，不含会员数据组装）。
     */
    private MemberInvoiceApplyQueryVO prepareQuery(MemberInvoiceApplyQueryVO query) {
        MemberInvoiceApplyQueryVO q = query != null ? query : new MemberInvoiceApplyQueryVO();
        if (StrUtil.isBlank(q.getMemberKeyword())) {
            return q;
        }
        List<String> memberIds = memberService.findIdsByKeyword(q.getMemberKeyword().trim());
        q.setMemberKeyword(null);
        if (CollUtil.isEmpty(memberIds)) {
            return null;
        }
        q.setMemberIdIn(memberIds);
        return q;
    }

    private PageRespVO<MemberInvoiceApplyListVO> emptyPage(Page<MemberInvoiceApply> page) {
        PageRespVO<MemberInvoiceApplyListVO> empty = new PageRespVO<>();
        empty.setRecords(Collections.emptyList());
        empty.setTotal(0L);
        empty.setPageNo(page.getPageNo());
        empty.setPageSize(page.getPageSize());
        empty.setPages(0L);
        return empty;
    }
}
