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.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.*;
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.TrainingRecordsDO;
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.TrainingRecordsMapper;
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 cn.iocoder.yudao.framework.common.util.object.BeanUtils;
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 TrainingRecordsServiceImpl implements TrainingRecordsService {

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

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

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

    @Override
    public void updateRecords(TrainingRecordsDO updateReqVO) {
        // 更新
        recordsMapper.updateById(updateReqVO);


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

        List<AttachmentsDO> attachments = updateReqVO.getAttachments();
        if (CollectionUtil.isNotEmpty(attachments)) {
            for (AttachmentsDO attachment : attachments) {
                attachment.setBusinessType(AttachmentsConstants.TRAINING);
                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 TrainingRecordsDO getRecords(Integer id) {
        TrainingRecordsDO trainingRecordsDO = recordsMapper.selectById(id);
        ElderlyInfoDO elderlyInfoDO = elderlyInfoMapper.selectById(trainingRecordsDO.getElderId());
        trainingRecordsDO.setElderlyInfo(elderlyInfoDO);
        trainingRecordsDO.setBedInfo(buildService.getFullBedName(Long.valueOf(trainingRecordsDO.getElderId())));

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

        return trainingRecordsDO;
    }

    @Override
    public PageResult<TrainingRecordsRespVO> getRecordsPage(TrainingRecordsPageReqVO pageReqVO) {
        PageResult<TrainingRecordsDO> pageResult = recordsMapper.selectPage(pageReqVO);
        PageResult<TrainingRecordsRespVO> resp = BeanUtils.toBean(pageResult, TrainingRecordsRespVO.class);
        for (TrainingRecordsRespVO 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", "模板",
                TrainingRecordsImportExcelVO.class, java.util.Collections.emptyList());
    }

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

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

        for (TrainingRecordsImportExcelVO 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;
            }

            TrainingRecordsDO record = new TrainingRecordsDO();
            record.setElderId(contract.getElderId().intValue());
            record.setElderName(StrUtil.blankToDefault(row.getElderName(), contract.getElderName()));
            record.setTrainingTime(row.getTrainingTime());
            record.setTherapist(row.getTherapist());
            record.setRecordContent(row.getRecordContent());
            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);
    }
}