package cn.cslg.report.service.impl;

import cn.cslg.report.common.model.QueryFUEntity;
import cn.cslg.report.common.model.dto.FollowUpDTO;
import cn.cslg.report.common.model.dto.FollowUpUpdateDTO;
import cn.cslg.report.common.model.dto.RegisterDTO;
import cn.cslg.report.common.model.vo.FilesVO;
import cn.cslg.report.common.model.vo.FollowUpVO;
import cn.cslg.report.common.model.vo.PersonnelVO;
import cn.cslg.report.common.utils.CacheUtils;
import cn.cslg.report.common.utils.Response;
import cn.cslg.report.common.utils.SecurityUtils.LoginUtils;
import cn.cslg.report.entity.AssoFollowUpFile;
import cn.cslg.report.entity.FollowUp;
import cn.cslg.report.exception.XiaoShiException;
import cn.cslg.report.mapper.FollowUpMapper;
import cn.cslg.report.service.IFollowUpService;
import cn.cslg.report.service.business.ReportFileService;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 后续事项的Service层实现类
 * @Author xiexiang
 * @Date 2023/4/1
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FollowUpServiceImpl implements IFollowUpService {
    private final FollowUpMapper followUpMapper;
    private final ReportFileService reportFileService;
    private final CacheUtils cacheUtils;
    private final LoginUtils loginUtils;

    /**
     * 新增后续事项
     *
     * @param followUps 新增后续事项的前端传输DTO数据对象
     */
    @Override
    public void add(List<FollowUpDTO> followUps) {
        log.info("开始处理【新增后续事项】的业务，参数为：{}", followUps);
        FollowUp followUp = new FollowUp();
        for(FollowUpDTO followUpDTO:followUps){
            if(followUpDTO.getFollowUpName() == null){
                log.info("后续事项名称不可为空");
            }
        }
        //判断传入列表不为空
        if (followUps != null && followUps.size() > 0 ) {
            //遍历传入列表
            for (int i = 0; i < followUps.size(); i++) {
                //DTO赋值给后续事项表实体类
                FollowUpDTO followUpDTO = followUps.get(i);
                followUpDTO.setStatus("进行中");
                BeanUtils.copyProperties(followUpDTO, followUp);
                //获取当前登陆人信息
                PersonnelVO personnelVO = cacheUtils.getLoginUser(loginUtils.getId());
                //给实体类赋值登陆人id和姓名
                followUp.setCreatePersonId(personnelVO.getId());
                followUp.setCreatePersonName(personnelVO.getName());
                //数据入表
                log.info("数据入表");
                int rows = followUpMapper.add(followUp);
                if (rows != 1) {
                    String message = "新增后续事项第" + i + "条失败";
                    log.info("数据入后续事项表失败，{}", message);
                    throw new XiaoShiException(message);
                }
            }log.info("新增后续事项完成");
        }
    }

    /**
     * 修改后续事项
     *
     * @param followUpUpdateDTOList 修改后续事项的前端传输DTO数据对象
     */
    @Override
    public void update(List<FollowUpUpdateDTO> followUpUpdateDTOList){
        log.info("开始处理【修改后续事项】的业务，参数为：{}", followUpUpdateDTOList);
        //DTO赋值给后续事项表实体类
        FollowUp followUp = new FollowUp();
        if (followUpUpdateDTOList.size() > 0 && followUpUpdateDTOList != null) {
            //遍历传入列表
            for (int i = 0; i < followUpUpdateDTOList.size(); i++) {
                FollowUpUpdateDTO followUpUpdateDTO = followUpUpdateDTOList.get(i);
                BeanUtils.copyProperties(followUpUpdateDTO, followUp);
                //根据id修改后续事项表数据
                log.info("修改后续事项表数据");
                int rows = followUpMapper.update(followUp);
                if (rows != 1) {
                    String message = "第" + i + "条失败";
                    log.info("修改后续事项表数据失败，{}", message);
                }
            }log.info("修改后续事项完成");
        }
    }

    @Override
    public List<FollowUpVO> query(Integer reportId) {
        return followUpMapper.query(reportId);
    }

    /**
     * 根据报告id查询
     *
     * @param queryFUEntity
     */
    @Override
    public List<FollowUpVO> findAllByPage(QueryFUEntity queryFUEntity){
        PageHelper.startPage(queryFUEntity.getCurrent(), queryFUEntity.getSize());
        List<FollowUpVO> followUpVOS = followUpMapper.query(queryFUEntity.getReportId());
        return followUpVOS;
    }

    /**
     * 根据ids删除许可记录数据
     *
     * @param ids
     */
    @Override
    public void delete(List<Integer> ids) {
        log.info("开始处理【删除许可记录】的业务，参数为：{}", ids);
        if (ids != null) {
            followUpMapper.delete(ids);
            log.info("产品删除完成");
        } else {
            log.info("删除产品失败，产品不存在");
        }
    }

    /**
     * 登记结果
     *
     * @param register
     * @param files
     */
    @Override
    public void register(RegisterDTO register, List<MultipartFile> files) throws ParseException {
        //获取当前时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = dateFormat.format(new Date());//date为当前时间 是String类型的时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date finishTime = simpleDateFormat.parse(date);//转换为Date类型
        System.out.println("等级结果当前完成时间"+ finishTime);

        FollowUp followUp = new FollowUp();
        //从registerDTO中取出后续事项id进行对应的操作
        followUp.setId(register.getFollowUpId());
        followUp.setStatus("已完成");
        followUp.setConclusion(register.getConclusion());
        followUp.setFinishTime(finishTime);
        //更新操作 将conclusion更新进入表
        int rows = followUpMapper.update(followUp);
        if (rows != 1) {
            String message = "登记结果失败，服务器忙请稍后再试";
            log.info("登记结果失败，{}", message);
        }
        log.info("登记结果完成");

        //删除

        //简化定义后续事项id
        int followUpId = register.getFollowUpId();
        //根据后续事项id查询关联表找出所有fileId
        List<Integer> fileIdS = followUpMapper.queryFileIdByFollowUpId(followUpId);
        //判断第二次登记结果时候文件数量
        List<FilesVO> filesVOs= register.getFilesVOs();
        if(filesVOs != null){//传入不为空
            //遍历前端传入数据，取得fileId的集合ids
            List<Integer> ids = new ArrayList<>();
            for(FilesVO filesVO:filesVOs){
                int id = filesVO.getFileId();
                ids.add(id);
            }
            //定义一个list存放需要删除的fileId
            List<Integer> deleteIds = new ArrayList<>();
            //遍历数据库中存在的fileId
            for(Integer fileId : fileIdS){
                if(ids.contains(fileId) != true){//不为true，就是没有，需要删除
                    deleteIds.add(fileId);
                }
            }
            if(deleteIds.size()>0) {
                followUpMapper.deleteAssoId(followUpId, deleteIds);
                log.info("多余关联附件删除完成");
            }
        }else if(filesVOs != null && filesVOs.size() == 0){//传入为空数组 等于附件需要全部删除
            followUpMapper.deleteAssoId(followUpId,fileIdS);
        }
        //新增文件

        //上传附件 进行关联绑定
        if (files != null && files.size() != 0) {
            //将文档上传并返回文件入库的Id
            List<Integer> fileIds = reportFileService.uploadFiles(files);
            this.addAsso(register.getFollowUpId(), fileIds);
        }
        //批量新增后续事项
        if(register.getFollowUps() != null && register.getFollowUps().size()>0) {
            this.add(register.getFollowUps());
        }
    }

    /**
     * @param followUpId 后续事项id
     * @param fileIds  文件id
     * @return
     * @function 上传后续事项与文件关联表 对应实体AssoFollowUpFile 0代表上传文件为附件
     */
    public String addAsso(Integer followUpId, List<Integer> fileIds) {
        for(int i = 0; i < fileIds.size(); i++){
            Integer fileId = fileIds.get(i);
            AssoFollowUpFile assoFollowUpFile = new AssoFollowUpFile();
            assoFollowUpFile.setFollowUpId(followUpId);
            assoFollowUpFile.setFileId(fileId);
            assoFollowUpFile.setFileType(0);
            int rows = followUpMapper.addAssoIds(assoFollowUpFile);
            System.out.println(rows);
            if(rows != 1){
                String message = "第" + i + "条失败";
                log.info("新增后续事项和附件id关联表数据失败，{}", message);
            }
        }log.info("新增后续事项和附件id关联表完成");
        return Response.success();
    }

    /**
     * 第二次登记结果，根据传入的register中的followUpId和filesVOs中的fileId删除关联表中的多出的数据
     *
     * @param followUpId 后续事项id
     * @param fileIds 附件id
     */
    @Override
    public void deleteAssoId(Integer followUpId,List<Integer> fileIds){
        log.info("开始处理【删除多余关联附件】的业务，参数为：{}", followUpId,fileIds);
        if (followUpId != null && fileIds !=null) {
            followUpMapper.deleteAssoId(followUpId,fileIds);
            log.info("多余关联附件删除完成");
        } else {
            log.info("删除多余关联附件失败，多余关联附件不存在");
        }
    }
}
