package com.tofly.xrtygis.custom.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.ftp.config.FtpUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.xrtygis.config.FilePathBean;
import com.tofly.xrtygis.custom.entity.dto.PollInfo;
import com.tofly.xrtygis.custom.mapper.CustomPollSourceMapper;
import com.tofly.xrtygis.custom.service.CustomPollSourceService;
import com.tofly.xrtygis.custom.service.GetMaxIdService;
import com.tofly.xrtygis.custom.util.service.FileInfoService;
import com.tofly.xrtygis.em.Constant;
import com.tofly.xrtygis.entity.File;
import com.tofly.xrtygis.entity.Poll;
import com.tofly.xrtygis.entity.Pollsource;
import com.tofly.xrtygis.entity.Warn;
import com.tofly.xrtygis.service.FileService;
import com.tofly.xrtygis.service.PollService;
import com.tofly.xrtygis.service.PollsourceService;
import com.tofly.xrtygis.service.WarnService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 20126
 */
@Service
@AllArgsConstructor
public class CustomPollSourceServiceImpl implements CustomPollSourceService {

    private final static String TABLE_NAME = "TF_YWPN_POLLSOURCE_W";
    private final static String WARNHISTORY = "TF_YWPN_WARNHISTORY_W_";
    private final static String WARN_HISTORY_VIEW = "TF_YWPN_WARNHISTORY_W_VIEW";

    private final FileInfoService fileInfoService;
    private final FilePathBean filePathBean;
    private final FileService fileService;
    private final PollsourceService pollsourceService;
    private final WarnService warnService;
    private final CustomPollSourceMapper customPollSourceMapper;
    private final GetMaxIdService getMaxIdService;
    private final PollService pollService;

    /**
     * 开启报警
     *
     * @param fileList 上传文件
     * @param poll     污染源信息
     * @return true of false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean turnOnTheAlarm(List<MultipartFile> fileList, Pollsource poll, String dto) {

        if (null == poll.getLttd() || null == poll.getLgtd()) {
            throw new ToflyDeniedException("坐标不能为空");
        }
        if (fileList != null && fileList.size() > 0) {
            StringBuilder fileIds = fileInfoService.saveFileList(fileList, filePathBean.getPollSourceFile(), TABLE_NAME);
            poll.setFileids(fileIds.toString());
        }
        pollsourceService.save(poll);

        if (!dto.isEmpty()) {
            List<PollInfo> pollInfos = JSONObject.parseArray(dto, PollInfo.class);
            if (!pollInfos.isEmpty()) {
                Poll poll1 = new Poll();
                pollInfos.forEach(info -> {
                    poll1.setPollute(info.getPollute());
                    poll1.setSourceId(poll.getId());
                    poll1.setPotency(info.getPotency());

                    pollService.save(poll1);
                });
            }
        }

        if ("1".equals(poll.getIswarn())) {
            //对应报警历史表表名
            String tableName = WARNHISTORY + Date8Util.getYearMonth();

            List<String> exist = customPollSourceMapper.doesItExistTable(tableName);

            Long maxId = getMaxIdService.getMaxId(WARN_HISTORY_VIEW);

            Warn warn = new Warn();

            warn.setItcd(poll.getId().toString());
            warn.setAddress(poll.getAddress());
            warn.setWarnType(Constant.POLL_TYPE);
            warn.setScadaTime(new Date());
            warn.setNotes("河道水质污染源报警");
            warn.setIsconfirm("0");
            warn.setIsclear("0");
            warn.setIsloc("1");
            warn.setId(maxId);
            customPollSourceMapper.insertWarn(warn);

            if (!exist.isEmpty()) {
                //添加到历史表
                customPollSourceMapper.insertWarnHistory(tableName, warn.getId(), maxId);
            }
        }
        return true;
    }

    /**
     * 删除污染源
     *
     * @return true
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePoll(String ids) {
        List<String> idarr = Arrays.asList(ids.split(","));
        if (idarr.size() > 0) {
            for (String id : idarr) {
                Pollsource poll = pollsourceService.getById(id);
                if (null != poll.getFileids()) {
                    String[] split = poll.getFileids().split(",");
                    for (String fileId : split) {
                        File file = fileService.getById(fileId);
                        if (!FtpUtil.deleteFile(file.getFilePath())) {
                            throw new ToflyDeniedException("文件未删除成功");
                        }
                    }
                }
            }
            return pollsourceService.removeByIds(idarr);
        } else {
            return false;
        }
    }

    /**
     * 获取文件路径
     *
     * @param id 污染源id
     * @return list
     */
    @Override
    public List<String> getFilePath(Long id) {

        Pollsource pollsource = pollsourceService.getById(id);
        if (null != pollsource) {
            List<String> fileIdList = Arrays.asList(pollsource.getFileids().split(","));
            return fileService.list(Wrappers.<File>lambdaQuery()
                    .select(File::getFilePath)
                    .in(File::getFilePath, fileIdList))
                    .stream().map(File::getFilePath).collect(Collectors.toList());
        } else {
            return null;
        }
    }

