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.NutritionRecordDO;
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.NutritionRecordMapper;
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("nutritionRecordService")
@Validated
public class NutritionRecordServiceImpl implements NutritionRecordService {

    @Resource
    private NutritionRecordMapper recordMapper;
    @Resource
    private ElderlyInfoMapper elderlyInfoMapper;
    @Resource
    private BuildService buildService;

    @Resource
    private ElderlyContractMapper elderlyContractMapper;

    @Override
    public void createRecord(NutritionRecordDO createReqVO) {
        // 插入
        recordMapper.insert(createReqVO);
    }

    @Override
    public void updateRecord(NutritionRecordDO updateReqVO) {
        // 更新
        recordMapper.updateById(updateReqVO);
    }

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

    @Override
    public NutritionRecordDO getRecord(Integer id) {
        NutritionRecordDO nutritionRecordDO = recordMapper.selectById(id);

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

        return nutritionRecordDO;
    }

    @Override
    public PageResult<NutritionRecordRespVO> getRecordPage(NutritionRecordPageReqVO pageReqVO) {
        PageResult<NutritionRecordDO> pageResult = recordMapper.selectPage(pageReqVO);
        PageResult<NutritionRecordRespVO> resp = BeanUtils.toBean(pageResult, NutritionRecordRespVO.class);
        for (NutritionRecordRespVO 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", "模板",
                NutritionRecordImportExcelVO.class, java.util.Collections.emptyList());
    }

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

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

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

            NutritionRecordDO record = new NutritionRecordDO();
            record.setElderId(contract.getElderId().intValue());
            record.setElderName(StrUtil.blankToDefault(row.getElderName(), contract.getElderName()));
            record.setRecordTime(row.getRecordTime());
            record.setDietitian(row.getDietitian());
            record.setRecordContent(row.getRecordContent());
            record.setTenantId(TenantContextHolder.getTenantId());

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

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