package com.ruoyi.care.service.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.List;

import com.ruoyi.care.domain.CareApplications;
import com.ruoyi.care.domain.CareNurseRecords;
import com.ruoyi.care.domain.CareRecords;
import com.ruoyi.care.mapper.CareApplicationsMapper;
import com.ruoyi.care.mapper.CareNurseRecordsMapper;
import com.ruoyi.care.mapper.CareRecordsMapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.enums.CareApplyStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.care.mapper.CareNurseClocksMapper;
import com.ruoyi.care.domain.CareNurseClocks;
import com.ruoyi.care.service.ICareNurseClocksService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 护理任务打卡Service业务层处理
 * 
 * @author qy
 * @date 2024-11-26
 */
@Service
public class CareNurseClocksServiceImpl implements ICareNurseClocksService 
{
    @Autowired
    private CareNurseClocksMapper careNurseClocksMapper;
    @Autowired
    private CareApplicationsMapper careApplicationsMapper;
    @Autowired
    private CareNurseRecordsMapper careNurseRecordsMapper;
    @Autowired
    private CareRecordsMapper careRecordsMapper;
    /**
     * 查询护理任务打卡
     * 
     * @param clockId 护理任务打卡主键
     * @return 护理任务打卡
     */
    @Override
    public CareNurseClocks selectCareNurseClocksByClockId(Long clockId)
    {
        return careNurseClocksMapper.selectCareNurseClocksByClockId(clockId);
    }

    /**
     * 查询护理任务打卡列表
     * 
     * @param careNurseClocks 护理任务打卡
     * @return 护理任务打卡
     */
    @Override
    public List<CareNurseClocks> selectCareNurseClocksList(CareNurseClocks careNurseClocks)
    {
        return careNurseClocksMapper.selectCareNurseClocksList(careNurseClocks);
    }

