package com.yeejoin.amos.supervision.business.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.module.common.api.excel.DataSources;
import com.yeejoin.amos.boot.module.common.api.excel.ExcelUtil;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.supervision.business.dao.mapper.HiddenDangerMapper;
import com.yeejoin.amos.supervision.business.dao.repository.IHiddenDangerDao;
import com.yeejoin.amos.supervision.business.dto.HiddenDangerDto;
import com.yeejoin.amos.supervision.business.dto.HiddenDangerExportDto;
import com.yeejoin.amos.supervision.business.dto.HiddenDangerImportDto;
import com.yeejoin.amos.supervision.business.feign.DangerFeignClient;
import com.yeejoin.amos.supervision.business.service.intfc.IHiddenDangerService;
import com.yeejoin.amos.supervision.core.common.dto.DangerDto;
import com.yeejoin.amos.supervision.dao.entity.HiddenDanger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.restful.exception.instance.DataNotFound;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author DELL
 */
@Service
public class HiddenDangerServiceImpl implements IHiddenDangerService {

    @Autowired
    DangerFeignClient feignClient;

    @Autowired
    IHiddenDangerDao iHiddenDangerDao;

    @Autowired
    HiddenDangerMapper hiddenDangerMapper;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    Sequence sequence;

    @Autowired
    DataSources dataSources;

    @Override
    public List<HiddenDangerExportDto> listAll(String planId, Long pointId, String level, String status) {
        //1.查询指定计划和公司的关联隐患数据
        List<HiddenDangerDto> hiddenDangers = hiddenDangerMapper.listByCondition(planId, pointId);
        List<Long> dangerIds = Lists.transform(hiddenDangers, HiddenDangerDto::getLatentDangerId);
        String dangerIdsStr = Joiner.on(",").join(dangerIds);
        //2.调用隐患模块查询关联隐患的具体数据（业务系统直落关系，具体隐患数据再隐患服务进行储存）
        FeignClientResult<List<DangerDto>> daResult = feignClient.listAll(dangerIdsStr, level, status);
        List<DangerDto> allData = daResult.getResult();
        Map<Long, HiddenDangerDto> keyMap = hiddenDangers.stream().collect(Collectors.toMap(HiddenDangerDto::getLatentDangerId, Function.identity()));
        //3.将查询会来的数据与业务数据拼接，进行返回
        return allData.stream().map(s -> {
            HiddenDangerExportDto exportDto = new HiddenDangerExportDto();
            Bean.copyExistPropertis(s, exportDto);
            HiddenDangerDto hiddenDangerDto = keyMap.get(s.getId());
            exportDto.setCheckTime(hiddenDangerDto != null ? hiddenDangerDto.getCheckTime() : "");
            exportDto.setCheckUserName(hiddenDangerDto != null ? hiddenDangerDto.getCheckUserName() : "");
            exportDto.setPointName(hiddenDangerDto != null ? hiddenDangerDto.getPointName() : "");
            exportDto.setInputItemName(hiddenDangerDto != null ? hiddenDangerDto.getInputItemName() : "");
            return exportDto;
        }).collect(Collectors.toList());
    }

    @Override
    public DangerDto getOne(Long latentDangerId) {
        HiddenDanger hiddenDanger = iHiddenDangerDao.findByLatentDangerId(latentDangerId);
        if (hiddenDanger == null) {
            throw new DataNotFound("该隐患数据不存在");
        }
        FeignClientResult<DangerDto> feignClientResult = feignClient.getOne(latentDangerId);
        return feignClientResult.getResult();
    }

    @Override
    public DangerDto updateDanger(Long latentDangerId, DangerDto dangerDto) {
        HiddenDanger hiddenDanger = iHiddenDangerDao.findByLatentDangerId(latentDangerId);
        if (hiddenDanger == null) {
            throw new DataNotFound("该隐患数据不存在");
        }
        FeignClientResult<List<DangerDto>> feignClientResult = feignClient.saveOrUpdateBatch(Collections.singletonList(dangerDto));
        List<DangerDto> saveDangers = feignClientResult.getResult();
        if (!saveDangers.isEmpty()) {
            hiddenDanger.setUpdateDate(new Date());
            iHiddenDangerDao.save(hiddenDanger);
            return saveDangers.get(0);
        } else {
            throw new RuntimeException("更新失败");
        }
    }

