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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
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.oauth.exception.ToflyDeniedException;
import com.tofly.xrtygis.commons.Constant;
import com.tofly.xrtygis.custom.entity.dto.TablelinkUserDto;
import com.tofly.xrtygis.custom.entity.dto.TablelinkpipeDto;
import com.tofly.xrtygis.custom.entity.marketing.CustomerWaterVo;
import com.tofly.xrtygis.custom.entity.marketing.WaterVolume;
import com.tofly.xrtygis.custom.mapper.CustomDisplayMapper;
import com.tofly.xrtygis.custom.mapper.GetMaxIdMapper;
import com.tofly.xrtygis.custom.mapper.TheOnlineCheckMapper;
import com.tofly.xrtygis.custom.service.TheOnlineCheckService;
import com.tofly.xrtygis.custom.util.CommonMethod;
import com.tofly.xrtygis.custom.util.Date7Utils;
import com.tofly.xrtygis.entity.Tablelinkpipe;
import com.tofly.xrtygis.entity.Tablelinkuser;
import com.tofly.xrtygis.entity.Watermeter;
import com.tofly.xrtygis.entity.vo.*;
import com.tofly.xrtygis.service.TablelinkpipeService;
import com.tofly.xrtygis.service.TablelinkuserService;
import com.tofly.xrtygis.service.WatermeterService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.awt.geom.Point2D;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.tofly.xrtygis.custom.util.CommonMethod.listToPage;

/**
 * 综合展示线上核对
 *
 * @author 泡泡
 */
@Service
@AllArgsConstructor
public class TheOnlineCheckServiceImpl implements TheOnlineCheckService {

    private final TablelinkpipeService tablelinkpipeService;
    private final TablelinkuserService tablelinkuserService;
    private final WatermeterService watermeterService;
    private final TheOnlineCheckMapper theOnlineCheckMapper;
    private final CustomDisplayMapper customDisplayMapper;
    private final GetMaxIdMapper getMaxIdMapper;

    private final static String TABLE_LINK_USER = "TF_YWPN_TABLELINKUSER_W";
    //当前数据条数
    private static Double NOW_COUNT = 0D;
    //添加数据条数
    private static Double INSERT_COUNT = 0D;

    /**
     * 确认水表是否为总表
     *D
     * @param code 水表编号
     * @return Boolean
     */
    @Override
    public boolean isSumTable(String code) {
        String sumTable = theOnlineCheckMapper.isSumTable(code);
        return sumTable != null && !"".equals(sumTable);
    }

    /**
     * 总表与管线绑定
     *
     * @param dto 总表与管线关联表
     * @return Boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean bindLine(TablelinkpipeDto dto) {

        if (null == dto) {
            throw new ToflyDeniedException("传入数据为空");
        }
        List<Tablelinkpipe> link = dto.getLink();
        if (link == null || link.isEmpty()) {
            throw new ToflyDeniedException("为传入信息");
        }

        for (Tablelinkpipe t : link) {
            if (t == null) {
                throw new ToflyDeniedException("传入数据为空");
            }
            if (t.getSid() == null || "".equals(t.getSid())) {
                throw new ToflyDeniedException("总表信息为空");
            }
            if (!this.isSumTable(t.getSid())) {
                throw new ToflyDeniedException("表编号：" + t.getSid() + " 不是总表");
            }
            Tablelinkpipe tlp = tablelinkpipeService.getOne(Wrappers.<Tablelinkpipe>lambdaQuery()
                    .eq(Tablelinkpipe::getTableId, t.getTableId()));
            Tablelinkpipe tlp1 = tablelinkpipeService.getOne(Wrappers.<Tablelinkpipe>lambdaQuery()
                    .eq(Tablelinkpipe::getPipeSid, t.getPipeSid()));
            //如果是手动填报
            if ("0".equals(t.getState().toString())){
                if (tlp != null || tlp1 != null){
                    throw new ToflyDeniedException("该总表或管线已有关联");
                }
            }else if ("1".equals(t.getState().toString())){
                if (tlp != null || tlp1 != null){
                    continue;
                }
            }if ("2".equals(t.getState().toString())){
                if (tlp != null){
                    t.setId(tlp.getId());
                    return tablelinkpipeService.updateById(t);
                }
            }
            return tablelinkpipeService.save(t);
        }
        return true;
    }

    /**
     * 查询总表信息
     *
     * @return list
     */
    @Override
    public List<Map<String, Object>> selectSunTable() {
        return theOnlineCheckMapper.selectSumTableInfo();
    }