    /**
     * 新增护理任务打卡
     * 
     * @param careNurseClocks 护理任务打卡
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCareNurseClocks(CareNurseClocks careNurseClocks,Long userId)
    {
        String psths[]=careNurseClocks.getImgPaths().split(",");
        int result=0;
        //获取当前节点记录
        CareRecords curr=new CareRecords();
        curr.setApplyId(Long.parseLong(careNurseClocks.getApplyId()));
        curr.setState("0");
        List<CareRecords> list=careRecordsMapper.selectCareRecordsList(curr);
        if(list.size()>0){
            curr=list.get(0);
            curr.setOperate(userId.toString());
            careRecordsMapper.updateCareRecords(curr);
        }

        careNurseClocks.setCreateTime(DateUtils.getNowDate());
        careNurseClocks.setImgPaths(careNurseClocks.getImgPaths().replaceAll("/temp/","/upload/"));
        // 判断当天任务是否一开始
        String  date=careNurseClocks.getNursingTime().substring(0,10);
        CareNurseRecords careNurseRecords= new CareNurseRecords();
        careNurseRecords.setNursingTime(date);
        careNurseRecords.setApplyId(Long.parseLong(careNurseClocks.getApplyId()));
        List<CareNurseRecords> lst=careNurseRecordsMapper.selectCareNurseRecordsList(careNurseRecords);
        if(lst.size()>0){
            careRecordsMapper.updateCareRecords(curr);
           //已经开始了直接新增打卡记录
           result= careNurseClocksMapper.insertCareNurseClocks(careNurseClocks);
        }else{
           //修改申请状态为正在进行，并添加护理记录及打卡记录
           CareApplications careApplications=careApplicationsMapper.selectCareApplicationsByApplyId(Long.parseLong(careNurseClocks.getApplyId()));
           careApplications.setDealStatus("in_progress");
           careApplicationsMapper.updateCareApplications(careApplications);

           careNurseRecords=new CareNurseRecords();
           careNurseRecords.setNursingTime(careNurseClocks.getNursingTime().substring(0,10));
           careNurseRecords.setApplyId(Long.parseLong(careNurseClocks.getApplyId()));
           careNurseRecordsMapper.insertCareNurseRecords(careNurseRecords);

           //获取打卡次数
            CareNurseRecords recordCount=new CareNurseRecords();
            recordCount.setApplyId(Long.parseLong(careNurseClocks.getApplyId()));
           curr.setRemark("已打卡"+careNurseRecordsMapper.selectCareNurseRecordsList(recordCount).size()+"次");
           careRecordsMapper.updateCareRecords(curr);

            result=careNurseClocksMapper.insertCareNurseClocks(careNurseClocks);
        }

        //保存成功后 将文件转移到正式路径

        for(int i=0;i<psths.length;i++){
            String path= RuoYiConfig.getProfile()+psths[i].replace("profile","");
            String finalFilePath=RuoYiConfig.getUploadPath()+psths[i].replace("/profile/temp","");
            try {
                moveFileToFinalPath(path,finalFilePath);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return result;

    }

    /**
     * 修改护理任务打卡
     * 
     * @param careNurseClocks 护理任务打卡
     * @return 结果
     */
    @Override
    public int updateCareNurseClocks(CareNurseClocks careNurseClocks)
    {
        String psths[]=careNurseClocks.getImgPaths().split(",");
        int result=0;

        careNurseClocks.setUpdateTime(DateUtils.getNowDate());
        careNurseClocks.setImgPaths(careNurseClocks.getImgPaths().replaceAll("/temp/","/upload/"));
        // 判断当天任务是否一开始
        String  date=careNurseClocks.getNursingTime().substring(0,10);
        CareNurseRecords careNurseRecords= new CareNurseRecords();
        careNurseRecords.setNursingTime(date);
        careNurseRecords.setApplyId(Long.parseLong(careNurseClocks.getApplyId()));
        List<CareNurseRecords> lst=careNurseRecordsMapper.selectCareNurseRecordsList(careNurseRecords);
        if(lst.size()>0){
            //已经开始了直接新增打卡记录
            result= careNurseClocksMapper.updateCareNurseClocks(careNurseClocks);
        }else{
            //修改申请状态为正在进行，并添加护理记录及打卡记录
            CareApplications careApplications=careApplicationsMapper.selectCareApplicationsByApplyId(Long.parseLong(careNurseClocks.getApplyId()));
            careApplications.setDealStatus("in_progress");
            careApplicationsMapper.updateCareApplications(careApplications);

            careNurseRecords=new CareNurseRecords();
            careNurseRecords.setNursingTime(careNurseClocks.getNursingTime().substring(0,10));
            careNurseRecords.setApplyId(Long.parseLong(careNurseClocks.getApplyId()));
            careNurseRecordsMapper.insertCareNurseRecords(careNurseRecords);

            //获取打卡次数
            CareNurseRecords recordCount=new CareNurseRecords();
            recordCount.setApplyId(Long.parseLong(careNurseClocks.getApplyId()));
            CareRecords curr=new CareRecords();
            curr.setApplyId(Long.parseLong(careNurseClocks.getApplyId()));
            curr.setState("0");
            List<CareRecords> list=careRecordsMapper.selectCareRecordsList(curr);
            if(list.size()>0){
                curr=list.get(0);
                curr.setRemark("已打卡"+careNurseRecordsMapper.selectCareNurseRecordsList(recordCount).size()+"次");
                careRecordsMapper.updateCareRecords(curr);
            }

            result=careNurseClocksMapper.updateCareNurseClocks(careNurseClocks);
        }

        //保存成功后 将文件转移到正式路径

        for(int i=0;i<psths.length;i++){
            if(psths[i].indexOf("/temp")>-1){
                String path= RuoYiConfig.getProfile()+psths[i].replace("profile","");
                String finalFilePath=RuoYiConfig.getUploadPath()+psths[i].replace("/profile/temp","");
                try {
                    moveFileToFinalPath(path,finalFilePath);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }
        return result;
    }

    /**
     * 批量删除护理任务打卡
     * 
     * @param clockIds 需要删除的护理任务打卡主键
     * @return 结果
     */
    @Override
    public int deleteCareNurseClocksByClockIds(Long[] clockIds)
    {
        return careNurseClocksMapper.deleteCareNurseClocksByClockIds(clockIds);
    }

    /**
     * 删除护理任务打卡信息
     * 
     * @param clockId 护理任务打卡主键
     * @return 结果
     */
    @Override
    public int deleteCareNurseClocksByClockId(Long clockId)
    {
        return careNurseClocksMapper.deleteCareNurseClocksByClockId(clockId);
    }

    private void moveFileToFinalPath(String tempFilePath, String finalFilePath) throws IOException {
        // 规范化路径
        Path tempPath = Paths.get(tempFilePath).normalize();
        Path finalPath = Paths.get(finalFilePath).normalize();

        // 检查临时文件是否存在
        if (!Files.exists(tempPath)) {
            throw new IOException("临时文件不存在, 请重新上传: " + tempPath.toString());
        }

        // 创建目标目录（如果不存在）
        Path finalDir = finalPath.getParent();
        if (finalDir != null && !Files.exists(finalDir)) {
            Files.createDirectories(finalDir);
        }

        // 移动文件到最终路径
        try {
            Files.move(tempPath, finalPath, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件已成功移动到: " + finalPath.toString());
        } catch (IOException e) {
            throw new IOException("文件移动失败: " + e.getMessage());
        }
    }
}
