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

import cn.hutool.core.collection.CollUtil;
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.dispatch.common.FlowConstant;
import com.tofly.dispatch.dto.HazardDTO;
import com.tofly.dispatch.dto.HazardQuery;
import com.tofly.dispatch.entity.*;
import com.tofly.dispatch.mapper.HazardMapper;
import com.tofly.dispatch.service.EmergencyHazardService;
import com.tofly.dispatch.service.FileService;
import com.tofly.dispatch.service.HazardService;
import com.tofly.dispatch.util.UploadFiles;
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.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 危险源
 *
 * @author qf
 * @date Thu Apr 21 00:00:00 CST 2022
 */
@Service("hazardService")
public class HazardServiceImpl extends ServiceImpl<HazardMapper, Hazard> implements HazardService {

    @Autowired
    private FileService fileService;
@Autowired
private EmergencyHazardService emergencyHazardService;

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

    @Autowired
    private HazardService hazardService;

    @Override
    public void insert(HazardDTO hazardDTO, List<MultipartFile> fileList) {
        setDefaultValue(hazardDTO);
        Hazard hazard = new Hazard();
        BeanUtils.copyProperties(hazardDTO, hazard);
        String fileIds = UploadFiles.saveFiles(fileService, fileList, hazardDTO.getAnnex(), hazardDTO.getAnnex(),
                filePath, "TF_DIC_HAZARD_W");
        if (!StringUtils.isEmpty(fileIds)) {
            hazard.setAnnex(fileIds);
        }
        if (!this.save(hazard)) {
            throw new RuntimeException("新增失败");
        }
    }

    /**
     * 设置默认值
     *
     * @param dto 实体
     */
    private void setDefaultValue(HazardDTO dto) {
        dto.setIsDel(FlowConstant.SHORT_ZERO);
        dto.setIsValid(FlowConstant.SHORT_ONE);
    }

    @Override
    public void edit(HazardDTO hazardDTO, List<MultipartFile> fileList) {
        Hazard hazard = new Hazard();
        BeanUtils.copyProperties(hazardDTO, hazard);
        Hazard byId = getById(hazardDTO.getId());
        String fileIds = UploadFiles.saveFiles(fileService, fileList, byId.getAnnex(), hazardDTO.getAnnex(),
                filePath, "TF_DIC_HAZARD_W");
        if (!StringUtils.isEmpty(fileIds)) {
            hazard.setAnnex(fileIds);
        }
        if (!StringUtils.isEmpty(fileIds) || (hazardDTO.getAnnex()!=null && hazardDTO.getAnnex().equals("[]"))) {
            hazardDTO.setAnnex(fileIds);
        }
        if(StringUtils.isEmpty(hazard.getReason())){
            hazard.setReason("");
        }
        if (!this.updateById(hazard)) {
            throw new RuntimeException("修改失败");
        }
    }

    @Override
    public void delete(Set<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new RuntimeException("传入数据为空");
        }
        QueryWrapper<EmergencyHazard> queryWrapper=new QueryWrapper<>();
        queryWrapper.in("HAZARD_ID",ids);
        Integer count_check = emergencyHazardService.count(queryWrapper);
        if (count_check > 0) {
            throw new RuntimeException("应急危险源在应急预案中使用，不能删除");
        }

       this.baseMapper.deleteBatchIds(ids);



    }

    @Override
    public Page<Hazard> pageList(Page page, HazardQuery query) {
        QueryWrapper<Hazard> queryWrapper = getAddressBookQueryWrapper(query);
        Page<Hazard> pageData = this.page(page, queryWrapper);
        if (pageData.getTotal() > 0) {
            getFileList(pageData.getRecords());
        }
        return pageData;
    }


    /**
     * 获取附件文件列表
     *
     * @param hazardList 危险源列表
     * @return 文件列表
     */
    private void getFileList(List<Hazard> hazardList) {
        for (Hazard record : hazardList) {
            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<Hazard> getAddressBookQueryWrapper(HazardQuery query) {
        QueryWrapper<Hazard> queryWrapper = new QueryWrapper<>();

        if (query != null) {
            if (!StringUtils.isEmpty(query.getHazardName())) {
                queryWrapper.like("HAZARD_NAME", query.getHazardName());
            }
            if (!StringUtils.isEmpty(query.getHazardType())) {
                queryWrapper.like("HAZARD_TYPE", query.getHazardType());
            }
        }

        queryWrapper.orderByDesc("CREATE_TIME");
        return queryWrapper;
    }

    @Override
    public List<Hazard> all(HazardQuery query) {
        QueryWrapper<Hazard> addressBookQueryWrapper = getAddressBookQueryWrapper(query);
        return this.list(addressBookQueryWrapper);
    }

    @Override
    public List<Hazard> getListByEmergencyId(Long emergencyId) {
        return this.baseMapper.getListByEmergencyId(emergencyId);
    }

}
