package com.mosty.yszx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.mosty.base.model.dto.sjzx.TbSjSpbfDTO;
import com.mosty.base.model.dto.yszx.Cameras;
import com.mosty.base.model.dto.yszx.TbYsSxtDto;
import com.mosty.base.model.entity.lzother.ZhjmxfXfqwXfqyGzdw;
import com.mosty.base.model.entity.yszx.TbYsGajg;
import com.mosty.base.model.entity.yszx.TbYsSxt;
import com.mosty.base.model.query.yszx.TbYsSxtNoPageQuery;
import com.mosty.base.model.query.yszx.TbYsSxtPageOneQuery;
import com.mosty.base.model.query.yszx.TbYsSxtQuery;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.yszx.TbYsGajgQuery;
import com.mosty.base.utils.CameraPreviewUtil;
import com.mosty.base.utils.UUIDGenerator;
import com.mosty.yszx.mapper.TbYsGajgMapper;
import com.mosty.yszx.mapper.TbYsSxtMapper;
import com.mosty.yszx.remote.TbBaseAdaptRemoteService;
import com.mosty.yszx.remote.TbSjzxAdaptRemoteService;
import com.mosty.yszx.service.TbYsSxtService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

//import org.locationtech.jts.geom.Geometry;
//import org.locationtech.jts.io.WKTReader;
//import org.geotools.geometry.jts.JTSFactoryFinder;

/**
 * @author dw
 * @since 2022/7/19
 **/
@Service
@AllArgsConstructor
public class TbYsSxtServiceImpl extends ServiceImpl<TbYsSxtMapper, TbYsSxt> implements TbYsSxtService {

    private final TbSjzxAdaptRemoteService tbSjzxAdaptRemoteService;
    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
    private final TbYsGajgMapper tbYsGajgMapper;

    @Override
    public int insertEntity(TbYsSxtDto dto) {
        TbYsSxt sxt = new TbYsSxt();
        BeanUtils.copyProperties(dto, sxt);
        sxt.setId(UUIDGenerator.getUUID());
        sxt.setJsnr(sxt.getSbbh() + " " + sxt.getSbmc() + " " + sxt.getCsmc() + " " + sxt.getDzmc());
        sxt.setXtSjly("1");
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(dto.getSsbmdm());
        if (dept != null) {
            sxt.setSsbmdm(dept.getDeptcode());
            sxt.setSsbmid(dept.getDeptid());
            sxt.setSsbm(dept.getDeptname());
            sxt.setSsxgaj(dept.getFxjname());
            sxt.setSsxgajid(dept.getFxjid());
            sxt.setSsxgajdm(dept.getFxjcode());
            sxt.setSssgaj(dept.getDszname());
            sxt.setSssgajid(dept.getDszid());
            sxt.setSssgajdm(dept.getDszid());
        }
        return this.baseMapper.insertEntity(sxt);
    }

    @Override
    public void updateEntity(TbYsSxtDto dto) {
        TbYsSxt sxt = new TbYsSxt();
        BeanUtils.copyProperties(dto, sxt);

        this.baseMapper.updateEntity(sxt);
        sxt = this.baseMapper.getInfoById(sxt.getId());
        sxt.setJsnr(sxt.getSbbh() + " " + sxt.getSbmc() + " " + sxt.getCsmc() + " " + sxt.getDzmc());
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(dto.getSsbmdm());
        if (dept != null) {
            sxt.setSsbmdm(dept.getDeptid());
            sxt.setSsbm(dept.getDeptname());
            sxt.setSsxgaj(dept.getFxjname());
            sxt.setSsxgajdm(dept.getFxjid());
            sxt.setSssgaj(dept.getDszname());
            sxt.setSssgajdm(dept.getDszid());
        }
        this.baseMapper.updateEntity(sxt);
    }

