package com.ruoyi.dxp.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.dxp.domain.Table;
import com.ruoyi.dxp.domain.TableColumn;
import com.ruoyi.dxp.dto.*;
import com.ruoyi.dxp.dto.database.DatabaseUtilsCreateTableParam;
import com.ruoyi.dxp.dto.database.DatabaseUtilsDbQueryParam;
import com.ruoyi.dxp.dto.database.DatabaseUtilsIndexParam;
import com.ruoyi.dxp.dto.database.DatabaseUtilsInsertParam;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据库帮助类
 */
public class DatabaseUtils {
    /**
     * DatebaseConnDto 连接配置
     *
     * @param config
     * @return
     */
    public static R<String> conn(ResApiDbConnDto config) {
        String url = OutServiceConfig.ApiUrl + "/dxp/database/connect";
        String param = JSON.toJSONString(config);
        // 发起请求
        String resApiResult = HttpUtils.sendPost(url, param);
        ResApiResultDto result = JSON.parseObject(resApiResult, ResApiResultDto.class);

        if (result.getCode() != 0) {
            return R.fail(result.getMsg());
        }

        return R.ok();
    }

    /**
     * 获取数据库连接状态
     *
     * @param req 请求参数
     * @return
     */
    public static R<ResApiPageDto<ResApiDbListDto>> getConnStatus(ResApiQueryDto req) {
        String url = OutServiceConfig.ApiUrl + "/dxp/database/databaseQueryStatus";
        String param = JSON.toJSONString(req);

        String resApiResult = HttpUtils.sendPost(url, param);
        ResApiResultDto<ResApiPageDto<ResApiDbListDto>> result = JSON.parseObject(resApiResult, ResApiResultDto.class);

        if (result.getCode() != 0) {
            return R.fail(result.getMsg());
        }

        if (result.getCode() == null) {
            return R.ok();
        }

        return R.ok(result.getData());
    }

    /**
     * 获取指定数据库下的所有表信息
     *
     * @param databaseId 数据库id
     * @return 表列表
     */
    public static R<List<Table>> getTableList(Long databaseId) {
        String url = OutServiceConfig.ApiUrl + "/dxp/database/databaseQueryTableList";
        String param = "{\"id\": " + databaseId + "}";

        String resApiResult = HttpUtils.sendPost(url, param);
        if (StringUtils.isEmpty(resApiResult)) {
            return R.fail("未获取到接口结果");
        }

        // 获取结果
        JSONObject jsonObject = JSON.parseObject(resApiResult);
        Integer code = jsonObject.getInteger("code");

        if (code == 0) {
            String data = jsonObject.getString("data");
            JSONObject jsonObjectList = JSON.parseObject(data);
            String listStr = jsonObjectList.getString("list");

            if (StringUtils.isNotEmpty(listStr)) {
                List<ResApiTableDto> list = JSON.parseArray(listStr, ResApiTableDto.class);
                List<Table> tableList = new ArrayList<>();
                for (ResApiTableDto t : list) {
                    Table table = new Table();
                    table.setTableName(t.getName());
                    table.setTableComment(t.getComments());
                    table.setDatabaseId(databaseId);

                    tableList.add(table);
                }

                return R.ok(tableList);
            }
        }
        return R.ok();
    }

    /**
     * 获取指定数据库，指定表下的列信息
     * @param databaseId 数据库id
     * @param tableName 表名
     * @return
     */
    public static R<List<TableColumn>> getColumnList(Long databaseId, String tableName) {
        String url = OutServiceConfig.ApiUrl + "/dxp/database/databaseQueryTableColnList";
        String param = "{ \"id\": " + databaseId + ", \"tableName\": \"" + tableName + "\" }";

        String resApiResult = HttpUtils.sendPost(url, param);
        if (StringUtils.isEmpty(resApiResult)) {
            return R.fail("未获取到接口结果");
        }

        // 获取结果
        JSONObject jsonObject = JSON.parseObject(resApiResult);
        Integer code = jsonObject.getInteger("code");

        if (code == 0) {
            String data = jsonObject.getString("data");
            JSONObject jsonObjectList = JSON.parseObject(data);
            String listStr = jsonObjectList.getString("list");

            if (StringUtils.isNotEmpty(listStr)) {
                List<ResApiColumnDto> list = JSON.parseArray(listStr, ResApiColumnDto.class);
                List<TableColumn> tableColumns = new ArrayList<>();
                long sort = 1;
                for (ResApiColumnDto t : list) {
                    TableColumn tableColumn = new TableColumn();
                    tableColumn.setColumnName(t.getName());
                    tableColumn.setColumnComment(t.getComments());
                    tableColumn.setColumnType(t.getType());
                    tableColumn.setDatabaseId(databaseId);
                    tableColumn.setSort(sort);
                    tableColumns.add(tableColumn);
                    sort++;
                }

                return R.ok(tableColumns);
            }
        }

        return R.ok();
    }

    /**
     * 删除索引
     * @param indexParam 参数
     * @return 结果
     */
    public static R<String> deleteIndex(DatabaseUtilsIndexParam indexParam) {
        String url = OutServiceConfig.ApiUrl + "/dxp/database/databaseDeleteIndex";
        String param = JSON.toJSONString(indexParam);
        String resApiResult = HttpUtils.sendPost(url, param);
        if (StringUtils.isEmpty(resApiResult)) {
            return R.fail("未获取到接口结果");
        }

        ResApiResultDto result = JSON.parseObject(resApiResult, ResApiResultDto.class);
        if (result.getCode() != 0) {
            return R.fail(result.getMsg());
        }

        return R.ok();
    }

