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

import cn.hutool.core.util.StrUtil;
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.CommunicationRecordPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.CommunicationRecordRespVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.FamilyCommunicationRecordImportExcelVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.ImportResultVO;
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.FamilyCommunicationRecordDO;
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.FamilyCommunicationRecordMapper;
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 cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import org.springframework.web.multipart.MultipartFile;

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


/**
 * 家属沟通记录 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
public class FamilyCommunicationRecordServiceImpl implements FamilyCommunicationRecordService {

    @Resource
    private FamilyCommunicationRecordMapper communicationRecordMapper;
    @Resource
    private BuildService buildService;
    @Resource
    private ElderlyInfoMapper elderlyInfoMapper;

    @Resource
    private ElderlyContractMapper elderlyContractMapper;

    @Override
    public void createCommunicationRecord(FamilyCommunicationRecordDO createReqVO) {

        communicationRecordMapper.insert(createReqVO);

    }

    @Override
    public void updateCommunicationRecord(FamilyCommunicationRecordDO updateReqVO) {
        // 更新
        communicationRecordMapper.updateById(updateReqVO);
    }

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



    @Override
    public FamilyCommunicationRecordDO getCommunicationRecord(Integer id) {
        FamilyCommunicationRecordDO familyCommunicationRecordDO = communicationRecordMapper.selectById(id);
        ElderlyInfoDO elderlyInfoDO = elderlyInfoMapper.selectById(familyCommunicationRecordDO.getElderId());
        familyCommunicationRecordDO.setElderlyInfo(elderlyInfoDO);
        familyCommunicationRecordDO.setBedInfo(buildService.getFullBedName(Long.valueOf(familyCommunicationRecordDO.getElderId())));
        return familyCommunicationRecordDO;
    }

    @Override
    public PageResult<CommunicationRecordRespVO> getCommunicationRecordPage(CommunicationRecordPageReqVO pageReqVO) {
        PageResult<FamilyCommunicationRecordDO> result = communicationRecordMapper.selectPage(pageReqVO);
        PageResult<CommunicationRecordRespVO> pageResult = BeanUtils.toBean(result, CommunicationRecordRespVO.class);
        for (CommunicationRecordRespVO communicationRecordRespVO : pageResult.getList()) {
            communicationRecordRespVO.setBedInfo(buildService.getFullBedName(communicationRecordRespVO.getElderId()));
            ElderlyContractDO contract = elderlyContractMapper.selectOne(new LambdaQueryWrapperX<ElderlyContractDO>()
                    .eq(ElderlyContractDO::getElderId, communicationRecordRespVO.getElderId())
                    .eq(ElderlyContractDO::getStatus, 1)
                    .orderByDesc(ElderlyContractDO::getCreatedTime)
                    .last("LIMIT 1"));
            if (contract != null) {
                communicationRecordRespVO.setContractNumber(contract.getContractNumber());
            }
        }
        return pageResult;
    }

    @Override
    public void exportImportTemplate(HttpServletResponse response) throws IOException {
        ExcelUtils.write(response, "家属沟通记录导入模板.xlsx", "模板",
                FamilyCommunicationRecordImportExcelVO.class, java.util.Collections.emptyList());
    }

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

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

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

            FamilyCommunicationRecordDO record = new FamilyCommunicationRecordDO();
            record.setElderId(contract.getElderId()); // Long
            record.setElderName(StrUtil.blankToDefault(row.getElderName(), contract.getElderName()));
            record.setCommunicationTime(row.getCommunicationTime());
            record.setCommunicationMethod(row.getCommunicationMethod());
            record.setServicePerson(row.getServicePerson());
            record.setFamilyName(row.getFamilyName());
            record.setRelationshipWithElder(row.getRelationshipWithElder());
            record.setCommunicationContent(row.getCommunicationContent());
            record.setSolutionEffect(row.getSolutionEffect());
            record.setTenantId(TenantContextHolder.getTenantId());

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

        return ImportUtil.buildResult(success, failures);
    }

}