package query

import (
	"context"
	"database/sql"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"in-server/common/xerr"
	"in-server/pkg/lzkit/crypto"
	"in-server/pkg/lzkit/lzUtils"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"

	"in-server/app/main/api/internal/svc"
	"in-server/app/main/api/internal/types"
	"in-server/app/main/model"
)

func ProcessQueryData(queryData sql.NullString, target *[]types.QueryItem, key []byte) error {
	queryDataStr := lzUtils.NullStringToString(queryData)
	if queryDataStr == "" {
		return nil
	}
	decryptedData, decryptErr := crypto.AesDecrypt(queryDataStr, key)
	if decryptErr != nil {
		return decryptErr
	}
	var decryptedArray []map[string]interface{}
	unmarshalErr := json.Unmarshal(decryptedData, &decryptedArray)
	if unmarshalErr != nil {
		return unmarshalErr
	}
	if len(*target) == 0 {
		*target = make([]types.QueryItem, len(decryptedArray))
	}
	for i := 0; i < len(decryptedArray); i++ {
		(*target)[i].Data = decryptedArray[i]
	}
	return nil
}

func ProcessQueryParams(QueryParams string, target *map[string]interface{}, key []byte) error {
	decryptedData, decryptErr := crypto.AesDecrypt(QueryParams, key)
	if decryptErr != nil {
		return decryptErr
	}
	unmarshalErr := json.Unmarshal(decryptedData, target)
	if unmarshalErr != nil {
		return unmarshalErr
	}
	return nil
}

func UpdateFeatureAndProductFeature(ctx context.Context, svcCtx *svc.ServiceContext, productID string, target *[]types.QueryItem) error {
	// 预先加载当前产品下所有 feature 的排序配置，避免在循环中反复查库
	builder := svcCtx.ProductFeatureModel.SelectBuilder().Where("product_id = ?", productID)
	productFeatures, err := svcCtx.ProductFeatureModel.FindAll(ctx, builder, "")
	if err != nil {
		return fmt.Errorf("查询 ProductFeatureModel 错误: %v", err)
	}

	featureSortMap := make(map[string]int, len(productFeatures))
	for _, pf := range productFeatures {
		featureSortMap[pf.FeatureId] = int(pf.Sort)
	}

	for i := 0; i < len(*target); i++ {
		queryItem := &(*target)[i]

		// Data 不是 map 或没有 apiID 时，不再报错/删除，直接跳过，保留原始数据
		data, ok := queryItem.Data.(map[string]interface{})
		if !ok {
			continue
		}
		apiID, ok := data["apiID"].(string)
		if !ok {
			continue
		}

		// 查不到 feature 时也补充信息：使用 apiID 作为名称、排序默认 0
		feature, err := svcCtx.FeatureModel.FindOneByApiId(ctx, apiID)
		featureName := apiID
		sort := 0
		if err == nil && feature != nil {
			featureName = feature.Name
			if s, ok := featureSortMap[feature.Id]; ok {
				sort = s
			}
		}
		featureData := map[string]interface{}{
			"featureName": featureName,
			"sort":        sort,
		}
		queryItem.Feature = featureData
	}
	return nil
}

func BuildEncryptedQuery(ctx context.Context, svcCtx *svc.ServiceContext, queryModel *model.Query) (string, error) {
	var query types.Query
	query.CreateTime = queryModel.CreateTime.Format("2006-01-02 15:04:05")
	query.UpdateTime = queryModel.UpdateTime.Format("2006-01-02 15:04:05")
	secretKey := svcCtx.Config.Encrypt.SecretKey
	key, decodeErr := hex.DecodeString(secretKey)
	if decodeErr != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取AES解密解药失败, %v", decodeErr)
	}
	processParamsErr := ProcessQueryParams(queryModel.QueryParams, &query.QueryParams, key)
	if processParamsErr != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告参数处理失败: %v", processParamsErr)
	}
	processErr := ProcessQueryData(queryModel.QueryData, &query.QueryData, key)
	if processErr != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", processErr)
	}
	updateErr := UpdateFeatureAndProductFeature(ctx, svcCtx, queryModel.ProductId, &query.QueryData)
	if updateErr != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", updateErr)
	}
	err := copier.Copy(&query, queryModel)
	if err != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结构体复制失败, %v", err)
	}
	product, err := svcCtx.ProductModel.FindOne(ctx, queryModel.ProductId)
	if err != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取商品信息失败, %v", err)
	}
	query.Product = product.ProductEn
	query.ProductName = product.ProductName

	// 获取订单信息，添加订单金额
	order, orderErr := svcCtx.OrderModel.FindOne(ctx, queryModel.OrderId)
	if orderErr == nil {
		query.Amount = order.Amount
	}

	queryBytes, marshalErr := json.Marshal(query)
	if marshalErr != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 序列化查询结果失败: %v", marshalErr)
	}
	encryptedQuery, encryptErr := crypto.AesEncrypt(queryBytes, key)
	if encryptErr != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 加密查询结果失败: %v", encryptErr)
	}
	return encryptedQuery, nil
}

// IsOrderAgent 兼容保留的旧接口，代理系统已下线，统一返回 false。
func IsOrderAgent(ctx context.Context, svcCtx *svc.ServiceContext, userId string, orderId string) (bool, error) {
	return false, nil
}
