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

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.xrtygis.custom.service.export.ExportCommonCodeService;
import com.tofly.xrtygis.entity.*;
import com.tofly.xrtygis.entity.dto.DmaTableDto;
import com.tofly.xrtygis.custom.entity.vo.DmaQueryVo;
import com.tofly.xrtygis.custom.entity.vo.QueryVo;
import com.tofly.xrtygis.custom.mapper.CustomDmaTableMapper;
import com.tofly.xrtygis.custom.service.dma.CustomDmaTableService;
import com.tofly.xrtygis.custom.util.CommonMethod;
import com.tofly.xrtygis.em.Constant;
import com.tofly.xrtygis.em.ExcelExportFileTypeEnum;
import com.tofly.xrtygis.entity.vo.DmatableVo;
import com.tofly.xrtygis.entity.vo.UserWaterMeterAnalyzeVo;
import com.tofly.xrtygis.entity.vo.UserWaterMeterInfoVo;
import com.tofly.xrtygis.mapper.DmatableMapper;
import com.tofly.xrtygis.service.*;
import com.tofly.xrtygis.strategy.ExcelStrategyContext;
import com.tofly.xrtygis.util.ExcelUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author 20126
 */
@Service
@AllArgsConstructor
public class CustomDmaTableServiceImpl implements CustomDmaTableService {

    private final static String DMA_OBSER = "TF_YWPN_DMAANDOBSER_W";
    private final static String DMA_FLOW_VIEW = "TF_YWPN_DMATABLEFLOW_W_VIEW";
    private final static String DMA_STAITEM = "TF_YWPN_DMATABLEANDSTAITEM_W";

    private final DmatableService dmatableService;
    private final DmaandobserService dmaandobserService;
    private final DmatableandstaitemService dmatableandstaitemService;
    private final CustomDmaTableMapper customDmaTableMapper;
    private final ScadastaitemService scadastaitemService;
    private final ExcelStrategyContext excelStrategyContext;
    private final DmatablechangeService dmatablechangeService;
    private final ExportCommonCodeService exportCommonCodeService;
    private final DmatableMapper dmatableMapper;
    private final TfIndexAllocationService indexAllocationService;


    /**
     * 添加表信息
     *
     * @param dmatable 区域表管理信息表
     * @return boolean
     */
    @Override
    public boolean insertTableInfo(Dmatable dmatable) {
        if (dmatable == null){
            throw new ToflyDeniedException("传入数据为空");
        }
//        if (null == dmatable.getSch() || "".equals(dmatable.getSch())) {
//            throw new ToflyDeniedException("表号不能为空");
//        }
//        if (null == dmatable.getPhenotype() || "".equals(dmatable.getPhenotype())) {
//            throw new ToflyDeniedException("表型号不能为空");
//        }
//        if (null == dmatable.getSchName() || "".equals(dmatable.getSchName())) {
//            throw new ToflyDeniedException("表名不能为空");
//        }
        if (null == dmatable.getBore() || "".equals(dmatable.getBore())) {
            throw new ToflyDeniedException("口径不能为空");
        }
//        if (dmatable.getSchCode() != null){
//            List<Dmatable> list = dmatableService.list(Wrappers.<Dmatable>lambdaQuery().eq(Dmatable::getSchCode, dmatable.getSchCode()));
//            if (list != null && list.size() > 0){
//                throw new ToflyDeniedException("表编号" + dmatable.getSchCode() +"已存在");
//            }
//        }
        return dmatableService.save(dmatable);
    }

    /**
     * 修改表信息
     *
     * @param dmatable 区域表管理信息表
     * @return boolean
     */
    @Override
    public boolean updateTableInfo(Dmatable dmatable) {
//        if (dmatable.getSchCode() != null){
//            List<Dmatable> list = dmatableService.list(Wrappers.<Dmatable>lambdaQuery()
//                    .eq(Dmatable::getSchCode, dmatable.getSchCode())
//                    .ne(Dmatable::getId,dmatable.getId()));
//            if (list != null && list.size() > 0){
//                throw new ToflyDeniedException("表编号" + dmatable.getSchCode() +"已存在");
//            }
//        }
        return dmatableService.updateById(dmatable);
    }

