/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.dispatch.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.dispatch.common.FlowConstant;
import com.tofly.dispatch.dto.EmergencyDTO;
import com.tofly.dispatch.dto.EmergencyQuery;
import com.tofly.dispatch.entity.*;
import com.tofly.dispatch.mapper.EmergencyMapper;
import com.tofly.dispatch.service.*;
import com.tofly.dispatch.util.UploadFiles;
import com.tofly.dispatch.vo.EmergencyVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 应急事件（处置预案、事件分析）
 *
 * @author xqf
 * @date Mon Apr 25 00:00:00 CST 2022
 */
@Slf4j
@Service("emergencyService")
public class EmergencyServiceImpl extends ServiceImpl<EmergencyMapper, Emergency> implements EmergencyService {

    @Autowired
    private EmergencyFacilitiesService emergencyFacilitiesService;

    @Autowired
    private EmergencyHazardService emergencyHazardService;

    @Autowired
    private EmergencyStaffService emergencyStaffService;

    @Autowired
    private HazardService hazardService;
    @Autowired
    private StaffService staffService;

    @Autowired
    private  FacilitiesService facilitiesService;

    @Autowired
    private FileService fileService;

    @Value("${dispatch.ftp.emergency}")
    private String filePath;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(EmergencyDTO dto, List<MultipartFile> fileList) {
        checkEventReason(dto);
        setDefaultValue(dto);
        dto.setAnnex(null);
        Emergency data = new Emergency();
        String fileIds = UploadFiles.saveFiles(fileService, fileList, dto.getAnnex(), dto.getAnnex(),
                filePath, "TF_DIC_EMERGENCY_W");
        if (!StringUtils.isEmpty(fileIds)) {
            dto.setAnnex(fileIds);
        }
        BeanUtils.copyProperties(dto, data);
        if (!this.save(data)) {
            throw new RuntimeException("新增失败");
        }

        if (!CollectionUtils.isEmpty(dto.getEmergencyFacilities())) {
            setEmergencyFacilities(dto.getEmergencyFacilities(), data.getId());
        }

        if (!CollectionUtils.isEmpty(dto.getEmergencyStaffs())) {

            setEmergencyStaffs(dto.getEmergencyStaffs(), data.getId());
        }

        if (!CollectionUtils.isEmpty(dto.getEmergencyHazards())) {

            setEmergencyHazards(dto.getEmergencyHazards(), data.getId());
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(EmergencyDTO dto, List<MultipartFile> fileList) {
        checkEventReason(dto);
        Emergency byId = getById(dto.getId());
        String fileIds = UploadFiles.saveFiles(fileService, fileList, byId.getAnnex(), dto.getAnnex(),
                filePath, "TF_DIC_EMERGENCY_W");
        if (!StringUtils.isEmpty(fileIds) || dto.getAnnex().equals("[]")) {
            dto.setAnnex(fileIds);
        }

        Emergency data = new Emergency();
        BeanUtils.copyProperties(dto, data);
        if (!this.updateById(data)) {
            throw new RuntimeException("修改失败");
        }

        //添加关联数据
        emergencyFacilitiesService.deleteEmergencyIds(Collections.singleton(data.getId()));
        emergencyStaffService.deleteEmergencyId(Collections.singleton(data.getId()));
        emergencyHazardService.deleteEmergencyId(Collections.singleton(data.getId()));
        setEmergencyFacilities(dto.getEmergencyFacilities(), data.getId());
        setEmergencyStaffs(dto.getEmergencyStaffs(), data.getId());
        setEmergencyHazards(dto.getEmergencyHazards(), data.getId());

    }



    /**
     * 批量添加-应急设施
     *
     * @param listFacilities 应急设施
     * @param emergencyId    应急事件（处置预案、事件分析）ID
     */
    private void setEmergencyFacilities(List<Facilities> listFacilities, Long emergencyId) {

        if (listFacilities != null && listFacilities.stream().count() > 0) {
            List<EmergencyFacilities> list = new ArrayList<>();
            for (Facilities data : listFacilities) {
                EmergencyFacilities emergencyFacilities = new EmergencyFacilities();
                emergencyFacilities.setEmergencyId(emergencyId);
                emergencyFacilities.setFacilitiesId(data.getId());
                list.add(emergencyFacilities);
            }

            emergencyFacilitiesService.saveBatch(list);
        }
    }


    /**
     * 批量添加-应急通信录
     *
     * @param listStaffs  应急通信录
     * @param emergencyId 应急事件（处置预案、事件分析）ID
     */
    private void setEmergencyStaffs(List<Staff> listStaffs, Long emergencyId) {
        if (listStaffs != null && listStaffs.stream().count() > 0) {
            List<EmergencyStaff> list = new ArrayList<>();
            for (Staff data : listStaffs) {
                EmergencyStaff emergencyStaff = new EmergencyStaff();
                emergencyStaff.setStaffId(data.getId());
                emergencyStaff.setEmergencyId(emergencyId);
                list.add(emergencyStaff);
            }

            emergencyStaffService.saveBatch(list);
        }
    }

    /**
     * 批量添加危险源
     *
     * @param emergencyHazards 危险源
     * @param emergencyId      应急事件（处置预案、事件分析）ID
     */
    public void setEmergencyHazards(List<EmergencyHazard> emergencyHazards, Long emergencyId) {
        if (emergencyHazards != null && emergencyHazards.stream().count() > 0) {
            for (EmergencyHazard emergencyHazard : emergencyHazards) {
                emergencyHazard.setEmergencyId(emergencyId);
            }
            emergencyHazardService.batchInsert(emergencyHazards);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new RuntimeException("传入数据为空");
        }
        QueryWrapper<Emergency> querySWrapper = new QueryWrapper<>();

        querySWrapper.in("ID", ids);
        querySWrapper.ne("CREATE_USER", SecurityUtils.getUserId());
        Integer count_check = this.baseMapper.selectCount(querySWrapper);
        if (count_check > 0) {
            throw new RuntimeException("只能删除自己创建的数据");
        }

        boolean update = this.update(new Emergency(), new UpdateWrapper<Emergency>().lambda()
                .set(Emergency::getIsDel, FlowConstant.SHORT_ONE)
                .eq(Emergency::getIsDel, FlowConstant.SHORT_ZERO)
                .in(Emergency::getId, ids));
        if (!update) {
            throw new RuntimeException("删除失败");
        }
        //删除关联数据
        emergencyFacilitiesService.deleteEmergencyIds(ids);
        emergencyStaffService.deleteEmergencyId(ids);

        emergencyHazardService.deleteEmergencyId(ids);
    }

    @Override
    public Page<EmergencyVO> pageList(Page page, EmergencyQuery query) {
        QueryWrapper<Emergency> queryWrapper = getEmergencyQueryWrapper(query);
        Page<Emergency> pageData = this.page(page, queryWrapper);

        Page<EmergencyVO> pageResult = new Page<>();
        pageResult.setCurrent(page.getCurrent());
        pageResult.setTotal(pageData.getTotal());
        pageResult.setSize(page.getSize());

        if (pageData.getTotal() > 0) {
            List<EmergencyVO> emergencyVOS = pageData.getRecords().stream().map(emergency -> {
                EmergencyVO emergencyVO = new EmergencyVO();
                BeanUtils.copyProperties(emergency, emergencyVO);
                return emergencyVO;
            }).collect(Collectors.toList());
            getFileList(emergencyVOS);
            pageResult.setRecords(emergencyVOS);
        }
        return pageResult;
    }


    /**
     * 获取附件文件列表
     *
     * @param list 列表
     * @return 文件列表
     */
    private void getFileList(List<EmergencyVO> list) {
        for (EmergencyVO record : list) {
            Set<Long> ids = new HashSet<>();
            if (record != null && !StringUtils.isEmpty(record.getAnnex())) {
                if (record.getAnnex().contains(",")) {
                    String[] split = record.getAnnex().split(",");
                    for (String s : split) {
                        ids.add(Long.parseLong(s));
                    }
                } else {
                    ids.add(Long.parseLong(record.getAnnex()));
                }
            }
            if (!CollectionUtils.isEmpty(ids)) {
                QueryWrapper<File> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("STATUS_FLAG", FlowConstant.SHORT_ZERO).in("ID", ids);
                List<File> fileList = fileService.list(queryWrapper);
                record.setFileList(fileList == null ? Collections.emptyList() : fileList);
            }
        }

    }

    /**
     * 设置查询条件
     *
     * @param query 查询参数
     * @return QueryWrapper
     */
    private QueryWrapper<Emergency> getEmergencyQueryWrapper(EmergencyQuery query) {
        QueryWrapper<Emergency> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("IS_DEL", FlowConstant.SHORT_ZERO);
        queryWrapper.orderByDesc("CREATE_TIME", "UPDATE_TIME");
        if (query != null) {
            if (!StringUtils.isEmpty(query.getEventName())) {
                queryWrapper.like("EVENT_NAME", query.getEventName());
            }
            if (!StringUtils.isEmpty(query.getEventType())) {
                queryWrapper.like("EVENT_TYPE", query.getEventType());
            }
            if (!StringUtils.isEmpty(query.getEventGrade())) {
                queryWrapper.like("EVENT_GRADE", query.getEventGrade());
            }
            if (!StringUtils.isEmpty(query.getIsAnalysis())) {
                queryWrapper.eq("IS_ANALYSIS", query.getIsAnalysis());
            }
        }
        return queryWrapper;
    }

    @Override
    public List<Emergency> all(EmergencyQuery query) {
        QueryWrapper<Emergency> addressBookQueryWrapper = getEmergencyQueryWrapper(query);
        return this.list(addressBookQueryWrapper);
    }




    @Override
    public EmergencyVO get(Long id) {
        EmergencyVO emergencyVO = new EmergencyVO();

        Emergency byId = getById(id);
        BeanUtils.copyProperties(byId, emergencyVO);

        // 获取文件列表
        emergencyVO.setFileList(getFileList(emergencyVO.getAnnex()));
        //危险源
        List<Hazard> emergencyHazards = hazardService.getListByEmergencyId(id);
        emergencyVO.setEmergencyHazards(emergencyHazards);
        //人员列表
        List<Staff> emergencyStaffs = staffService.getListByEmergencyId(id);
        emergencyVO.setEmergencyStaffs(emergencyStaffs);

        //事故设施
        List<Facilities> emergencyFacilitiesVOS = facilitiesService.getListByEmergencyId(id);
        emergencyVO.setEmergencyFacilities(emergencyFacilitiesVOS);


        return emergencyVO;
    }


    /**
     * 获取附件文件列表
     *
     * @param fileAnnexs 文件列表
     * @return 文件列表
     */
    private List<File> getFileList(String fileAnnexs) {
        Set<Long> ids = new HashSet<>();
        if (!StringUtils.isEmpty(fileAnnexs)) {
            if (fileAnnexs.contains(",")) {
                String[] split = fileAnnexs.split(",");
                for (String s : split) {
                    ids.add(Long.parseLong(s));
                }
            } else {
                ids.add(Long.parseLong(fileAnnexs));
            }
        }
        if (!CollectionUtils.isEmpty(ids)) {
            QueryWrapper<File> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("STATUS_FLAG", FlowConstant.SHORT_ZERO).in("ID", ids);
            List<File> fileList = fileService.list(queryWrapper);
            return fileList;
        }
        return null;
    }

    /**
     * 设置默认值
     *
     * @param emergencyDto 实体
     */
    private void setDefaultValue(EmergencyDTO emergencyDto) {
        emergencyDto.setIsDel(FlowConstant.SHORT_ZERO);
        emergencyDto.setCaseNumber("YJYA" + DateUtil.format(new Date(), "yyyyMMddHHmmss" + RandomUtil.randomNumbers(4)));
//        emergencyDto.setIsValid(FlowConstant.SHORT_ONE);
    }


    /**
     * 检测是否分析事件原因
     *
     * @param emergencyDTO
     */
    public void checkEventReason(EmergencyDTO emergencyDTO) {
        if (emergencyDTO.getIsAnalysis() == null || emergencyDTO.getIsAnalysis().equals(FlowConstant.SHORT_ZERO)) {
            emergencyDTO.setIsAnalysis(FlowConstant.SHORT_ZERO);
        } else if (emergencyDTO.getIsAnalysis().equals(FlowConstant.SHORT_ONE) && StringUtils.isEmpty(emergencyDTO.getEventReason())) {
            throw new RuntimeException("事件原因不能为空");
        }
    }
}
