package com.mosty.yjzl.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.mosty.base.model.dto.yjzl.TbZdxlFgdwSaveDTO;
import com.mosty.base.model.dto.yjzl.TbZdxlFgdwUpdateDTO;
import com.mosty.base.model.entity.yjzl.TbYjxx;
import com.mosty.base.model.entity.yjzl.zddw.TbZdxlFgdw;
import com.mosty.base.model.query.yjzl.TbZdxlFgdwQuery;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.yjzl.TbZdxlFgdwVO;
import com.mosty.base.utils.PageUtils;
import com.mosty.base.utils.QueryWrapperUtils;
import com.mosty.base.utils.UUIDGenerator;
import com.mosty.yjzl.mapper.TbZdxlFgdwMapper;
import com.mosty.yjzl.remote.TbBaseAdaptRemoteService;
import com.mosty.yjzl.service.TbZdxlFgdwService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zhangzhao
 * @description 指导巡逻方格点位表Service实现类
 * @modifier zhangzhao
 * @modifiedTime 2025/05/15 21:55
 * @since 2025/05/15 21:55
 */
@Service
@AllArgsConstructor
public class TbZdxlFgdwServiceImpl extends ServiceImpl<TbZdxlFgdwMapper, TbZdxlFgdw> implements TbZdxlFgdwService {

    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
    @Override
    public TbZdxlFgdwVO selectById(Long id) {
        if(ObjectUtils.isEmpty(id)){
            return null;
        }
        TbZdxlFgdw entity = this.baseMapper.selectOne(new QueryWrapper<TbZdxlFgdw>()
                .eq(TbZdxlFgdw.ID_FIELD, id)
                .eq("xt_sjzt", "1")
                .eq("xt_scbz", "0")
        );
        return this.buildAllInfoByEntity(entity);
    }

    @Override
    public TbZdxlFgdwVO selectByBddId(String bddId) {
        if(StringUtils.isBlank(bddId)){
            return null;
        }
        TbZdxlFgdw entity = this.baseMapper.selectOne(new QueryWrapper<TbZdxlFgdw>()
                .inSql(TbZdxlFgdw.ID_FIELD, "select fgdw_id from tb_zdxl_fgdw_bdd where xt_sjzt = '1' and xt_scbz = '0' and id = '" + bddId + "' ")
                .eq("xt_sjzt", "1")
                .eq("xt_scbz", "0")
        );
        return this.buildAllInfoByEntity(entity);
    }

    @Override
    public List<TbZdxlFgdwVO> selectAllList() {
        return this.buildAllInfoListByEntityList(this.baseMapper.selectList(new QueryWrapper<>()));
    }

    @Override
    public IPage<TbZdxlFgdwVO> selectPage(TbZdxlFgdwQuery query) {
        IPage<TbZdxlFgdw> page = PageUtils.buildPage(query.getPageSize(), query.getPageCurrent());
        QueryWrapper<TbZdxlFgdw> qw = new QueryWrapper<>();

        //组装查询参数
        this.buildListSelectQueryWrapper(qw, query);

        //返回Page
        IPage<TbZdxlFgdwVO> resultPage = new Page<>(query.getPageCurrent(), query.getPageSize());
        String ssbm = this.tbBaseAdaptRemoteService.getSsbm(query.getSsdbmdm(), null);
        qw.lambda().likeRight(StringUtils.isNotBlank(ssbm), TbZdxlFgdw::getSsbmdm, ssbm);
        //查询数据
        page = this.baseMapper.selectPage(page, qw);
        List<TbZdxlFgdw> list = page.getRecords();
        if(CollectionUtils.isEmpty(list)){
            return resultPage;
        }

        //转为VO
        List<TbZdxlFgdwVO> resultList = this.buildAllInfoListByEntityList(list);

        //组装VO
        resultPage.setRecords(resultList);
        resultPage.setTotal(page.getTotal());
        return resultPage;
    }

    @Override
    public List<TbZdxlFgdwVO> selectList(TbZdxlFgdwQuery query) {
        QueryWrapper<TbZdxlFgdw> qw = new QueryWrapper<>();

        //组装查询参数
        this.buildListSelectQueryWrapper(qw, query);

        //查询数据
        List<TbZdxlFgdw> list = this.baseMapper.selectList(qw);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }

