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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.xrtygis.custom.service.GetMaxIdService;
import com.tofly.xrtygis.entity.Plot;
import com.tofly.xrtygis.entity.Valveandplot;
import com.tofly.xrtygis.mapper.ValveandplotMapper;
import com.tofly.xrtygis.service.PlotService;
import com.tofly.xrtygis.service.ValveandplotService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

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

/**
 * 阀门-小区关联表
 *
 * @author admin
 * @date Thu Mar 17 00:00:00 CST 2022
 */
@Service("valveAndPlotService")
@AllArgsConstructor
public class ValveandplotServiceImpl extends ServiceImpl<ValveandplotMapper, Valveandplot> implements ValveandplotService {

    private final PlotService plotService;
    private final GetMaxIdService getMaxIdService;

    private final static String VALVE_AND_PLOT = "TF_YWPN_VALVEANDPLOT_W";

    /**
     * 绑定阀门与小区
     *
     * @param valveCode 阀门编号
     * @param plotName  小区名称
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean bindValveAndPlot(String valveCode, String plotName) {
        if (StringUtils.isEmpty(valveCode)) {
            throw new ToflyDeniedException("未选定阀门");
        }
        if (StringUtils.isEmpty(plotName)) {
            throw new ToflyDeniedException("未选定小区");
        }
        //存放填装好的存放信息
        List<Valveandplot> saveList = new ArrayList<>(10);
        //根据小区编号分组的集合
        Map<Long, List<Valveandplot>> groupByPlot = null;
        //查询所以已绑定信息
        List<Valveandplot> valveAndPlotList = this.list();

        if (!valveAndPlotList.isEmpty()) {
            groupByPlot = valveAndPlotList.stream().collect(Collectors.groupingBy(Valveandplot::getPlotId));
        }

        Plot plotSave;

        Long maxId = getMaxIdService.getMaxId(VALVE_AND_PLOT);

        for (String plotCode : plotName.split(",")) {
            //小区id
            Long plotId;

            Plot plot = plotService.getOne(Wrappers.<Plot>lambdaQuery()
                    .eq(Plot::getName, plotCode));
            //小区不存在添加后绑定
            if (plot == null) {
                plotSave = new Plot();
                plotSave.setName(plotCode);
                plotService.save(plotSave);
                plotId = plotSave.getId();
            } else {
                plotId = plot.getId();
            }

            List<String> valveList = Arrays.asList(valveCode.split(","));

            Valveandplot valveandplot;

            Long userId = SecurityUtils.getUserId();

            for (String valveId : valveList) {
                //判断管线是否重复绑定小区
                if (groupByPlot != null) {
                    if (groupByPlot.containsKey(plotId)) {
                        Set<String> mapValve = groupByPlot.get(plotId).stream()
                                .map(Valveandplot::getValveId).collect(Collectors.toSet());
                        if (!mapValve.isEmpty()) {
                            if (mapValve.contains(valveId)) {
                                Plot plotById = plotService.getById(plotId);
                                throw new ToflyDeniedException("管线编号：" + valveId + "已绑定小区：" + plotById.getName());
                            }
                        }
                    }
                }

                valveandplot = new Valveandplot();
                valveandplot.setValveId(valveId)
                        .setPlotId(plotId)
                        .setId(maxId)
                        .setCreateUser(userId);
                maxId++;
                saveList.add(valveandplot);
            }
        }

        return baseMapper.insertValveAndPlot(saveList);
    }

    /**
     * @param valveId 阀门编号
     * @param plotId  小区编号
     * @return boolean
     */
    @Override
    public boolean removeValveAndPlot(String valveId, String plotId) {

        if (!StringUtils.isEmpty(valveId) && StringUtils.isEmpty(plotId)) {
            this.remove(Wrappers.<Valveandplot>lambdaQuery().in(Valveandplot::getValveId, Arrays.asList(valveId.split(","))));
        } else {
            this.remove(Wrappers.<Valveandplot>lambdaQuery()
                    .in(Valveandplot::getValveId, valveId)
                    .in(Valveandplot::getPlotId, Arrays.asList(plotId.split(","))));
        }
        return true;
    }

    @Override
    public List<Map> valveIdGetPlot(String id) {
        List<String> idList = Arrays.asList(id.split(","));
        return baseMapper.valveIdGetPlot(idList);
    }
}