    /**
     * 获取污染源信息
     *
     * @param page    page
     * @param address 地址
     * @return page
     */
    @Override
    public Page viewPollSource(Page page, String address, String iswarn) {
        return pollsourceService.page(page, Wrappers.<Pollsource>lambdaQuery()
                .eq(Pollsource::getCreateUser, SecurityUtils.getUserId())
                .like(address != null, Pollsource::getAddress, address)
                .like(iswarn != null, Pollsource::getIswarn, iswarn)
                .orderByDesc(Pollsource::getUpdateTime));
    }

    /**
     * 获取详细信息
     *
     * @param id 污染源id
     * @return map
     */
    @Override
    public Pollsource getInfo(Long id) {
        Pollsource pollsource = pollsourceService.getById(id);
        if (null != pollsource.getFileids()) {
            List<String> fileids = Arrays.asList(pollsource.getFileids().split(","));
            List<String> collect = fileService.list(Wrappers.<File>lambdaQuery()
                    .in(File::getId, fileids)
                    .select(File::getFilePath))
                    .stream().map(File::getFilePath).collect(Collectors.toList());

            pollsource.setFilePaths(collect);
        }
        return pollsource;
    }

    /**
     * 关闭报警
     *
     * @param ids 污染源id
     * @return true
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean closeWarn(String ids) {
        String[] split = ids.split(",");
        if (split.length > 0) {
            for (String id : split) {

                Pollsource poll = pollsourceService.getById(id);

                if (null == poll) {
                    throw new ToflyDeniedException("未查询到相关污染源信息，请刷新重试");
                }

                boolean update = pollsourceService.update(Wrappers.<Pollsource>lambdaUpdate()
                        .eq(Pollsource::getId, id)
                        .set(Pollsource::getIswarn, "0")
                        .set(Pollsource::getUpdateTime, new Date())
                        .set(Pollsource::getUpdateUser, SecurityUtils.getUserId()));
                //关闭污染源消息的报警
                if (update) {
                    Warn warn = warnService.getOne(Wrappers.<Warn>lambdaQuery()
                            .eq(Warn::getItcd, id).select(Warn::getId));

                    if (null == warn) {
                        ResultRespone.failed("网页端已进行处理");
                        return true;
                    }

                    String table = WARNHISTORY + DateUtil.getDateFormat(poll.getCreateTime(), "yyyyMM");

                    if (!customPollSourceMapper.doesItExistTable(table).isEmpty()) {
                        customPollSourceMapper.closeWarnHistory(table, id);
                    }

                    //删除实时表消息
                    warnService.remove(Wrappers.<Warn>lambdaQuery().eq(Warn::getId, warn.getId()));

                } else {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 获取全部上报信息
     *
     * @param page    page
     * @param address 模糊查询条件
     * @param iswarn  是否报警
     * @return page
     */
    @Override
    public Page getAllPollSource(Page page, String address, String iswarn, String start, String end, String pollIds) {

        Date sta = null;
        Date en = null;
        if (start != null && !"".equals(start) && end != null && !"".equals(end)) {
            sta = DateUtil.formatDate(start, "yyyy-MM-dd HH:mm:ss");
            en = DateUtil.formatDate(end, "yyyy-MM-dd HH:mm:ss");
        }

        List source = null;
        if (pollIds != null) {
            List<Poll> list = pollService.list(Wrappers.<Poll>lambdaQuery()
                    .in(Poll::getPollute, Arrays.asList(pollIds.split(",")))
                    .select(Poll::getSourceId));
            if (list != null && list.size() >= 1){
                source = list.stream().map(Poll::getSourceId).collect(Collectors.toList());
            }
        }


        return pollsourceService.page(page, Wrappers.<Pollsource>lambdaQuery()
                .in(source != null, Pollsource::getId,source)
                .like(address != null, Pollsource::getAddress, address)
                .eq(iswarn != null, Pollsource::getIswarn, iswarn)
                .between(sta != null && en != null, Pollsource::getCreateTime, sta, en)
                .orderByDesc(Pollsource::getCreateTime));
    }

    @Override
    public List<Map> getpollUte() {
        return customPollSourceMapper.getPollUte();
    }


}