    /**
     * 显示管线与表信息关联
     *
     * @param page page
     * @return page
     */
    @Override
    public Page<Map<String,Object>> viewTablePipe(Page page, String type, String likeStr) {
        Short types = null;
        if(org.apache.commons.lang3.StringUtils.isNotBlank(type)){
            types = Short.parseShort(type);
        }
        return theOnlineCheckMapper.viewTablePipe(page, types,likeStr);
    }

    @Override
    public String deleteTableById(Long id) {
        List<Map<String,Object>> map = theOnlineCheckMapper.getDmaByTableId(id);
        if(map != null && map.size() != 0){
            throw new ToflyDeniedException("请先解除总表绑定的DMA分区");
        }
        theOnlineCheckMapper.deleteTableById(id);
        theOnlineCheckMapper.deleteUserById(id);
        theOnlineCheckMapper.deleteDmaWaterById(id);
        return "删除成功";
    }

    /**
     * 总表管线确认
     *
     * @param codes 水表编号
     * @return boolean
     */
    @Override
    public boolean confirmTablePipe(String codes,String type) {

        if (StringUtils.isEmpty(type)){
            throw new ToflyDeniedException("未选择确认方式");
        }

        switch (type){
            case "0":
                if (codes == null || "".equals(codes)) {
                    throw new ToflyDeniedException("传入水表编号为空");
                }
                tablelinkpipeService.update(Wrappers.<Tablelinkpipe>lambdaUpdate()
                        .in(Tablelinkpipe::getSid, Arrays.asList(codes.split(",")))
                        .ne(Tablelinkpipe::getState, "1")
                        .set(Tablelinkpipe::getState, "1"));
                break;
            case "1":
                tablelinkpipeService.update(Wrappers.<Tablelinkpipe>lambdaUpdate()
                        .ne(Tablelinkpipe::getState, "1")
                        .set(Tablelinkpipe::getState, "1"));
                break;
            default:
        }
        return true;
    }

    /**
     * 查询未关联客户信息
     *
     * @param str  用户编号/用户地址/用户姓名
     * @param page page
     * @return page
     */
    @Override
    public Page unaffiliatedCustomer(Page page, String str) {
        return theOnlineCheckMapper.unaffiliatedCustomer(page, str);
    }

    /**
     * 用户关联总表
     *
     * @param dto dto
     * @return boolean
     */
    @Override
    public boolean userToTable(TablelinkUserDto dto) {
        if (dto == null) {
            throw new ToflyDeniedException("传入数据为空");
        }
        Long tableId = dto.getTableId();
        if (tableId == null) {
            throw new ToflyDeniedException("未指定关联总表");
        }
        Tablelinkpipe table = tablelinkpipeService.getOne(Wrappers.<Tablelinkpipe>lambdaQuery()
                .eq(Tablelinkpipe::getTableId, tableId).select(Tablelinkpipe::getSid));
        if (table != null && !this.isSumTable(table.getSid())) {
            throw new ToflyDeniedException("表编号：" + table.getSid() + " 不为总表");
        }

        List<Map<String, String>> info = dto.getInfo();
        if (info.isEmpty()) {
            throw new ToflyDeniedException("未传入客户信息");
        }
        List<Tablelinkuser> list = new ArrayList<>();

        Long maxId = getMaxIdMapper.getMaxId(TABLE_LINK_USER);

        Tablelinkuser user;
        String khbh;
        for (Map<String, String> m : info) {
            if(m.get("khbh") == null){
                continue;
            }
            khbh = m.get("khbh");
            user = new Tablelinkuser();
            user.setId(maxId);
            user.setKhbh(khbh);
            user.setTableId(tableId);
            user.setSid(m.get("sbbh"));
            user.setState("0");

            maxId++;
            list.add(user);
        }

        //遍历查询数据库是否存在此列表中的数据，是则删除
        List<Tablelinkuser> tablelinkuserList = tablelinkuserService.list(new QueryWrapper<Tablelinkuser>().eq("TABLE_ID",tableId));
        if(list.size() != 0 && tablelinkuserList != null && tablelinkuserList.size() != 0){
            Iterator<Tablelinkuser> iterator = list.iterator();
            while (iterator.hasNext()) {
                Tablelinkuser next = iterator.next();
                for (Tablelinkuser vo : tablelinkuserList) {
                    if (next.getTableId().equals(vo.getTableId()) && next.getKhbh().equals(vo.getKhbh())) {
                        iterator.remove();
                        break;
                    }
                }
            }
        }
        if(list.size() == 0){
            return true;
        }
        return theOnlineCheckMapper.insertUserToTable(list);
    }

