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

import cn.hutool.core.util.StrUtil;
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.*;
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.RehabilitationAssessmentsDO;
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.RehabilitationAssessmentsMapper;
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.pojo.PageResult;
import org.springframework.web.multipart.MultipartFile;

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


/**
 * 康复评估记录 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
public class RehabilitationAssessmentsServiceImpl implements RehabilitationAssessmentsService {

    @Resource
    private RehabilitationAssessmentsMapper assessmentsMapper;
    @Resource
    private ElderlyInfoMapper elderlyInfoMapper;
    @Resource
    private BuildService buildService;

    @Resource
    private ElderlyContractMapper elderlyContractMapper;

    @Override
    public Integer createAssessments(RehabilitationAssessmentsDO createReqVO) {
        // 插入
        assessmentsMapper.insert(createReqVO);
        // 返回
        return createReqVO.getAssessmentId();
    }

    @Override
    public void updateAssessments(RehabilitationAssessmentsDO updateReqVO) {
        // 更新
        assessmentsMapper.updateById(updateReqVO);
    }

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


    @Override
    public RehabilitationAssessmentsDO getAssessments(Integer id) {
        RehabilitationAssessmentsDO rehabilitationAssessmentsDO = assessmentsMapper.selectById(id);
        ElderlyInfoDO elderlyInfoDO = elderlyInfoMapper.selectById(rehabilitationAssessmentsDO.getElderId());
        rehabilitationAssessmentsDO.setElderlyInfo(elderlyInfoDO);
        rehabilitationAssessmentsDO.setBedInfo(buildService.getFullBedName(Long.valueOf(rehabilitationAssessmentsDO.getElderId())));
        return rehabilitationAssessmentsDO;
    }

    @Override
    public PageResult<RehabilitationAssessmentsRespVO> getAssessmentsPage(AssessmentsPageReqVO pageReqVO) {
        PageResult<RehabilitationAssessmentsDO> pageResult = assessmentsMapper.selectPage(pageReqVO);
        PageResult<RehabilitationAssessmentsRespVO> resp = BeanUtils.toBean(pageResult, RehabilitationAssessmentsRespVO.class);
        for (RehabilitationAssessmentsRespVO 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", "模板",
                RehabilitationAssessmentsImportExcelVO.class, java.util.Collections.emptyList());
    }

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

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

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

            RehabilitationAssessmentsDO record = new RehabilitationAssessmentsDO();
            record.setElderId(contract.getElderId().intValue());
            record.setElderName(StrUtil.blankToDefault(row.getElderName(), contract.getElderName()));
            record.setAssessmentTime(row.getAssessmentTime());
            record.setAssessmentTimes(row.getAssessmentTimes());
            record.setTherapist(row.getTherapist());
            record.setAdmissionCondition(row.getAdmissionCondition());
            record.setDysfunction(row.getDysfunction());
            record.setRehabilitationMethod(row.getRehabilitationMethod());
            record.setRehabilitationPlan(row.getRehabilitationPlan());
            record.setExpectedEffect(row.getExpectedEffect());
            record.setTenantId(TenantContextHolder.getTenantId());

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

        return ImportUtil.buildResult(success, failures);
    }

}