    @Override
    public IPage<TbYsSxt> getPageList(TbYsSxtQuery dto) {
        Map<String, Object> map = new HashMap<>();
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(),null));
        map.put("pageIndex", (dto.getPageNum() - 1) * dto.getPageSize());
        map.put("pageSize", dto.getPageSize());
        map.put("dto", dto);

        int count = this.baseMapper.getCount(map);
        List<TbYsSxt> list = this.baseMapper.getPageList(map);
        IPage<TbYsSxt> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        page.setTotal(count);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<TbYsSxt> getList(TbYsSxtNoPageQuery dto) {
        Map<String, Object> map = new HashMap<>();
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(),null));
        map.put("dto", dto);
        return this.baseMapper.getList(map);
    }

    @Override
    public TbYsSxt getInfo(String id) {
        return this.baseMapper.getInfoById(id);
    }

    @Override
    public void delEntity(String id) {
        TbYsSxt sxt = this.baseMapper.getInfoById(id);
        if (sxt != null) {
            sxt.setXtScbz("1");
            this.baseMapper.updateEntity(sxt);
        }
    }

    @Override
    public List<TbYsSxt> getSjList(String jd, String wd, String sjid) {
        Map<String, Object> map = new HashMap<>();
        map.put("jd", jd);
        map.put("wd", wd);
        List<TbYsSxt> tbYsSxt = this.baseMapper.getSjList(map);
        if (!CollectionUtils.isEmpty(tbYsSxt)) {
            for (TbYsSxt tb : tbYsSxt) {
                TbSjSpbfDTO tbSjSpbf = new TbSjSpbfDTO();
                tbSjSpbf.setId(UUIDGenerator.getUUID());
                tbSjSpbf.setSjId(sjid);
                tbSjSpbf.setSxtId(tb.getId());
                tbSjSpbf.setBfkssj(new Date());
                tbSjSpbf.setSsbm(tb.getSsbm());
                tbSjSpbf.setSsbmdm(tb.getSsbmdm());
                tbSjSpbf.setSsxgaj(tb.getSsxgaj());
                tbSjSpbf.setSsxgajdm(tb.getSsxgajdm());
                tbSjSpbf.setSssgaj(tb.getSssgaj());
                tbSjSpbf.setSssgajdm(tb.getSssgajdm());
                tbSjzxAdaptRemoteService.tbSjSpbfAdd(tbSjSpbf);
            }
        }
        return tbYsSxt;
    }

    @Override
    public int insertEntity(TbYsSxt sxt) {
        return this.baseMapper.insertEntity(sxt);
    }

    @Override
    public TbYsSxt queryBySjlyid(String sjlyid) {
        return this.baseMapper.queryBySjlyid(sjlyid);
    }

    @Override
    public TbYsSxtDto getInfoBySbbh(String sbbh) {
        TbYsSxt sxt = this.baseMapper.selectOne(
                new LambdaQueryWrapper<TbYsSxt>()
                        .eq(TbYsSxt::getSbbh, sbbh)
                        .last(" limit 1")
        );
        if (sxt != null) {
            TbYsSxtDto dto = new TbYsSxtDto();
            BeanUtils.copyProperties(sxt, dto);
            return dto;
        }
        return null;
    }

    @Override
    public List<String> getSxtBhList(List<String> ids) {
        List<String> rList = new ArrayList<>();
        ids.forEach(id -> {
            TbYsSxt sxt = this.baseMapper.selectOne(
                    new LambdaQueryWrapper<TbYsSxt>()
                            .eq(TbYsSxt::getXtSjzt, "1")
                            .eq(TbYsSxt::getSbbh, id)
                            .last("limit 1")
            );
            if (sxt == null) {
                rList.add(id);
            }
        });
        return rList;
    }

    @Override
    public void addLzGzy(ZhjmxfXfqwXfqyGzdw dto) {
        TbYsSxt sxt = this.baseMapper.selectOne(
                new LambdaQueryWrapper<TbYsSxt>()
                        .eq(TbYsSxt::getXtSjzt, "1")
                        .eq(TbYsSxt::getSbbh, dto.getSbbh())
                        .last(" limit 1")
        );
        if (sxt != null) return;
        sxt = new TbYsSxt();
        sxt.setSjlyid(dto.getId());
        sxt.setJkdbgbh(dto.getSbbh());
        sxt.setSbbh(dto.getSbbh());
        sxt.setSbmc(dto.getSbmc());
        sxt.setCsmc(dto.getCsmc());
        sxt.setIpdz(dto.getIpdz());
        sxt.setIpv6dz(dto.getIpv6dz());
        sxt.setJd(dto.getDqjd());
        sxt.setWd(dto.getDqwd());
        sxt.setXzqhdm(dto.getAzddXzqhdm());
        sxt.setDzmc(StringUtils.isEmpty(dto.getAzddDzmc()) ? dto.getSbmc() : dto.getAzddDzmc());
        sxt.setSblxdm(dto.getGzsblxdm());
        sxt.setJsfxdm(dto.getJsfxdm());
        sxt.setJsqysm(dto.getJsqysm());
        sxt.setSxjwzlxdm(dto.getSxjwzlxdm());
        sxt.setSxjytdm(dto.getSxjytdm());
        sxt.setSbzt("1");
        sxt.setXtSjly("1");
        sxt.setSblx("01");
        sxt.setJsnr(sxt.getSbbh() + " " + sxt.getSbmc() + " " + sxt.getCsmc() + " " + sxt.getDzmc());
        sxt.setSsxgaj(dto.getSsfxjmc());
        sxt.setSsxgajdm(dto.getSsfxjdm());
        sxt.setSssgaj(dto.getSsdszmc());
        sxt.setSssgajdm(dto.getSsdszdm());
        // TODO　计算所属辖区位置
        this.baseMapper.insertEntity(sxt);
    }

    @Override
    public TbYsSxtDto selectGzy(TbYsSxtPageOneQuery dto) {
        TbYsSxt sxt = this.baseMapper.selectOne(
                new LambdaQueryWrapper<TbYsSxt>()
                        .eq(TbYsSxt::getSbmc, dto.getSbmc())
                        .eq(TbYsSxt::getJd, dto.getJd())
                        .eq(TbYsSxt::getWd, dto.getWd())
                        .eq(TbYsSxt::getXtSjzt, "1")
                        .last(" limit 1")
        );
        if (sxt != null) {
            TbYsSxtDto vo = new TbYsSxtDto();
            BeanUtils.copyProperties(sxt, vo);
            return vo;
        }
        return null;
    }

    @Override
    public void updateJwd() {
        //获取经纬度为空为0数据
        LambdaQueryWrapper<TbYsSxt> wp = new LambdaQueryWrapper<>();
        wp.ne(TbYsSxt::getJd, 0).ne(TbYsSxt::getWd, 0);
        wp.notLike(TbYsSxt::getSsbm, "派出所").or(w -> w.isNull(TbYsSxt::getSsbm));
        List<TbYsSxt> tbYsSxts = this.baseMapper.selectList(wp);
        if (!CollectionUtils.isEmpty(tbYsSxts)) {
            Map<String, Object> map = new HashMap<>();
            TbYsGajgQuery query = new TbYsGajgQuery();
            query.setGajgmc("派出所");
            map.put("dto", query);
            List<String> ysxlList = new ArrayList<String>() {{
                this.add("001001004");
            }};
            map.put("ysxlList", ysxlList);
            List<TbYsGajg> tbYsGajgs = this.tbYsGajgMapper.getList(map);
//            if (!CollectionUtils.isEmpty(tbYsGajgs)) {
//                for (TbYsSxt tb : tbYsSxts) {
//                    if (tb.getJd() != null || tb.getWd() != null) {
//                        for (TbYsGajg tbYsGajg : tbYsGajgs) {
//                            if (!StringUtils.isEmpty(tbYsGajg.getDtm())) {
//                                String wktPoly = tbYsGajg.getDtm().toString();
//                                WKTReader reader = new WKTReader(JTSFactoryFinder.getGeometryFactory());
//                                Geometry geometry;
//                                try {
//                                    geometry = reader.read(wktPoly);
//                                    Geometry geometryOut = reader.read("POINT(" + tb.getJd() + " " + tb.getWd() + ")");
//                                    boolean isSsd = geometry.contains(geometryOut);
//                                    if (isSsd) {
//                                        tb.setSsbm(tbYsGajg.getGajgjc());
//                                        tb.setSsbmdm(tbYsGajg.getSsbmdm());
//                                        tb.setSsbmid(tbYsGajg.getSsbmid());
//                                        TbYsSxtDto dto = new TbYsSxtDto();
//                                        BeanUtils.copyProperties(tb, dto);
//                                        this.updateEntity(dto);
//                                        break;
//                                    }
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        }
//                    }
//                }
//            }
        }
    }


    @Override
    public void updateLzGzy() {
        this.baseMapper.deleteAll();
        saveGzy(1);

    }

    public void saveGzy(Integer pageNo) {
        final String getCamsApi = "/api/resource/v1/cameras";
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", pageNo);
        jsonBody.put("pageSize", 1000);
        jsonBody.put("treeCode", 0);
        String result = CameraPreviewUtil.getCameraPreviewURL(getCamsApi, jsonBody);// post请求application/json类型参数
        if (!StringUtils.isEmpty(result)) {
            Cameras cameras = JSONObject.parseObject(result, Cameras.class);
            if (cameras.getCode().equals("0") && cameras.getData() != null) {
                List<Cameras.listInfo> list = cameras.getData().getList();
                if (!CollectionUtils.isEmpty(list)) {
                    list.forEach(v -> {
                                if (!StringUtils.isEmpty(v.getCapabilitySetName()) && v.getCapabilitySetName().indexOf("Face") < 0) {
//                        if (v.getStatus() == 1) {
                                    ZhjmxfXfqwXfqyGzdw entity = new ZhjmxfXfqwXfqyGzdw();
                                    entity.setId(UUIDGenerator.getUUID());
                                    entity.setSbbh(v.getGbIndexCode());
                                    entity.setSbmc(v.getName());
                                    entity.setCsmc("海康威视");
                                    entity.setDqjd(StringUtils.isEmpty(v.getLongitude()) ? null : new BigDecimal(v.getLongitude()));
                                    entity.setDqwd(StringUtils.isEmpty(v.getLatitude()) ? null : new BigDecimal(v.getLatitude()));
//                        entity.setAzddDzmc(v.getName());
                                    entity.setGzsblxdm("01");
                                    entity.setCjsjlxdm("01");
                                    entity.setSxjytdm("1");
                                    entity.setSsdszmc("四川省雅安市公安局");
                                    entity.setSsdszdm("511800000000");
                                    entity.setSsstmc("四川省公安厅");
                                    entity.setSsstdm("510000000000");
                                    if (!StringUtils.isEmpty(v.getGbIndexCode()) && v.getGbIndexCode().length() >= 6) {
                                        String xzqh = v.getGbIndexCode().substring(0, 6);
                                        entity.setAzddXzqhdm(xzqh);
                                        switch (xzqh) {
                                            case "511825":
                                                entity.setSsfxjmc("四川省雅安市天全县公安局");
                                                entity.setSsfxjdm(xzqh + "000000");
                                                break;
                                        }
                                    }
                                    if (!StringUtils.isEmpty(entity.getSsfxjmc())) {
                                        this.addLzGzy(entity);
                                    }
//                        }
                                }
                            }
                    );

                }
            }
            Integer page = (int) Math.ceil((double) cameras.getData().getTotal() / (double) cameras.getData().getPageSize());
            System.out.println(pageNo);
            if (page > pageNo) {
                this.saveGzy(pageNo + 1);
            }
        }
    }

}
