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.CareRecordsPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.ImportResultVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.MedicalCareRecordsImportExcelVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.MedicalCareRecordsRespVO;
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.MedicalCareRecordsDO;
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.MedicalCareRecordsMapper;
import cn.iocoder.yudao.module.system.enums.AttachmentsConstants;
import cn.iocoder.yudao.module.system.util.ImportUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
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.*;

import static org.apache.commons.lang3.time.DateUtils.parseDate;


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

    @Resource
    private MedicalCareRecordsMapper careRecordsMapper;
    @Resource
    private AttachmentsMapper attachmentsMapper;
    @Resource
    private ElderlyInfoMapper elderlyInfoMapper;
    @Resource
    private ElderlyContractMapper elderlyContractMapper;
    @Resource
    private BuildService buildService;

    @Override
    public void createCareRecords(MedicalCareRecordsDO createReqVO) {
        // 插入
        careRecordsMapper.insert(createReqVO);

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

    @Override
    public void updateCareRecords(MedicalCareRecordsDO updateReqVO) {
        // 更新
        careRecordsMapper.updateById(updateReqVO);

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

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

    }

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


    @Override
    public MedicalCareRecordsDO getCareRecords(Integer id) {
        MedicalCareRecordsDO medicalCareRecordsDO = careRecordsMapper.selectById(id);

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

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

        return medicalCareRecordsDO;
    }

    @Override
    public PageResult<MedicalCareRecordsRespVO> getCareRecordsPage(CareRecordsPageReqVO pageReqVO) {
        PageResult<MedicalCareRecordsDO> pageResult = careRecordsMapper.selectPage(pageReqVO);
        PageResult<MedicalCareRecordsRespVO> resp = BeanUtils.toBean(pageResult, MedicalCareRecordsRespVO.class);
        for (MedicalCareRecordsRespVO 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 {
        List<MedicalCareRecordsImportExcelVO> list = Collections.emptyList();
        // 假设你们有 ExcelUtils；如果没有，就用 EasyExcel.write(response.getOutputStream(), MedicalCareRecordsImportExcelVO.class)...
        ExcelUtils.write(response, "医疗护理记录导入模板.xlsx", "模板",
                MedicalCareRecordsImportExcelVO.class, list);
    }
    @Override
    public ImportResultVO importCareRecords(MultipartFile file) throws IOException {
        List<MedicalCareRecordsImportExcelVO> list = ExcelUtils.read(file, MedicalCareRecordsImportExcelVO.class);

        int rowNum = 1; // 如果第一行是表头，则数据从第 2 行开始，按你实际偏移
        int success = 0;
        List<ImportResultVO.RowError> failures = new ArrayList<>();

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

            // 1. 简单校验
            if (StrUtil.isEmpty(row.getContractNumber())) {
                ImportUtil.addFailure(failures, rowNum, row.getElderName(), row.getContractNumber(),"合同编号不能为空");
                continue;
            }
            // 2. 用合同号找长者（只匹配当前租户 + 有效合同 + 最新一条）
            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;
            }

            // 3. 组装 DO
            MedicalCareRecordsDO record = new MedicalCareRecordsDO();
            record.setElderId(contract.getElderId().intValue());
            record.setElderName(row.getElderName() != null ? 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 {
                careRecordsMapper.insert(record);
                success++;
            } catch (Exception e) {
                ImportUtil.addFailure(failures, rowNum, row.getElderName(), row.getContractNumber(),"插入数据库失败：" + e.getMessage());
            }
        }
        return ImportUtil.buildResult(success,failures);
    }
}