        //转为VO返回
        return this.buildAllInfoListByEntityList(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long updateEntity(TbZdxlFgdwUpdateDTO dto) {
        //复制参数至实体
        TbZdxlFgdw entity = BeanUtil.copyProperties(dto, TbZdxlFgdw.class);
        entity.setMc1(dto.getMc());

        //修改实体
        int resultInt = this.baseMapper.updateById(entity);
        if(resultInt > 0){
            //返回主键
            return entity.getId();
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveEntity(TbZdxlFgdwSaveDTO dto) {
        //复制参数至实体
        TbZdxlFgdw entity = BeanUtil.copyProperties(dto, TbZdxlFgdw.class);
        entity.setMc1(dto.getMc());
        entity.setX11(dto.getX1());
        entity.setY11(dto.getY1());
        entity.setX21(dto.getX2());
        entity.setY21(dto.getY2());

        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(dto.getSsbmdm());
        if(Objects.nonNull(dept)){
            entity.setSsbm(dept.getDeptname());
            entity.setSsbmdm(dept.getDeptcode());
            entity.setSsxgajdm(dept.getFxjcode());
            entity.setSsxgaj(dept.getFxjname());
            entity.setSssgaj(dept.getDszname());
            entity.setSssgajdm(dept.getDszcode());
        }
        //新增实体
        int resultInt = this.baseMapper.insert(entity);
        if(resultInt > 0){
            //返回主键
            return entity.getId();
        }
        return null;
    }

    /**
     * 组装查询参数
     * @param qw QueryWrapper
     * @param query 查询对象
     */
    private void buildListSelectQueryWrapper(QueryWrapper<TbZdxlFgdw> qw, TbZdxlFgdwQuery query){
        //组装其他排序方式
        QueryWrapperUtils.buildQueryWrapperOrder(qw, query.getSort(), query.getOrder());
        //未注销数据
        qw.eq("xt_sjzt", "1").eq("xt_scbz", "0");

        //方格点位ID
        qw.like(ObjectUtils.isNotEmpty(query.getMc()), TbZdxlFgdw.MC, query.getMc());

    }

    /**
     * 组装全量信息列表（根据实体列表）
     * @param entityList 实体列表
     * @return 全量信息列表
     */
    private List<TbZdxlFgdwVO> buildAllInfoListByEntityList(List<TbZdxlFgdw> entityList){
        if(CollectionUtils.isEmpty(entityList)){
            return null;
        }
        List<TbZdxlFgdwVO> allInfoVOList = new ArrayList<>();
        //组装返回数据
        for(TbZdxlFgdw entity : entityList){
            TbZdxlFgdwVO resultVO = this.buildAllInfoByEntity(entity);
            allInfoVOList.add(resultVO);
        }
        //返回列表
        if(CollectionUtils.isEmpty(allInfoVOList)){
            return null;
        }
        return allInfoVOList;
    }

    /**
     * 组装全量信息（根据实体信息）
     * @param entity 实体信息
     * @return 全量信息
     */
    private TbZdxlFgdwVO buildAllInfoByEntity(TbZdxlFgdw entity){
        if(ObjectUtils.isEmpty(entity)){
            return null;
        }
        TbZdxlFgdwVO resultVO = BeanUtil.copyProperties(entity, TbZdxlFgdwVO.class);

        //组装方格其他数据
        resultVO.setMc(resultVO.getMc1());
        resultVO.setX1(resultVO.getX11());
        resultVO.setY1(resultVO.getY11());
        resultVO.setX2(resultVO.getX21());
        resultVO.setY2(resultVO.getY21());

        return resultVO;
    }

    @Override
    public Map<String, BigDecimal> getSquarePoints(double longitude, double latitude, double distance) {
        Map<String, BigDecimal> squareMap = new HashMap<>();
        // 计算经度弧度,从弧度转换为角度
        double dLongitude = 2 * (Math.asin(Math.sin(distance / (2 * 6378137)) / Math.cos(Math.toRadians(latitude))));
        dLongitude = Math.toDegrees(dLongitude);
        // 计算纬度角度
        double dLatitude = distance / 6378137;
        dLatitude = Math.toDegrees(dLatitude);
        // 正方形四个角点
        // 左上角
        double[] leftTopPoint = {latitude + dLatitude, longitude - dLongitude};

        // 右下角
        double[] rightBottomPoint = {latitude - dLatitude, longitude + dLongitude};

        BigDecimal x1 = BigDecimal.valueOf(leftTopPoint[1]);
        BigDecimal y1 = BigDecimal.valueOf(leftTopPoint[0]);
        BigDecimal x2 = BigDecimal.valueOf(rightBottomPoint[1]);
        BigDecimal y2 = BigDecimal.valueOf(rightBottomPoint[0]);

        squareMap.put("x1", x1);
        squareMap.put("y1", y1);
        squareMap.put("x2", x2);
        squareMap.put("y2", y2);
        return squareMap;
    }

    @Override
    public Integer deleteById(Long id) {
        if (ObjectUtils.isEmpty(id)) {
            return 0;
        }
        return this.baseMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return 0;
        }
        int count = 0;
        for (Long id : ids) {
            count += this.deleteById(id);
        }
        return count;
    }

}
