package org.example.Impl;


import org.example.Entity.BaseResponse.BaseResponse;
import org.example.Entity.Node.TreeNode;
import org.example.Utils.DbOperator;
import org.example.Utils.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

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

@Service
public class MapImpl extends OptBaseImpl {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private final DbOperator dbOperator;

    @Autowired
    public MapImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
        this.dbOperator = new DbOperator(jdbcTemplate);
    }

    /**
     * 根据模块ID获取地理位置标记图标路径
     *
     * @param dllcoid 模块ID
     * @return 图标路径
     */
    public String getMarkerIcon(String dllcoid) {
        String sql = "select locationimg from dbo.p_systemdlltab where dllcoid = ?";
        Object result = jdbcTemplate.queryForObject(sql, new Object[]{dllcoid}, String.class);
        return result != null ? result.toString() : "";
    }

    /**
     * 根据城市名称获取地理位置信息
     *
     * @param cityname 城市名称
     * @return 包含地理位置信息的响应对象
     */
    public BaseResponse getArea(String cityname) {
        BaseResponse response = new BaseResponse();
        String select = "id as code, parent_id as parentcode, name, longitude as lng, latitude as lat, boundaries, level, desp";
        String sql = String.format("select %s from dbo.P_Area where name = ? or short_name = ?", select);

        List<Map<String, Object>> data = jdbcTemplate.queryForList(sql, cityname, cityname);
        response.setData(data);
        response.setSuccess(true);
        return response;
    }

    /**
     * 根据城市名称获取所属城市及下一级和父级相关信息
     *
     * @param cityname 城市名称
     * @return 包含地理位置信息的响应对象
     */
    public BaseResponse getAreas(String cityname) {
        BaseResponse response = new BaseResponse();
        String select = "id as code, parent_id as parentcode, name, longitude, latitude, boundaries, level, desp";
        String citySql = String.format("select %s from dbo.P_Area where name = ? or short_name = ?", select);

        List<Map<String, Object>> cityData = jdbcTemplate.queryForList(citySql, cityname, cityname);

        if (!cityData.isEmpty()) {
            Map<String, Object> firstRow = cityData.get(0);
            String id = firstRow.get("code").toString();
            String parentId = firstRow.get("parentcode").toString();

            String areaSql = String.format("select %s from dbo.P_Area where parent_id = ? " +
                    "union all " +
                    "select %s from dbo.P_Area where parent_id = (select parent_id from dbo.P_Area where id = ?)", select, select);

            List<Map<String, Object>> areaData = jdbcTemplate.queryForList(areaSql, parentId, id);
            response.setData(areaData);
            response.setSuccess(true);
        }

        return response;
    }

    /**
     * 根据城市ID获取子级城市信息
     *
     * @param id 城市ID
     * @return 包含子级城市信息的响应对象
     */
    public BaseResponse getAreaChildren(String id) {
        BaseResponse response = new BaseResponse();
        String select = "id as code, parent_id as parentcode, name, longitude, latitude, boundaries, level, desp";
        String sql = String.format("select %s from dbo.P_Area where parent_id = ?", select);

        List<Map<String, Object>> data = jdbcTemplate.queryForList(sql, id);
        response.setData(data);
        response.setSuccess(true);
        return response;
    }

    /**
     * 获取地理位置的整个树形结构
     *
     * @param name 城市名称
     * @return 包含树形结构的响应对象
     */
    public BaseResponse getAreasToTree(String name) {
        BaseResponse response = new BaseResponse();
        String code = "";

        // 获取城市编码
        String codeSql = "select id from dbo.P_Area where name = ?";
        try {
            code = jdbcTemplate.queryForObject(codeSql, new Object[]{name}, String.class);
        } catch (Exception e) {
            // 未查询到对应城市时返回空响应
            return response;
        }

        if (code == null || code.isEmpty()) {
            return response;
        }

        // 处理编码（去除末尾的0）
        String trimmedCode = code.replaceAll("0+$", "");
        String sql = "select id as code, parent_id as parentcode, name, level, desp from dbo.P_Area where id like ?";
        List<Map<String, Object>> areaData = jdbcTemplate.queryForList(sql, trimmedCode + "%");

        if (!areaData.isEmpty()) {
            // 转换为TreeNode列表
            List<TreeNode> nodes = areaData.stream().map(row -> {
                TreeNode node = new TreeNode();
                node.setSpeciesno(row.get("code").toString());
                node.setSpeciesname(row.get("name").toString());
                node.parentno = (row.get("parentcode") != null ? row.get("parentcode").toString() : "");
                node.setCheckbox(false);
                return node;
            }).collect(Collectors.toList());

            // 设置子节点
            for (TreeNode node : nodes) {
                List<TreeNode> children = nodes.stream()
                        .filter(child -> child.parentno.equals(node.getSpeciesno()))
                        .collect(Collectors.toList());
                node.children = (children);
            }

            // 获取根节点（与原始code匹配的节点）
            String finalCode = code;
            List<TreeNode> rootNodes = nodes.stream()
                    .filter(node -> node.getSpeciesno().equals(finalCode))
                    .collect(Collectors.toList());

            response.setData(rootNodes);
            response.setSuccess(true);
        }

        return response;
    }

    /**
     * 修改地理位置数据
     *
     * @param id    地理位置ID
     * @param datas 修改的数据（JSON字符串）
     * @return 是否修改成功
     */
    public boolean updateArea(String id, String datas) {
        // 解析JSON数据为Map
        Map<String, Object> dataMap = (Map<String, Object>) JSON.Decode(datas);
        if (dataMap.isEmpty()) {
            return false;
        }

        // 构建更新SQL
        StringBuilder updateSql = new StringBuilder("update P_Area set ");
        List<Object> params = new ArrayList<>();

        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            updateSql.append(entry.getKey()).append(" = ?, ");
            params.add(entry.getValue());
        }

        // 移除末尾的逗号和空格
        if (updateSql.length() > 0) {
            updateSql.setLength(updateSql.length() - 2);
        }

        updateSql.append(" where id = ?");
        params.add(id);

        // 执行更新
        int rowsAffected = jdbcTemplate.update(updateSql.toString(), params.toArray());
        return rowsAffected > 0;
    }
}