    /**
     * 确认水表与总表
     *
     * @param codes 客户编号
     * @return boolean
     */
    @Override
    public boolean confirmTableUser(String tableId, String codes,String type) {

        if (StringUtils.isEmpty(type)){
            throw new ToflyDeniedException("未选中确认方式");
        }
        if ("0".equals(type)){
            if (StringUtils.isEmpty(tableId)){
                throw new ToflyDeniedException("总表id不能为空");
            }

            if (!StringUtils.isEmpty(tableId) && StringUtils.isEmpty(codes)) {
                tablelinkuserService.update(Wrappers.<Tablelinkuser>lambdaUpdate()
                        .in(Tablelinkuser::getTableId, Arrays.asList(tableId.split(",")))
                        .ne(Tablelinkuser::getState, 1)
                        .set(Tablelinkuser::getState, 1));
            } else {
                tablelinkuserService.update(Wrappers.<Tablelinkuser>lambdaUpdate()
                        .in(Tablelinkuser::getKhbh, Arrays.asList(codes.split(",")))
                        .ne(Tablelinkuser::getState, 1)
                        .set(Tablelinkuser::getState, 1));
            }
        }else {
            tablelinkuserService.update(Wrappers.<Tablelinkuser>lambdaUpdate()
                    .ne(Tablelinkuser::getState, 1)
                    .set(Tablelinkuser::getState, 1));
        }
        return true;
    }

    /**
     * 查询关联总表客户信息
     *
     * @param page page
     * @return page
     */
    @Override
    public Page associatedCustomer(Page page, String tableIds, String likeStr) {
        return theOnlineCheckMapper.affiliatedCustomerPage(page, tableIds, likeStr);
    }

    /**
     * 查询关联总表客户信息
     *
     * @param tableIds 表id
     * @return page
     */
    @Override
    public List<Map<String, Object>> associatedCustomer(String tableIds, String likeStr) {
        return theOnlineCheckMapper.affiliatedCustomer(tableIds, likeStr);
    }

    /**
     * 移除总表-客户关联
     *
     * @param ids ids
     * @return boolean
     */
    @Override
    public boolean removeUser(String tableId, String ids) {
        if (tableId != null && !"".equals(tableId) && StringUtils.isEmpty(ids)) {
            tablelinkuserService.remove(Wrappers.<Tablelinkuser>lambdaQuery()
                    .eq(Tablelinkuser::getTableId, tableId));
        } else {
            tablelinkuserService.removeByIds(Arrays.asList(ids.split(",")));
        }
        return true;
    }