    /**
     * 创建索引
     * @param indexParam 参数
     * @return 结果
     */
    public static R<String> addIndex(DatabaseUtilsIndexParam indexParam) {
        String url = OutServiceConfig.ApiUrl + "/dxp/database/databaseAddIndex";
        String param = JSON.toJSONString(indexParam);
        String resApiResult = HttpUtils.sendPost(url, param);
        if (StringUtils.isEmpty(resApiResult)) {
            return R.fail("未获取到接口结果");
        }

        ResApiResultDto result = JSON.parseObject(resApiResult, ResApiResultDto.class);
        if (result.getCode() != 0) {
            return R.fail(result.getMsg());
        }

        return R.ok();
    }

    /**
     * 创建表
     * @param createTableParam 创建参数
     * @return 结果
     */
    public static R<String> createTable(DatabaseUtilsCreateTableParam createTableParam) {
        String url = OutServiceConfig.ApiUrl + "/dxp/database/databaseCreateTable";
        String param = JSON.toJSONString(createTableParam);
        String resApiResult = HttpUtils.sendPost(url, param);
        if (StringUtils.isEmpty(resApiResult)) {
            return R.fail("未获取到接口结果");
        }

        ResApiResultDto result = JSON.parseObject(resApiResult, ResApiResultDto.class);
        if (result.getCode() != 0) {
            return R.fail(result.getMsg());
        }

        return R.ok();
    }

    /**
     * 查询数据
     * @param insertParam 插入参数
     * @return 结果
     */
    public static R<String> insertTable(DatabaseUtilsInsertParam insertParam) {
        String url = OutServiceConfig.ApiUrl + "/dxp/database/databaseInsertData";
        String param = JSON.toJSONString(insertParam);
        String resApiResult = HttpUtils.sendPost(url, param);
        if (StringUtils.isEmpty(resApiResult)) {
            return R.fail("未获取到接口结果");
        }

        ResApiResultDto result = JSON.parseObject(resApiResult, ResApiResultDto.class);
        if (result.getCode() != 0) {
            return R.fail(result.getMsg());
        }

        return R.ok();
    }

    /**
     * 查询表数据
     * @param queryParam 查询参数
     * @return 查询结果
     */
    public static R<ResApiPageDto<List<Object>>> queryTable(DatabaseUtilsDbQueryParam queryParam) {
        String url = OutServiceConfig.ApiUrl + "/dxp/database/databaseQueryTable";
        String param = JSON.toJSONString(queryParam);
        String resApiResult = HttpUtils.sendPost(url, param);
        if (StringUtils.isEmpty(resApiResult)) {
            return R.fail("未获取到接口结果");
        }

        ResApiResultDto<ResApiPageDto<List<Object>>> result = JSON.parseObject(resApiResult, ResApiResultDto.class);
        if (result != null) {
            return R.ok(result.getData());
        }

        return R.ok();
    }

    /**
     * 删除表
     * @param databaseId 数据库id
     * @param tableName 表名
     * @return 结果
     */
    public static R<String> deleteTable(Long databaseId, String tableName) {
        String url = OutServiceConfig.ApiUrl + "/dxp/database/databaseDropTable";
        String param = "{ \"id\": " + databaseId + ", \"tbName\": \"" + tableName + "\" }";

        String resApiResult = HttpUtils.sendPost(url, param);
        if (StringUtils.isEmpty(resApiResult)) {
            return R.fail("未获取到接口结果");
        }

        ResApiResultDto result = JSON.parseObject(resApiResult, ResApiResultDto.class);
        if (result.getCode() != 0) {
            return R.fail(result.getMsg());
        }

        return R.ok();
    }

    /**
     * 删除表数据
     * @param databaseId 数据库id
     * @param tableName 表名
     * @return 结果
     */
    public static R<String> deleteTableData(Long databaseId, String tableName) {
        String url = OutServiceConfig.ApiUrl + "/dxp/database/databaseDeleteTableData";
        String param = "{ \"id\": " + databaseId + ", \"tbName\": \"" + tableName + "\" }";

        String resApiResult = HttpUtils.sendPost(url, param);
        if (StringUtils.isEmpty(resApiResult)) {
            return R.fail("未获取到接口结果");
        }

        ResApiResultDto result = JSON.parseObject(resApiResult, ResApiResultDto.class);
        if (result.getCode() != 0) {
            return R.fail(result.getMsg());
        }

        return R.ok();
    }

    /**
     * 用户端查询表数据
     * @param queryParam 查询参数
     * @return 查询结果
     */
    public static R<ResApiPageDto<List<Object>>> queryCustomerTable(String accessId, DatabaseUtilsDbQueryParam queryParam) {
        String url = OutServiceConfig.ApiUrl + "/dxp/outapi/base/proxyToData/any/" + accessId;
        String param = JSON.toJSONString(queryParam);
        String resApiResult = HttpUtils.sendPost(url, param);
        if (StringUtils.isEmpty(resApiResult)) {
            return R.fail("未获取到接口结果");
        }

        ResApiResultDto<ResApiPageDto<List<Object>>> result = JSON.parseObject(resApiResult, ResApiResultDto.class);
        if (result != null) {
            if (result.getCode().equals(0)) {
                return R.ok(result.getData());
            } else {
                return R.fail(result.getCode().intValue(), result.getMsg());
            }
        }

        return R.ok();
    }
}
