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

import com.alibaba.fastjson.JSONArray;
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.util.Date8Util;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.watermeter.custom.entity.marketing.*;
import com.tofly.watermeter.custom.service.CustomWaterGisService;
import com.tofly.watermeter.custom.util.Date7Utils;
import com.tofly.watermeter.entity.Bwrksbdatail;
import com.tofly.watermeter.entity.Valvelinktable;
import com.tofly.watermeter.entity.Watermeter;
import com.tofly.watermeter.mapper.BwrksbdatailMapper;
import com.tofly.watermeter.mapper.QfcbqfmxMapper;
import com.tofly.watermeter.service.BwrksbdatailService;
import com.tofly.watermeter.service.ValvelinktableService;
import com.tofly.watermeter.service.WatermeterService;
import com.tofly.watermeter.util.CallAPIUtil;
import com.tofly.watermeter.util.service.CallAPIService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * @author 陈浩
 * @date 2021/4/9
 */
@Service
@AllArgsConstructor
public class CustomWaterGisServiceImpl implements CustomWaterGisService {

    private final ValvelinktableService valvelinktableService;

    private final WatermeterService watermeterService;

    private final BwrksbdatailService bwrksbdatailService;

    private final BwrksbdatailMapper bwrksbdatailMapper;

    private final QfcbqfmxMapper qfcbqfmxMapper;

    private final CallAPIService callAPIService;

    /**
     * 水表关联查询
     */
    @Override
    public Page viewWater(Page page, String khbh, String yhxm, String yhdz) {
        CustomerDto dto = new CustomerDto();
        dto.setYHBH(khbh);
        dto.setYHXM(yhxm);
        dto.setYHDZ(yhdz);
        dto.setACTION("query");

        Map map = new HashMap(4);

        try {
            map = CallAPIUtil.callAPIUtil(dto, "api/Business/GetCustomerData");
        } catch ( Exception e ) {
            e.printStackTrace();
        }

        if (map.get("data") == null) {
            return null;
        }
        List<CustomerInfo> customerInfos = JSONArray.parseArray(map.get("data").toString(), CustomerInfo.class);

        if (!customerInfos.isEmpty()) {
            for (CustomerInfo customerInfo : customerInfos) {
                if (null == customerInfo.getSBBH()) {
                    continue;
                }
                Watermeter watermeter = watermeterService.getOne(Wrappers.<Watermeter>lambdaQuery()
                        .eq(Watermeter::getSid, customerInfo.getSBBH()));
                if (watermeter != null && null != watermeter.getX() && null != watermeter.getY()) {
                    customerInfo.setX(watermeter.getX());
                    customerInfo.setY(watermeter.getY());
                }
            }
            return listToPage(page, customerInfos);
        } else {
            return null;
        }
    }

    /**
     * 用水监控
     *
     * @param page pang
     * @param code 客户编号/姓名/地址
     * @return page
     */
    @Override
    public Page waterMonitoring(Page page, String code) {
        return qfcbqfmxMapper.getCustomerInfo(page, code);
    }

    /**
     * 停水区域查询
     *
     * @param page    page
     * @param valveId 阀门id
     * @return page
     */
    @Override
    public Page viewWaterCut(Page page, String valveId) {

        if (valveId == null || "".equals(valveId)) {
            throw new ToflyDeniedException("请传入阀门");
        }

        List<String> valveIdList = Arrays.asList(valveId.split(","));

        //查出对应水表编号
        List<Valvelinktable> list = valvelinktableService.list(Wrappers.<Valvelinktable>lambdaQuery()
                .in(Valvelinktable::getValveId, valveIdList));

        if (list.isEmpty()) {
            throw new ToflyDeniedException("未找到相对应关联水表");
        }

        List<CustomerInfo> pageLists = new ArrayList<>();

        for (Valvelinktable table : list) {
            Bwrksbdatail tail = bwrksbdatailService.getById(table.getTableId());

            if (null != tail) {
                Watermeter watermeter = watermeterService.getOne(Wrappers.<Watermeter>lambdaQuery()
                        .eq(Watermeter::getSid, tail.getBwSbbh()));

                WaterClient client = new WaterClient();
                client.setCBPQ(tail.getBwGspq());
                client.setYHBH(tail.getBwKhbh());
                client.setACTION("query");
                Map customerData = new HashMap();
                try {
                    customerData = CallAPIUtil.callAPIUtil(client, "api/Business/GetCustomerData");
                } catch ( Exception e ) {
                    e.printStackTrace();
                }

                //取出查询数据
                CustomerInfo info = JSONObject.parseObject(customerData.get("data").toString(), CustomerInfo.class);
                info.setGLBH(table.getValveId());

                if (null != watermeter) {
                    //查询出水表信息采集数据不为空设置xy坐标
                    info.setX(watermeter.getX());
                    info.setY(watermeter.getY());
                }
                pageLists.add(info);
            }
        }
        return listToPage(page, pageLists);
    }