    /**
     * 客户-总表移动
     *
     * @param tableId 总表id
     * @param codes   客户编号
     * @return boolean
     */
    @Override
    public boolean moveUserTable(String tableId, String codes, String origTableId) {
        if (tableId == null) {
            throw new ToflyDeniedException("未选定总表");
        }
        if (codes == null) {
            throw new ToflyDeniedException("未选定转移水表");
        }
        if (origTableId == null) {
            throw new ToflyDeniedException("未选定源总表");
        }
        tablelinkuserService.remove(new QueryWrapper<Tablelinkuser>().lambda()
                .in(Tablelinkuser::getKhbh, Arrays.asList(codes.split(",")))
                .eq(Tablelinkuser::getTableId, origTableId));
        List<Tablelinkuser> tablelinkuserList = new ArrayList<>();
        String[] codeList = codes.split(",");
        for (String c : codeList) {
            Tablelinkuser user = new Tablelinkuser();
            user.setState("0");
            user.setKhbh(c);
            user.setTableId(Long.valueOf(tableId));
            tablelinkuserList.add(user);
        }
        return tablelinkuserService.saveBatch(tablelinkuserList);
    }

    /**
     * 总表换表
     *
     * @param oldId 旧表id
     * @param newId 新表id
     * @return boolean
     */
    @Override
    public boolean inTheTable(String oldId, String newId) {
        if (StringUtils.isEmpty(oldId)) {
            throw new ToflyDeniedException("未传入旧表信息");
        }
        if (StringUtils.isEmpty(newId)) {
            throw new ToflyDeniedException("未传入新表信息");
        }
        return tablelinkuserService.update(Wrappers.<Tablelinkuser>lambdaUpdate()
                .eq(Tablelinkuser::getTableId, oldId)
                .set(Tablelinkuser::getTableId, newId)
                .set(Tablelinkuser::getState, 0));
    }


    /**
     * 设置小区名称
     *
     * @param name      小区名称
     * @param tableCode 水表编号
     * @return boolean
     */
    @Override
    public boolean setPlotName(String name, String tableCode) {
        if (name == null) {
            throw new ToflyDeniedException("未设置小区名称");
        }
        return theOnlineCheckMapper.updatePlotName(name, Arrays.asList(tableCode.split(",")));
    }

    /**
     * 自动匹配
     *
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean autoMatch() {
        List<Map<String, Object>> maps = this.selectSunTable();
        if (!maps.isEmpty()) {
            List<Tablelinkuser> info = new ArrayList<>();
            for (Map<String, Object> map : maps) {
                if (!StringUtils.isEmpty(map.get("address"))) {
                    List<Map<String, Object>> matchInfo = theOnlineCheckMapper.getMatchInfo(map.get("address").toString());
                    if (!matchInfo.isEmpty()) {
                        Long maxId = getMaxIdMapper.getMaxId(TABLE_LINK_USER);
                        Tablelinkuser user;
                        for (Map<String, Object> m : matchInfo) {
                            user = new Tablelinkuser();
                            user.setSid(m.get("sid") == null ? null : m.get("sid").toString());
                            user.setKhbh(m.get("yhbh") == null ? null : m.get("yhbh").toString());
                            user.setState("0");
                            user.setTableId(Long.parseLong(map.get("id").toString()));
                            user.setId(maxId);
                            maxId++;

                            info.add(user);
                        }
                    }
                }
            }
            //查询当前数据条数
            NOW_COUNT = theOnlineCheckMapper.getNowNum();
            INSERT_COUNT = Double.parseDouble(info.size() + "");
            if (!info.isEmpty()) {
                theOnlineCheckMapper.insertUserToTable(info);
            }
        }
        return true;
    }

    /**
     * 获取添加进度
     *
     * @return double
     */
    @Override
    public Double getInsertSchedule() {
        return CommonMethod.divide(CommonMethod.subtract(theOnlineCheckMapper.getNowNum(),NOW_COUNT),INSERT_COUNT);
    }

    @Override
    public Page<ResultUserWaterMeterInfoVo> getTableDmaUserBindList(Page page, Long dmaId, String likeStr, String tableLikeStr) {

        return theOnlineCheckMapper.getTableDmaUserBindList(page,dmaId,likeStr,tableLikeStr);
    }

    @Override
    public List<ResultUserWaterMeterInfoVo> getTableDmaUserBindList(Long dmaId, String likeStr, String tableLikeStr) {
        return theOnlineCheckMapper.getTableDmaUserBindList(dmaId, likeStr, tableLikeStr);
    }