    @Override
    public IPage pageList(Page page, String planId, Long pointId, String level, String status) {
        List<HiddenDangerDto> dangers = hiddenDangerMapper.listByCondition(planId, pointId);
        List<Long> dangerIds = Lists.transform(dangers, HiddenDangerDto::getLatentDangerId);
        String dangerIdsStr = Joiner.on(",").join(dangerIds);
        FeignClientResult<IPage<DangerDto>> feignClientResult = feignClient.pageList(page, dangerIdsStr, level, status);
        IPage<DangerDto> dangerDtoIPage = feignClientResult.getResult();
        Map<Long, HiddenDangerDto> keyMap = dangers.stream().collect(Collectors.toMap(HiddenDangerDto::getLatentDangerId, Function.identity()));
        dangerDtoIPage.getRecords().forEach(r -> {
            HiddenDangerDto hiddenDangerDto = keyMap.get(r.getId());
            r.setCheckTime(hiddenDangerDto != null ? hiddenDangerDto.getCheckTime() : "");
            r.setCheckUserName(hiddenDangerDto != null ? hiddenDangerDto.getCheckUserName() : "");
            r.setPointName(hiddenDangerDto != null ? hiddenDangerDto.getPointName() : "");
            r.setInputItemName(hiddenDangerDto != null ? hiddenDangerDto.getInputItemName() : "");
        });
        return dangerDtoIPage;
    }

    @Override
    public void importDanger(Long planId, List<HiddenDangerImportDto> list) {
        //1.调用创建隐患
        List<DangerDto> dtoList = list.stream().map(s -> {
            String[] dangerArray = s.getDangerLevelName().split("@");
            String[] reformTypeArray = s.getReformTypeName().split("@");
            DangerDto dangerDto = new DangerDto();
            Bean.copyExistPropertis(s, dangerDto);
            dangerDto.setBizType(contextPath);
            dangerDto.setBizId(sequence.nextId());
            dangerDto.setDangerLevel(dangerArray.length > 1 ? dangerArray[1] : "");
            dangerDto.setDangerLevelName(dangerArray.length > 1 ? dangerArray[0] : "");
            dangerDto.setReformType(reformTypeArray.length > 1 ? reformTypeArray[1] : "");
            dangerDto.setReformTypeName(reformTypeArray.length > 1 ? reformTypeArray[0] : "");
            //自行检查
            dangerDto.setCheckMode("1");
            return dangerDto;
        }).collect(Collectors.toList());
        FeignClientResult<List<DangerDto>> feignClientResult = feignClient.saveOrUpdateBatch(dtoList);
        List<DangerDto> dangerDbs = feignClientResult.getResult();
        //2.保存隐患关系表
        List<HiddenDanger> hiddenDangers = dangerDbs.stream().map(d -> {
            HiddenDanger hiddenDanger = new HiddenDanger();
            hiddenDanger.setCreateBy(RequestContext.getExeUserId());
            hiddenDanger.setPlanId(planId);
            hiddenDanger.setLatentDangerId(d.getId());
            hiddenDanger.setCheckInputId(d.getBizId());
            hiddenDanger.setDangerType("1");
            hiddenDanger.setDangerTypeName("自行检查");
            hiddenDanger.setCreateDate(new Date());
            return hiddenDanger;
        }).collect(Collectors.toList());
        for (int i = 0; i <= hiddenDangers.size(); i++) {
            String[] pointArray = list.get(i).getPointName().split("@");
            hiddenDangers.get(i).setPointId(pointArray.length > 1 ? Long.parseLong(pointArray[1]) : null);
        }
        iHiddenDangerDao.saveAll(hiddenDangers);
    }

    @Override
    public void templateExport(HttpServletResponse response) {
        ExcelUtil.createTemplate(response, "隐患清单", "隐患清单", null, HiddenDangerExportDto.class, dataSources, true);
    }
}
