package cn.iocoder.yudao.module.system.service.biz;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.ImportResultVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.MedicalRecordsImportExcelVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.MedicalRecordsRespVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.RecordsPageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.AttachmentsDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlyContractDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlyInfoDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.MedicalRecordsDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.AttachmentsMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyContractMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.MedicalRecordsMapper;
import cn.iocoder.yudao.module.system.enums.AttachmentsConstants;
import cn.iocoder.yudao.module.system.util.ImportUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;




/**
 * 医疗记录主 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
public class MedicalRecordsServiceImpl implements MedicalRecordsService {

    @Resource
    private MedicalRecordsMapper recordsMapper;
    @Resource
    private AttachmentsMapper attachmentsMapper;
    @Resource
    private ElderlyInfoMapper elderlyInfoMapper;
    @Resource
    private ElderlyContractMapper elderlyContractMapper;
    @Resource
    private BuildService buildService;

    @Override
    public void createRecords(MedicalRecordsDO createReqVO) {
        // 插入
        recordsMapper.insert(createReqVO);

        List<AttachmentsDO> attachments = createReqVO.getAttachments();
        if (CollectionUtil.isNotEmpty(attachments)) {
            for (AttachmentsDO attachment : attachments) {
                attachment.setBusinessType(AttachmentsConstants.MEDICAL);
                attachment.setBusinessId(createReqVO.getRecordId());
                attachment.setTenantId(TenantContextHolder.getTenantId());
                attachment.setUploadTime(LocalDateTime.now());
                attachmentsMapper.insert(attachment);
            }
        }
    }

    @Override
    public void updateRecords(MedicalRecordsDO updateReqVO) {
        // 更新
        updateReqVO.setUpdateTime(LocalDateTime.now());
        recordsMapper.updateById(updateReqVO);

        attachmentsMapper.delete(new LambdaQueryWrapperX<AttachmentsDO>()
                .eq(AttachmentsDO::getBusinessType, AttachmentsConstants.MEDICAL)
                .eq(AttachmentsDO::getBusinessId, updateReqVO.getRecordId()));

        List<AttachmentsDO> attachments = updateReqVO.getAttachments();
        if (CollectionUtil.isNotEmpty(attachments)) {
            for (AttachmentsDO attachment : attachments) {
                attachment.setBusinessType(AttachmentsConstants.MEDICAL);
                attachment.setBusinessId(updateReqVO.getRecordId());
                attachment.setTenantId(TenantContextHolder.getTenantId());
                attachment.setUploadTime(LocalDateTime.now());
                attachmentsMapper.insert(attachment);
            }
        }
    }

    @Override
    public void deleteRecords(Integer id) {
        // 删除
        recordsMapper.deleteById(id);
    }

    @Override
    public MedicalRecordsDO getRecords(Integer id) {
        MedicalRecordsDO medicalRecordsDO = recordsMapper.selectById(id);

        ElderlyInfoDO elderlyInfoDO = elderlyInfoMapper.selectById(medicalRecordsDO.getElderId());
        medicalRecordsDO.setElderlyInfo(elderlyInfoDO);
        medicalRecordsDO.setBedInfo(buildService.getFullBedName(Long.valueOf(medicalRecordsDO.getElderId())));

        List<AttachmentsDO> attachments = attachmentsMapper.selectList(new LambdaQueryWrapperX<AttachmentsDO>()
                .eq(AttachmentsDO::getBusinessType, AttachmentsConstants.MEDICAL)
                .eq(AttachmentsDO::getBusinessId, medicalRecordsDO.getRecordId()));
        medicalRecordsDO.setAttachments(attachments);

        return medicalRecordsDO;

    }

    @Override
    public PageResult<MedicalRecordsRespVO> getRecordsPage(RecordsPageReqVO pageReqVO) {
        PageResult<MedicalRecordsDO> pageResult = recordsMapper.selectPage(pageReqVO);
        PageResult<MedicalRecordsRespVO> resp = BeanUtils.toBean(pageResult, MedicalRecordsRespVO.class);
        for (MedicalRecordsRespVO vo : resp.getList()) {
            vo.setBedInfo(buildService.getFullBedName(Long.valueOf(vo.getElderId())));
            ElderlyContractDO contract = elderlyContractMapper.selectOne(new LambdaQueryWrapperX<ElderlyContractDO>()
                    .eq(ElderlyContractDO::getElderId, vo.getElderId())
                    .eq(ElderlyContractDO::getStatus, 1)
                    .orderByDesc(ElderlyContractDO::getCreatedTime)
                    .last("LIMIT 1"));
            if (contract != null) {
                vo.setContractNumber(contract.getContractNumber());
            }
        }
        return resp;
    }

    @Override
    public void exportImportTemplate(HttpServletResponse response) throws IOException {
        ExcelUtils.write(response, "医疗记录导入模板.xlsx", "模板",
                MedicalRecordsImportExcelVO.class, java.util.Collections.emptyList());
    }

    @Override
    public ImportResultVO importMedicalRecords(MultipartFile file) throws Exception {
        List<MedicalRecordsImportExcelVO> list = ExcelUtils.read(file, MedicalRecordsImportExcelVO.class);

        int rowNum = 1;
        int success = 0;
        List<ImportResultVO.RowError> failures = new ArrayList<>();

        for (MedicalRecordsImportExcelVO row : list) {
            rowNum++;

            if (StrUtil.isEmpty(row.getContractNumber())) {
                ImportUtil.addFailure(failures, rowNum, row.getElderName(), row.getContractNumber(), "合同号不能为空");
                continue;
            }

            ElderlyContractDO contract = elderlyContractMapper.selectValidContract(row.getContractNumber());
            if (contract == null) {
                ImportUtil.addFailure(failures, rowNum, row.getElderName(), row.getContractNumber(), "未找到对应合同或合同状态无效");
                continue;
            }
            if (contract.getElderId() == null) {
                ImportUtil.addFailure(failures, rowNum, row.getElderName(), row.getContractNumber(), "合同未关联长者");
                continue;
            }

            MedicalRecordsDO record = new MedicalRecordsDO();
            record.setElderId(contract.getElderId().intValue());
            record.setElderName(StrUtil.blankToDefault(row.getElderName(), contract.getElderName()));
            record.setDiscoveryTime(row.getDiscoveryTime());
            record.setDiscoverer(row.getDiscoverer());
            record.setConditionDesc(row.getConditionDesc());
            record.setHandlingNote(row.getHandlingNote());
            record.setTenantId(TenantContextHolder.getTenantId());

            try {
                recordsMapper.insert(record);
                success++;
            } catch (Exception e) {
                ImportUtil.addFailure(failures, rowNum, row.getElderName(), row.getContractNumber(), "插入数据库失败", e);
            }
        }

        return ImportUtil.buildResult(success, failures);
    }
}