    @Override
    public Page<UserWaterMeterInfoVo> getTableUserBindList(Page page, String likeStr, String cbbmc, String cbpqLikeStr) {
        Page<UserWaterMeterInfoVo> waterMeterInfoVoPage = theOnlineCheckMapper.getTableUserBindList(page,likeStr,cbbmc,cbpqLikeStr);
        for(UserWaterMeterInfoVo one : waterMeterInfoVoPage.getRecords()){
            if(one.getUserCode() == null){
                continue;
            }
            String userCode = one.getUserCode();
            one.setWaterMeterNameList(theOnlineCheckMapper.getTableListByUserCode(userCode));
        }
        return waterMeterInfoVoPage;
    }

    @Override
    public Integer getTableUserListNum() {
        return theOnlineCheckMapper.getTableUserListNum();
    }

    @Override
    public Page<WaterStopAreaInfoVo> waterStopArea(Page page, String pipeIds,String likeStr) {
        // 根据管线获取对应绑定总表信息 tablelinkpipeService
        // 通过总表信息获取对应绑定的用户信息及水表信息
        // 返回用户+水表相关信息  1对多
        return theOnlineCheckMapper.getWaterStopAreaPage(page,pipeIds,likeStr);
    }

    @Override
    public Map<String, Object> getTableInArea(Page page, Double[] lon, Double[] lat, String strTime, String endTime, String code, String likeStr) {
        if (lon == null || lat == null) {
            throw new ToflyDeniedException("区域范围不能为空");
        }
        //查询所有表位过滤坐标为空的数据
        List<Watermeter> watermeterList = watermeterService.list().stream().filter(wm -> wm.getX() != null && wm.getY() != null).collect(Collectors.toList());

        if (watermeterList.isEmpty()) {
            throw new ToflyDeniedException("请先上传水表坐标");
        }

        //存放返回结果
        Map<String, Object> result = new HashMap<>();
        //存放点坐标的集合
        List<Point2D.Double> pointList = new ArrayList<>();

        for (int i = 0; i < lon.length; i++) {
            pointList.add(new Point2D.Double(lon[i], lat[i]));
        }
        //循环有坐标的水表
        Iterator<Watermeter> it = watermeterList.iterator();

        Point2D.Double point;
        //在范围内添加到一个新的集合，否则删除
        while (it.hasNext()) {
            Watermeter next = it.next();
            point = new Point2D.Double(next.getX(), next.getY());
            if (!IsPtInPoly(point, pointList)) {
                it.remove();
            }
        }
        //取出水表编号
        List<String> sid = watermeterList.stream().map(Watermeter::getSid).collect(Collectors.toList());

        if (sid.isEmpty()) {
            throw new ToflyDeniedException("未查询到相关信息");
        }
        //传入时间为空区间设置为三年前
        if (StringUtils.isEmpty(strTime) || StringUtils.isEmpty(endTime) ) {
            strTime = DateUtil.getDateFormat(Date7Utils.addNextPeriod(-36, new Date()), "yyyyMM");
            endTime = Date8Util.getYearMonth();
        }

        List<CustomerWaterVo> data = theOnlineCheckMapper.getCustomerWaterVoList(sid,strTime,endTime,likeStr);
        if (null != data && data.size()>0) {

            //根据月份分组
            Map<String, List<CustomerWaterVo>> collect = data.stream().collect(Collectors.groupingBy(CustomerWaterVo::getMonth));
            //拿出月份
            List<String> cwyfList = new ArrayList(collect.keySet());
            //存放区域水量
            Map<String, Object> mapSum = new HashMap<>();

            List pageList = new ArrayList();

            for (String month : cwyfList) {
                BigDecimal sum = BigDecimal.ZERO;
                if ("0".equals(code)) {
                    //计算截取区域的用水总和
                    sum = collect.get(month).stream().map(p -> p.getWaterConsumption() == null ? BigDecimal.ZERO : p.getWaterConsumption()).reduce(BigDecimal.ZERO, BigDecimal::add);
                } else {
                    String mon = strTime.substring(4, 6);
                    if (mon.equals(month.substring(4, 6))) {
                        sum = collect.get(month).stream().map(p -> p.getWaterConsumption() == null ? BigDecimal.ZERO : p.getWaterConsumption()).reduce(BigDecimal.ZERO, BigDecimal::add);
                    }
                }
                mapSum.put(month, sum);
            }
            //获取坐标
            List<Map> coordinate = customDisplayMapper.getCoordinate(sid);

            pageList.add(mapSum);

            result.put("areaSum", listToPage(page, pageList));
            result.put("coordinate", coordinate);
        }
        return result;
    }

