package cn.iocoder.yudao.module.system.service.yk.impl;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.yk.vo.YKPaymentRecordConfirmVO;
import cn.iocoder.yudao.module.system.controller.admin.yk.vo.YkElderlyPaymentRecordPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.yk.vo.YkElderlyPaymentRecordPageRespVO;
import cn.iocoder.yudao.module.system.controller.admin.yk.vo.YkElderlyPaymentRecordSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.yk.YkElderlyPaymentRecordDO;
import cn.iocoder.yudao.module.system.dal.mysql.yk.YkElderlyPaymentRecordMapper;
import cn.iocoder.yudao.module.system.service.yk.YkElderlyInfoService;
import cn.iocoder.yudao.module.system.service.yk.YkElderlyPaymentRecordService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;


/**
 * 颐康长者收款记录信息 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
public class YkElderlyPaymentRecordServiceImpl implements YkElderlyPaymentRecordService {

    @Resource
    private YkElderlyPaymentRecordMapper elderlyPaymentRecordMapper;

    @Resource
    private YkElderlyInfoService ykElderlyInfoService;

    @Override
    public Long createElderlyPaymentRecord(YkElderlyPaymentRecordSaveReqVO createReqVO) {
        // 插入
        YkElderlyPaymentRecordDO elderlyPaymentRecord = BeanUtils.toBean(createReqVO, YkElderlyPaymentRecordDO.class);
        elderlyPaymentRecordMapper.insert(elderlyPaymentRecord);
        
        // 自动确认：查询该日期内是否有财务变动记录未确认，金额匹配则相互确认
        String confirmMsg = ykElderlyInfoService.autoConfirmPaymentRecord(elderlyPaymentRecord);
        // 如果确认失败，记录日志（可以根据需要改为抛出异常或返回提示信息）
        if (confirmMsg != null) {
            // 这里可以记录日志，或者根据需要处理提示信息
            // 由于接口返回Long，暂时通过日志记录，如果需要返回提示信息，可以修改接口返回类型
        }
        
        // 返回
        return elderlyPaymentRecord.getId();
    }

    @Override
    public String paymentRecordConfirmChangeRecord(YKPaymentRecordConfirmVO createReqVO) {
        // 插入
        YkElderlyPaymentRecordDO elderlyPaymentRecord = new YkElderlyPaymentRecordDO();
        elderlyPaymentRecord.setPaymentType(createReqVO.getPaymentType());
        elderlyPaymentRecord.setOperator(createReqVO.getOperator());
        elderlyPaymentRecord.setAmount(createReqVO.getAmount());
        elderlyPaymentRecord.setYkElderId(createReqVO.getYkElderId());
        elderlyPaymentRecord.setPaymentDateTime(createReqVO.getPaymentDateTime().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime());
        // 自动确认：查询该日期内是否有财务变动记录未确认，金额匹配则相互确认
        return ykElderlyInfoService.autoConfirmPaymentRecord(elderlyPaymentRecord);
    }

    @Override
    public void updateElderlyPaymentRecord(YkElderlyPaymentRecordSaveReqVO updateReqVO) {
        // 更新
        YkElderlyPaymentRecordDO updateObj = BeanUtils.toBean(updateReqVO, YkElderlyPaymentRecordDO.class);
        elderlyPaymentRecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteElderlyPaymentRecord(Long id) {
        // 删除
        elderlyPaymentRecordMapper.deleteById(id);
    }


    @Override
    public YkElderlyPaymentRecordDO getElderlyPaymentRecord(Long id) {
        return elderlyPaymentRecordMapper.selectById(id);
    }

    @Override
    public PageResult<YkElderlyPaymentRecordDO> getElderlyPaymentRecordPage(YkElderlyPaymentRecordPageReqVO pageReqVO) {
        if(pageReqVO.getDateRange() != null && pageReqVO.getDateRange().length == 2){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            pageReqVO.setBegin(formatter.format(pageReqVO.getDateRange()[0].atTime(LocalTime.MIN)));
            pageReqVO.setEnd(formatter.format(pageReqVO.getDateRange()[1].atTime(LocalTime.MAX)));
        }
        return elderlyPaymentRecordMapper.selectPage(pageReqVO);
    }

    @Override
    public YkElderlyPaymentRecordPageRespVO getElderlyPaymentRecordPageWithStats(YkElderlyPaymentRecordPageReqVO pageReqVO) {
        // 处理日期范围
        if(pageReqVO.getDateRange() != null && pageReqVO.getDateRange().length == 2){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            pageReqVO.setBegin(formatter.format(pageReqVO.getDateRange()[0].atTime(LocalTime.MIN)));
            pageReqVO.setEnd(formatter.format(pageReqVO.getDateRange()[1].atTime(LocalTime.MAX)));
        }
        
        // 获取分页结果
        PageResult<YkElderlyPaymentRecordDO> pageResult = elderlyPaymentRecordMapper.selectPage(pageReqVO);
        
        // 统计总金额（按日期范围，不考虑分页）
        BigDecimal cashTotalAmount = elderlyPaymentRecordMapper.sumCashAmountByDateRange(pageReqVO);
        BigDecimal wechatTotalAmount = elderlyPaymentRecordMapper.sumWechatAmountByDateRange(pageReqVO);
        
        // 构建返回对象
        YkElderlyPaymentRecordPageRespVO respVO = new YkElderlyPaymentRecordPageRespVO();
        respVO.setPageResult(pageResult);
        respVO.setTotalCash(cashTotalAmount);
        respVO.setTotalWechat(wechatTotalAmount);
        
        return respVO;
    }

    @Override
    public void batchDeleteElderlyPaymentRecord(List<Long> ids) {
        elderlyPaymentRecordMapper.deleteBatchIds(ids);
    }

}