    /**
     * 客户用水量查询
     *
     * @param khbh 客户编号
     * @return map
     */
    @Override
    public Page viewUseWater(Page page, String khbh) {

        List<String> sbbhList = bwrksbdatailService.list(Wrappers.<Bwrksbdatail>lambdaQuery()
                        .like(Bwrksbdatail::getBwKhbh, khbh))
                .stream()
                .map(Bwrksbdatail::getBwSbbh).collect(Collectors.toList());

        if (sbbhList.isEmpty()) {
            throw new ToflyDeniedException("未查询到相关信息");
        }

        List<Map> pagelist = new ArrayList<>();

        Map<String, Object> result = new HashMap();
        for (String sbbh : sbbhList) {

            Watermeter watermeter = watermeterService.getOne(Wrappers.<Watermeter>lambdaQuery()
                    .eq(Watermeter::getSid, sbbh));

            //为查询条件设置值
            WaterVolume waterVolume = new WaterVolume();
            waterVolume.setSBBH(sbbh);
            waterVolume.setCWYF_START("200001");
            waterVolume.setCWYF_START(Date8Util.getYearMonth());
            waterVolume.setACTION("query");

            Map customerWater = new HashMap(5);
            try {
                customerWater = CallAPIUtil.callAPIUtil(waterVolume, "api/Business/GetCustomerWater");
            } catch ( Exception e ) {
                e.printStackTrace();
            }
            if (customerWater.size() > 0 && null != customerWater.get("data")) {
                List<CustomerUseWater> useWaters = JSONObject.parseArray(customerWater.get("data").toString(), CustomerUseWater.class);
                result.put("useWaters", useWaters);
                if (null != watermeter) {
                    result.put("X", watermeter.getX());
                    result.put("Y", watermeter.getY());
                } else {
                    result.put("X", null);
                    result.put("Y", null);
                }
                pagelist.add(result);
            }
        }
        return listToPage(page, pagelist);
    }

    /**
     * 用水监控查看所有用户用水量
     *
     * @param page page
     * @return page
     */
    @Override
    public Page waterMonitoring(Page page) {

        List<String> sbbhList = bwrksbdatailService.list(Wrappers.<Bwrksbdatail>lambdaQuery()
                        .isNotNull(Bwrksbdatail::getBwKhbh)
                        .select(Bwrksbdatail::getBwSbbh))
                .stream()
                .map(Bwrksbdatail::getBwSbbh)
                .distinct()
                .collect(Collectors.toList());

        List<CustomerUseWater> useWaters;

        Page resultPage = null;

        if (!sbbhList.isEmpty()) {

            String sbbhStr = sbbhList.toString();

            WaterVolume volume = new WaterVolume();
            volume.setACTION("query");
            volume.setSBBH(sbbhStr.substring(1, sbbhStr.lastIndexOf("]")));
            volume.setCWYF_START(DateUtil.getDateFormat(Date7Utils.addNextPeriod(-1, new Date()), "yyyyMM"));
            volume.setCWYF_END(Date8Util.getYearMonth());

            Map map = new HashMap(5);

            try {
                map = CallAPIUtil.callAPIUtil(volume, "api/Business/GetCustomerWater");
            } catch ( Exception e ) {
                e.printStackTrace();
            }
            if (map.size() > 0 && map.get("data") != null) {
                useWaters = JSONObject.parseArray(map.get("data").toString(), CustomerUseWater.class);
                if (useWaters != null && useWaters.size() > 0) {
                    resultPage = listToPage(page, useWaters);
                }
            }
        }
        return resultPage;
    }