    /**
     * 删除表信息
     *
     * @param ids id
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteTableInfo(String ids) {
        List<String> split = Arrays.asList(ids.split(","));

        List<String> msg = new ArrayList<>();

        for (String id : split) {
            Dmatable tableInfo = dmatableService.getById(id);
            if (null == tableInfo) {
                continue;
            }
            List<Map> obser = customDmaTableMapper.useOrNot(DMA_OBSER, id);
            List<Map> flow = customDmaTableMapper.useOrNot(DMA_FLOW_VIEW, id);
            List<Map> staitem = customDmaTableMapper.useOrNot(DMA_STAITEM, id);
//            if (!obser.isEmpty() || !flow.isEmpty() || !staitem.isEmpty()) {
//                msg.add(tableInfo.getSchName());
//
//            }
        }
        String message = msg.toString();
        if (msg.size() > 0) {
            throw new ToflyDeniedException("配置表：" + message.substring(1, message.lastIndexOf("]")) + " 正在使用中，无法删除");
        }
        return dmatableService.removeByIds(split);
    }

    /**
     * 查看表信息
     *
     * @return boolean
     */
    @Override
    public Page selectTableInfo(Page page, Long id, String dto) {
        return customDmaTableMapper.fuzzyQuery(page, id, dto);
    }


    /**
     * 查询指标信息
     *
     * @param stationId 站点id
     * @return list
     */
    @Override
    public List viewIndex(Long stationId) {

        return scadastaitemService.list(Wrappers.<Scadastaitem>lambdaQuery()
                .eq(Scadastaitem::getStationId, stationId)
                .in(Scadastaitem::getTycd, 1, 2)
                .select(Scadastaitem::getItnm, Scadastaitem::getId));
    }

    /**
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean bindIndex(Long tableId, Long itid, String itype) {

        Dmatableandstaitem staitem = dmatableandstaitemService.getOne(Wrappers.<Dmatableandstaitem>lambdaQuery()
                .eq(Dmatableandstaitem::getTableId, tableId)
                .eq(Dmatableandstaitem::getItype, itype));

        if (null != staitem) {
            throw new ToflyDeniedException("该指标已被绑定");
        }
        return customDmaTableMapper.insertBindTable(tableId, itid, itype);
    }

    /**
     * 解绑指标
     *
     * @param itid 表id
     * @return boolean
     */
    @Override
    public boolean untieIndex(String itid) {
        return dmatableandstaitemService.removeByIds(Arrays.asList(itid.split(",")));
    }

    /**
     * 获取绑定表信息
     *
     * @param page page
     * @param id   配置表id
     * @return page
     */
    @Override
    public Page getBindTableInfo(Page page, Long id) {
        return customDmaTableMapper.getBindTableInfo(page, id);
    }

    /**
     * 数据导出
     *
     * @param response response
     * @return true
     */
    @Override
    public void exportTableInfo(HttpServletResponse response, Page page, DmaTableDto dmaTableDto) {
       exportCommonCodeService.exportCode(response, "exportFlowRecordService", dmatableMapper.getDmatablePage(page, dmaTableDto).getRecords());
    }

    /**
     * 查询旧表信息
     *
     * @param id 表id
     * @return list
     */
    @Override
    public List<Map> oldTableData(Long id) {
        return customDmaTableMapper.oldTableData(id);
    }

    /**
     * 查询旧表历史流量
     *
     * @param id 表id
     * @return list
     */
    @Override
    public List<Map> historicalTraffic(Long id, String start, String end) {
        return customDmaTableMapper.historicalTraffic(id, start, end);
    }

    /**
     * 获取平均流量
     *
     * @param id    表id
     * @param start 开始时间
     * @param end   结束时间
     * @return double
     */
    @Override
    public Double avgFlow(Long id, String start, String end) {
        return customDmaTableMapper.avgFlow(id, start, end);
    }