    @Override
    public Page<CustomerWaterVo> useWaterHistory(Page page, String yhbh, String startTime, String endTime) {
        return theOnlineCheckMapper.getUseWaterHistoryPage(page, yhbh, startTime, endTime);
    }

    @Override
    public Page<UserWaterMeterInfoVo> getYxUserInfoPage(Page page, String meterReadingArea, String yhbhs,String likeStr) {
        return theOnlineCheckMapper.getYxUserInfoPage(page, meterReadingArea,yhbhs, likeStr);
    }

    @Override
    public Page<ChargeDetailInfoVo> getYxChargeDetail(Page page, Long userId) {
        return theOnlineCheckMapper.getYxChargeDetail(page, userId);
    }

    @Override
    public Page<ChargeUserInfoVo> getYxChargeUserInfo(Page page, String likeStr, Long chargeArea, String sex) {
        return theOnlineCheckMapper.getYxChargeUserInfo(page, likeStr, chargeArea, sex);
    }

    @Override
    public List<ChargeUserInfoVo> getYxChargeUserInfoList(String likeStr, Long chargeArea, String sex) {
        return theOnlineCheckMapper.getYxChargeUserInfoList(likeStr, chargeArea, sex);
    }

    @Override
    public List<Map<String, Object>> getMeterReadingAreaList() {
        List<Map<String, Object>> list = theOnlineCheckMapper.getMeterReadingAreaList();
        return list.stream().filter(e->!String.valueOf(e.get("sscbpq")).equals("0")).collect(Collectors.toList());
    }

    @Override
    public List<Integer> getDmaLevelListByTableId(Long tableId,Long dmaId) {
        return theOnlineCheckMapper.getDmaLevelListByTableId(tableId,dmaId);
    }

    /**
     * 判断点是否在多边形内
     *
     * @param point 检测点
     * @param pts   多边形的顶点
     * @return 点在多边形内返回true, 否则返回false
     */
    public static boolean IsPtInPoly(Point2D.Double point, List<Point2D.Double> pts) {
        int N = pts.size();
        boolean boundOrVertex = true; //如果点位于多边形的顶点或边上，也算做点在多边形内，直接返回true
        int intersectCount = 0;
        double precision = 2e-10; //浮点类型计算时候与0比较时候的容差
        Point2D.Double p1, p2;
        Point2D.Double p = point; //当前点

        p1 = pts.get(0);
        for (int i = 1; i <= N; ++i) {
            if (p.equals(p1)) {
                return boundOrVertex;
            }
            p2 = pts.get(i % N);
            if (p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)) {
                p1 = p2;
                continue;
            }

            if (p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)) {
                if (p.y <= Math.max(p1.y, p2.y)) {
                    if (p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)) {
                        return boundOrVertex;
                    }

                    if (p1.y == p2.y) {
                        if (p1.y == p.y) {
                            return boundOrVertex;
                        } else {
                            ++intersectCount;
                        }
                    } else {
                        double xinters = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;
                        if (Math.abs(p.y - xinters) < precision) {
                            return boundOrVertex;
                        }

                        if (p.y < xinters) {
                            ++intersectCount;
                        }
                    }
                }
            } else {
                if (p.x == p2.x && p.y <= p2.y) {
                    Point2D.Double p3 = pts.get((i + 1) % N);
                    if (p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)) {
                        ++intersectCount;
                    } else {
                        intersectCount += 2;
                    }
                }
            }
            p1 = p2;
        }

        if (intersectCount % 2 == 0) {
            return false;
        } else {
            return true;
        }
    }

}