    /**
     * 用户用水历史
     *
     * @param page      page
     * @param yhbh      用户编号
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return page
     */
    @Override
    public Page useWaterHistory(Page page, String yhbh, String startTime, String endTime) {

        if (yhbh == null) {
            throw new ToflyDeniedException("用户编号不允许为空");
        }
        if (startTime == null || endTime == null) {
            throw new ToflyDeniedException("时间不允许为空");
        }

        Page resultPage = new Page();

        CustomerDto dto = new CustomerDto();
        dto.setYHBH(yhbh);
        dto.setACTION("query");

        Map map = null;
        try {
            map = CallAPIUtil.callAPIUtil(dto, "/api/Business/GetCustomerData");
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        if (map != null && map.size() > 0 && map.get("data") != null) {
            List<CustomerInfo> customerInfos = JSONArray.parseArray(map.get("data").toString(), CustomerInfo.class);
            if (customerInfos != null && customerInfos.size() > 0) {
                for (CustomerInfo customerInfo : customerInfos) {

                    if (customerInfo.getSBBH() != null && !"0".equals(customerInfo.getSBBH())) {

                        WaterHistory history = new WaterHistory();
                        history.setSBBH(customerInfo.getSBBH());
                        history.setACTION("query");
                        history.setCWYF_START(startTime);
                        history.setCWYF_END(endTime);

                        Map resultMap = null;

                        try {
                            resultMap = CallAPIUtil.callAPIUtil(history, "/api/Business/GetCustomerWater");
                        } catch ( Exception e ) {
                            e.printStackTrace();
                        }
                        if (resultMap != null && resultMap.size() > 0 && resultMap.get("data") != null) {
                            List<CustomerWater> data = JSONObject.parseArray(resultMap.get("data").toString(), CustomerWater.class);

                            if (data != null && data.size() > 0) {
//                                data.removeIf(customerWater -> !customerWater.getYHBH().equals(customerInfo.getYHBH()));
                                resultPage = listToPage(page, data);
                            }
                        }
                    }
                }
            }
        }
        return resultPage;
    }

    /**
     * 通过水表编号获取信息
     *
     * @param number 水表编号
     * @return list
     */
    @Override
    public Map<String, Object> numberGetInfo(String number) {

        if (StringUtil.isEmpty(number)) {
            throw new ToflyDeniedException("请输入表号!");
        }

        Map<String, Object> map = bwrksbdatailMapper.numberGetInfo(number);

        if (!bwrksbdatailMapper.getDmaTable(number).isEmpty()) {
            throw new ToflyDeniedException("该表号已做配置");
        }
        if (map == null) {
            throw new ToflyDeniedException("该表未存在或未安装");
        }
        return map;
    }

    /**
     * 模糊查询水表编号
     *
     * @param str str
     * @return list
     */
    @Override
    public List<String> likeNumber(String str) {
        return bwrksbdatailMapper.likeNumber("'%" + str + "%'");
    }

    /* *********************************************************************************** */


    /**
     * 将list输出page
     */
    public static Page listToPage(Page page, List pageList) {
        // 当前页第一条数据在List中的位置
        int start = (int) ((page.getCurrent() - 1) * page.getSize());
        // 当前页最后一条数据在List中的位置
        int end = (int) ((start + page.getSize()) > pageList.size() ? pageList.size() : (page.getSize() * page.getCurrent()));
        page.setRecords(new ArrayList<>());
        if (page.getSize() * (page.getCurrent() - 1) <= page.getTotal()) {
            // 分隔列表 当前页存在数据时 设置
            page.setRecords(pageList.subList(start, end));
        }
        page.setTotal(pageList.size());
        return page;
    }
}
