package org.dromara.web.service.impl;
import java.util.Date;
import com.google.common.collect.Maps;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.web.domain.ChargeRecord;
import org.dromara.web.domain.InvoiceRecord;
import org.dromara.web.domain.bo.EmailSendBo;
import org.dromara.web.domain.bo.InvoiceMakeOutBo;
import org.dromara.web.mapper.ChargeRecordMapper;
import org.dromara.web.mapper.InvoiceRecordMapper;
import org.dromara.web.service.EmailService;
import org.dromara.web.service.InvoiceManagementService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: Huanyi
 * @CreateTime: 2025-08-15
 * @Description:
 * @Version: 1.0
 */

@Service
@RequiredArgsConstructor
@Slf4j
public class InvoiceManagementServiceImpl implements InvoiceManagementService {

    private final EmailService emailService;

    private final ChargeRecordMapper chargeRecordMapper;
    private final InvoiceRecordMapper invoiceRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R makeOut(InvoiceMakeOutBo bo) {

        EmailSendBo sendBo = new EmailSendBo();
        sendBo.setEmail(bo.getEmail());
        sendBo.setMessage("test");
        sendBo.setFileBase64("");
        emailService.send(sendBo);

        LambdaUpdateWrapper<ChargeRecord> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ChargeRecord::getId, bo.getId()).set(ChargeRecord::getWhetherInvoice, 1);
        int updateFlag = chargeRecordMapper.update(wrapper);
        if (updateFlag <= 0) throw new RuntimeException("开票失败！");

        ChargeRecord chargeRecord = chargeRecordMapper.selectById(bo.getId());

        InvoiceRecord record = new InvoiceRecord();
        record.setNumber("");
        record.setType(bo.getType() == 0 ? "个人" : "企业");
        record.setHeader("");
        record.setHeaderName("");
        record.setName(chargeRecord.getPatientName());
        record.setAdmissionId(chargeRecord.getPatientNo());
        record.setAmount(chargeRecord.getReceivableAmount());
        record.setProgress(1L);
        record.setFailReason("");

        int insertFlag = invoiceRecordMapper.insert(record);
        if (insertFlag <= 0) throw new RuntimeException("开票失败！");

        return R.ok();
    }
}