    /**
     * 区域表换表
     *
     * @param dma 区域表更换记录信息表
     * @return true
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changeTable(Dmatablechange dma) {
        if (null == dma) {
            throw new ToflyDeniedException("传入数据不能为空");
        }

        if (dma.getTableId() == null) {
            throw new ToflyDeniedException("表id不能为空");
        }

        if (null == dma.getNewBore() || null == dma.getNewPhenotype() || null == dma.getNewFactory() || null == dma.getNewSch()) {
            throw new ToflyDeniedException("信息填报不完整");
        }

        if (dma.getOldStart() != null && dma.getOldEnd() != null && dma.getNewStart() != null && dma.getNewEnd() != null) {
            if (dma.getOldStart() > dma.getOldEnd()) {
                throw new ToflyDeniedException("旧表终止读数只能大于等于旧表起始读数");
            }

            if (dma.getNewStart() > dma.getNewEnd()) {
                throw new ToflyDeniedException("新表终止读数只能大于等于新表起始读数");
            }

            Double gsl = CommonMethod.add(CommonMethod.add(CommonMethod.subtract(dma.getOldEnd(), dma.getOldStart()), CommonMethod.subtract(dma.getNewEnd(), dma.getNewStart())), dma.getReckon());

            double v = Double.parseDouble(String.format("%.1f", gsl));

            dma.setGsl(v);
        }
        dmatablechangeService.save(dma);

        return dmatableService.update(Wrappers.<Dmatable>lambdaUpdate()
                .eq(Dmatable::getId, dma.getTableId())
                .set(Dmatable::getBore, dma.getNewBore()));
//                .set(Dmatable::getPhenotype, dma.getNewPhenotype())
//                .set(Dmatable::getFactory, dma.getNewFactory())
//                .set(Dmatable::getSch, dma.getNewSch()));
    }

    @Override
    public Page<Dmatable> viewFlowMeter(Page page, DmaTableDto dmaTableDto) {
        return dmatableMapper.getDmatablePage(page, dmaTableDto);
    }
    @Override
    public List<Dmatable> getDmatableList(DmaTableDto dmaTableDto){
        return dmatableMapper.getDmatablePage(dmaTableDto);
    }

    @Override
    public List<TfIndexAllocation> viewFlowIndexById(Long id) {
        return indexAllocationService.list(new QueryWrapper<TfIndexAllocation>()
                .eq("DEVICE_ID",id));
    }

//    @Override
//    public DmaQueryVo getDmaTree() {
//        //查询父分区列表
//        List<QueryVo> mainDmaList = customDmaTableMapper.getAllMainDma();
//        DmaQueryVo dmaQueryVo = new DmaQueryVo();
//        dmaQueryVo.setQueryVoList(getDmaChild(mainDmaList));
//        dmaQueryVo.setDmaCountList(customDmaTableMapper.getDmaAllLevelCount());
//        return dmaQueryVo;
//    }
//
//    /**
//     * 递归子分区
//     * @param dmaList 分区列表
//     * @return
//     */
//    public List<QueryVo> getDmaChild(List<QueryVo> dmaList) {
//        for(QueryVo dma:dmaList){
//            List<QueryVo> dmaChildList = customDmaTableMapper.getDmaChild(Long.parseLong(dma.getId()));
//            if(CollectionUtils.isNotEmpty(dmaChildList)){
//                dma.setChildren(getDmaChild(dmaChildList));
//            }
//            dma.setViewId((dma.getLabel() + "_" + dma.getId()));
//        }
//        return dmaList;
//    }
    @Override
    public Page<UserWaterMeterInfoVo> getUserWaterMeterInfo(Page page, String likeStr){
       return dmatableMapper.getUserWaterMeterInfoVoPage(page,likeStr);
    }
    @Override
    public List<UserWaterMeterInfoVo> getUserWaterMeterInfo(String likeStr){
        return dmatableMapper.getUserWaterMeterInfoVoPage(likeStr);
    }

    @Override
    public List<UserWaterMeterAnalyzeVo> getUserWaterMeterAnalyze(String userCode,String waterMeterCode,Date startTime, Date endTime) {
        List<UserWaterMeterAnalyzeVo> userWaterMeterAnalyze = dmatableMapper.getUserWaterMeterAnalyze(userCode, waterMeterCode, startTime, endTime);
        if(null!=userWaterMeterAnalyze && userWaterMeterAnalyze.size()>0){
            return userWaterMeterAnalyze;
        }else {
            return new ArrayList<>();
        }

    }

}
