package admin_agent

import (
	"context"
	"fmt"
	"strings"
	"time"

	"sim-server/app/main/model"
	"sim-server/common/xerr"
	"sim-server/pkg/lzkit/crypto"

	"github.com/pkg/errors"

	"sim-server/app/main/api/internal/svc"
	"sim-server/app/main/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminGetAgentOrdersListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminGetAgentOrdersListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetAgentOrdersListLogic {
	return &AdminGetAgentOrdersListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminGetAgentOrdersListLogic) AdminGetAgentOrdersList(req *types.AdminGetAgentOrdersListReq) (resp *types.AdminGetAgentOrdersListResp, err error) {
	// 1. 查询订单列表（基础查询）
	orders, total, err := l.queryOrders(req)
	if err != nil {
		return nil, err
	}

	if len(orders) == 0 {
		return &types.AdminGetAgentOrdersListResp{
			Total: 0,
			Items: []types.AgentOrdersListItem{},
		}, nil
	}

	// 2. 收集所有需要的ID
	orderIds := make([]string, len(orders))
	userIds := make([]string, 0, len(orders))
	productIds := make([]string, 0, len(orders))
	for i, order := range orders {
		orderIds[i] = order.Id
		userIds = append(userIds, order.UserId)
		productIds = append(productIds, order.ProductId)
	}

	// 3. 批量查询佣金信息
	commissionsMap := l.queryCommissionsByOrderIds(orderIds)

	// 4. 批量查询代理信息
	agentIds := make([]string, 0)
	for _, commission := range commissionsMap {
		agentIds = append(agentIds, commission.AgentId)
	}
	agentsMap := l.queryAgentsByAgentIds(agentIds)

	// 5. 批量查询用户信息
	usersMap := l.queryUsersByUserIds(userIds)

	// 6. 批量查询产品信息
	productsMap := l.queryProductsByProductIds(productIds)

	// 7. 批量查询查询记录（用于报告结果跳转）
	queriesMap := l.queryQueriesByOrderIds(orderIds)

	// 8. 组装数据
	list := l.assembleOrderList(orders, commissionsMap, agentsMap, usersMap, productsMap, queriesMap)

	// 8. 应用后端筛选条件（代理、用户、产品、佣金状态）
	filteredList := l.applyFilters(list, req, agentsMap, usersMap, productsMap, commissionsMap)

	// 9. 应用分页（如果使用了后端筛选）
	if l.needsBackendFiltering(req) {
		total = int64(len(filteredList))
		// 手动分页
		page := req.Page
		if page <= 0 {
			page = 1
		}
		pageSize := req.PageSize
		if pageSize <= 0 {
			pageSize = 20
		}

		start := (page - 1) * pageSize
		end := start + pageSize
		if start > int64(len(filteredList)) {
			return &types.AdminGetAgentOrdersListResp{
				Total: total,
				Items: []types.AgentOrdersListItem{},
			}, nil
		}
		if end > int64(len(filteredList)) {
			end = int64(len(filteredList))
		}

		return &types.AdminGetAgentOrdersListResp{
			Total: total,
			Items: filteredList[start:end],
		}, nil
	}

	return &types.AdminGetAgentOrdersListResp{
		Total: total,
		Items: filteredList,
	}, nil
}

// needsBackendFiltering 检查是否需要后端筛选
func (l *AdminGetAgentOrdersListLogic) needsBackendFiltering(req *types.AdminGetAgentOrdersListReq) bool {
	return (req.AgentId != nil && *req.AgentId != "") ||
		(req.AgentMobile != nil && *req.AgentMobile != "") ||
		(req.UserMobile != nil && *req.UserMobile != "") ||
		(req.ProductName != nil && *req.ProductName != "") ||
		(req.CommissionStatus != nil)
}

// applyFilters 应用后端筛选条件
func (l *AdminGetAgentOrdersListLogic) applyFilters(
	list []types.AgentOrdersListItem,
	req *types.AdminGetAgentOrdersListReq,
	agentsMap map[string]*model.Agent,
	usersMap map[string]*model.User,
	productsMap map[string]*model.Product,
	commissionsMap map[string]*model.AgentCommission,
) []types.AgentOrdersListItem {
	var result []types.AgentOrdersListItem

	for _, item := range list {
		// 代理ID筛选
		if req.AgentId != nil && *req.AgentId != "" {
			if item.AgentId != *req.AgentId {
				continue
			}
		}

		// 代理手机号筛选
		if req.AgentMobile != nil && *req.AgentMobile != "" {
			if !contains(item.AgentMobile, *req.AgentMobile) {
				continue
			}
		}

		// 用户手机号筛选
		if req.UserMobile != nil && *req.UserMobile != "" {
			if item.UserMobile == nil || !contains(*item.UserMobile, *req.UserMobile) {
				continue
			}
		}

		// 产品名称筛选
		if req.ProductName != nil && *req.ProductName != "" {
			if !contains(item.ProductName, *req.ProductName) {
				continue
			}
		}

		// 佣金状态筛选
		if req.CommissionStatus != nil {
			if item.CommissionStatus != *req.CommissionStatus {
				continue
			}
		}

		result = append(result, item)
	}

	return result
}

// contains 检查字符串是否包含子字符串（不区分大小写）
func contains(str, substr string) bool {
	return strings.Contains(strings.ToLower(str), strings.ToLower(substr))
}

// queryOrders 查询订单列表
func (l *AdminGetAgentOrdersListLogic) queryOrders(req *types.AdminGetAgentOrdersListReq) ([]*model.Order, int64, error) {
	builder := l.svcCtx.OrderModel.SelectBuilder()

	// 订单筛选
	if req.OrderNo != nil && *req.OrderNo != "" {
		builder = builder.Where("`order_no` LIKE ?", "%"+*req.OrderNo+"%")
	}
	if req.PlatformOrderId != nil && *req.PlatformOrderId != "" {
		builder = builder.Where("`platform_order_id` LIKE ?", "%"+*req.PlatformOrderId+"%")
	}
	if req.PaymentPlatform != nil && *req.PaymentPlatform != "" {
		builder = builder.Where("`payment_platform` = ?", *req.PaymentPlatform)
	}
	if req.PaymentScene != nil && *req.PaymentScene != "" {
		builder = builder.Where("`payment_scene` = ?", *req.PaymentScene)
	}
	if req.OrderStatus != nil && *req.OrderStatus != "" {
		builder = builder.Where("`status` = ?", *req.OrderStatus)
	}

	// 时间筛选
	if req.CreateTimeStart != nil && *req.CreateTimeStart != "" {
		createTimeStart, err := time.Parse("2006-01-02 15:04:05", *req.CreateTimeStart)
		if err == nil {
			builder = builder.Where("`create_time` >= ?", createTimeStart)
		}
	}
	if req.CreateTimeEnd != nil && *req.CreateTimeEnd != "" {
		createTimeEnd, err := time.Parse("2006-01-02 15:04:05", *req.CreateTimeEnd)
		if err == nil {
			builder = builder.Where("`create_time` <= ?", createTimeEnd)
		}
	}
	if req.PayTimeStart != nil && *req.PayTimeStart != "" {
		payTimeStart, err := time.Parse("2006-01-02 15:04:05", *req.PayTimeStart)
		if err == nil {
			builder = builder.Where("`pay_time` >= ?", payTimeStart)
		}
	}
	if req.PayTimeEnd != nil && *req.PayTimeEnd != "" {
		payTimeEnd, err := time.Parse("2006-01-02 15:04:05", *req.PayTimeEnd)
		if err == nil {
			builder = builder.Where("`pay_time` <= ?", payTimeEnd)
		}
	}

	// 排序
	orderBy := "`create_time` DESC"
	if req.OrderBy != nil && *req.OrderBy != "" {
		orderType := "DESC"
		if req.OrderType != nil && strings.ToUpper(*req.OrderType) == "ASC" {
			orderType = "ASC"
		}
		orderBy = fmt.Sprintf("`%s` %s", *req.OrderBy, orderType)
	}

	// 分页
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 20
	}

	// 查询总数和列表
	orders, total, err := l.svcCtx.OrderModel.FindPageListByPageWithTotal(l.ctx, builder, page, pageSize, orderBy)
	if err != nil {
		return nil, 0, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询订单列表失败, %v", err)
	}

	return orders, total, nil
}

// queryCommissionsByOrderIds 批量查询佣金信息
func (l *AdminGetAgentOrdersListLogic) queryCommissionsByOrderIds(orderIds []string) map[string]*model.AgentCommission {
	if len(orderIds) == 0 {
		return make(map[string]*model.AgentCommission)
	}

	// 构建IN查询
	inClause := strings.Repeat("?,", len(orderIds))
	inClause = inClause[:len(inClause)-1]

	commissions, err := l.svcCtx.AgentCommissionModel.FindAll(l.ctx,
		l.svcCtx.AgentCommissionModel.SelectBuilder().
			Where(fmt.Sprintf("`order_id` IN (%s)", inClause), stringsToInterfaces(orderIds)...),
		"")

	if err != nil {
		logx.Errorf("查询佣金信息失败: %v", err)
		return make(map[string]*model.AgentCommission)
	}

	// 构建map: orderId -> commission
	result := make(map[string]*model.AgentCommission)
	for _, commission := range commissions {
		result[commission.OrderId] = commission
	}

	return result
}

// queryAgentsByAgentIds 批量查询代理信息
func (l *AdminGetAgentOrdersListLogic) queryAgentsByAgentIds(agentIds []string) map[string]*model.Agent {
	if len(agentIds) == 0 {
		return make(map[string]*model.Agent)
	}

	// 去重
	uniqueAgentIds := make(map[string]bool)
	for _, id := range agentIds {
		uniqueAgentIds[id] = true
	}

	ids := make([]string, 0, len(uniqueAgentIds))
	for id := range uniqueAgentIds {
		ids = append(ids, id)
	}

	if len(ids) == 0 {
		return make(map[string]*model.Agent)
	}

	// 构建IN查询
	inClause := strings.Repeat("?,", len(ids))
	inClause = inClause[:len(inClause)-1]

	agents, err := l.svcCtx.AgentModel.FindAll(l.ctx,
		l.svcCtx.AgentModel.SelectBuilder().
			Where(fmt.Sprintf("`id` IN (%s)", inClause), stringsToInterfaces(ids)...),
		"")

	if err != nil {
		logx.Errorf("查询代理信息失败: %v", err)
		return make(map[string]*model.Agent)
	}

	// 构建map: agentId -> agent
	result := make(map[string]*model.Agent)
	for _, agent := range agents {
		result[agent.Id] = agent
	}

	return result
}

// queryUsersByUserIds 批量查询用户信息
func (l *AdminGetAgentOrdersListLogic) queryUsersByUserIds(userIds []string) map[string]*model.User {
	if len(userIds) == 0 {
		return make(map[string]*model.User)
	}

	// 去重
	uniqueUserIds := make(map[string]bool)
	for _, id := range userIds {
		uniqueUserIds[id] = true
	}

	ids := make([]string, 0, len(uniqueUserIds))
	for id := range uniqueUserIds {
		ids = append(ids, id)
	}

	if len(ids) == 0 {
		return make(map[string]*model.User)
	}

	// 构建IN查询
	inClause := strings.Repeat("?,", len(ids))
	inClause = inClause[:len(inClause)-1]

	users, err := l.svcCtx.UserModel.FindAll(l.ctx,
		l.svcCtx.UserModel.SelectBuilder().
			Where(fmt.Sprintf("`id` IN (%s)", inClause), stringsToInterfaces(ids)...),
		"")

	if err != nil {
		logx.Errorf("查询用户信息失败: %v", err)
		return make(map[string]*model.User)
	}

	// 构建map: userId -> user
	result := make(map[string]*model.User)
	for _, user := range users {
		result[user.Id] = user
	}

	return result
}

// queryProductsByProductIds 批量查询产品信息
func (l *AdminGetAgentOrdersListLogic) queryProductsByProductIds(productIds []string) map[string]*model.Product {
	if len(productIds) == 0 {
		return make(map[string]*model.Product)
	}

	// 去重
	uniqueProductIds := make(map[string]bool)
	for _, id := range productIds {
		uniqueProductIds[id] = true
	}

	ids := make([]string, 0, len(uniqueProductIds))
	for id := range uniqueProductIds {
		ids = append(ids, id)
	}

	if len(ids) == 0 {
		return make(map[string]*model.Product)
	}

	// 构建IN查询
	inClause := strings.Repeat("?,", len(ids))
	inClause = inClause[:len(inClause)-1]

	products, err := l.svcCtx.ProductModel.FindAll(l.ctx,
		l.svcCtx.ProductModel.SelectBuilder().
			Where(fmt.Sprintf("`id` IN (%s)", inClause), stringsToInterfaces(ids)...),
		"")

	if err != nil {
		logx.Errorf("查询产品信息失败: %v", err)
		return make(map[string]*model.Product)
	}

	// 构建map: productId -> product
	result := make(map[string]*model.Product)
	for _, product := range products {
		result[product.Id] = product
	}

	return result
}

// queryQueriesByOrderIds 批量查询查询记录信息
func (l *AdminGetAgentOrdersListLogic) queryQueriesByOrderIds(orderIds []string) map[string]*model.Query {
	if len(orderIds) == 0 {
		return make(map[string]*model.Query)
	}

	// 构建IN查询
	inClause := strings.Repeat("?,", len(orderIds))
	inClause = inClause[:len(inClause)-1]

	queries, err := l.svcCtx.QueryModel.FindAll(l.ctx,
		l.svcCtx.QueryModel.SelectBuilder().
			Where(fmt.Sprintf("`order_id` IN (%s)", inClause), stringsToInterfaces(orderIds)...),
		"")

	if err != nil {
		logx.Errorf("查询查询记录失败: %v", err)
		return make(map[string]*model.Query)
	}

	// 构建map: orderId -> query
	result := make(map[string]*model.Query)
	for _, query := range queries {
		result[query.OrderId] = query
	}

	return result
}

// assembleOrderList 组装订单列表数据
func (l *AdminGetAgentOrdersListLogic) assembleOrderList(
	orders []*model.Order,
	commissionsMap map[string]*model.AgentCommission,
	agentsMap map[string]*model.Agent,
	usersMap map[string]*model.User,
	productsMap map[string]*model.Product,
	queriesMap map[string]*model.Query,
) []types.AgentOrdersListItem {
	var list []types.AgentOrdersListItem

	for _, order := range orders {
		// 获取佣金信息
		var commissionAmount float64
		var commissionStatus int64 = 2 // 默认已取消
		var agentId string
		var agentMobile string

		if commission, ok := commissionsMap[order.Id]; ok {
			commissionAmount = commission.Amount
			commissionStatus = commission.Status
			agentId = commission.AgentId

			// 获取代理信息并解密手机号
			if agent, ok := agentsMap[commission.AgentId]; ok {
				if agent.Mobile != "" {
					// 解密代理手机号
					mobile, err := crypto.DecryptMobile(agent.Mobile, l.svcCtx.Config.Encrypt.SecretKey)
					if err != nil {
						logx.Errorf("解密代理手机号失败: %v", err)
						agentMobile = ""
					}
					agentMobile = mobile
				}
			}
		} else {
			// 没有佣金记录，使用订单ID作为代理ID
			agentId = order.Id
		}

		// 获取用户手机号并解密
		var userMobile *string
		if user, ok := usersMap[order.UserId]; ok && user.Mobile.Valid {
			// 解密用户手机号
			mobile, err := crypto.DecryptMobile(user.Mobile.String, l.svcCtx.Config.Encrypt.SecretKey)
			if err != nil {
				logx.Errorf("解密用户手机号失败: %v", err)
				userMobile = nil
			} else {
				userMobile = &mobile
			}
		}

		// 获取产品名称
		productName := "未知产品"
		if product, ok := productsMap[order.ProductId]; ok {
			productName = product.ProductName
		}

		// 获取平台订单号
		platformOrderId := ""
		if order.PlatformOrderId.Valid {
			platformOrderId = order.PlatformOrderId.String
		}

		// 获取支付时间
		var payTime *string
		if order.PayTime.Valid {
			pt := order.PayTime.Time.Format("2006-01-02 15:04:05")
			payTime = &pt
		}

		// 获取查询记录ID（用于报告结果跳转）
		var queryId *string
		if query, ok := queriesMap[order.Id]; ok {
			queryId = &query.Id
		}

		list = append(list, types.AgentOrdersListItem{
			Id:               order.Id,
			OrderNo:          order.OrderNo,
			PlatformOrderId:  platformOrderId,
			AgentId:          agentId,
			AgentMobile:      agentMobile,
			UserId:           order.UserId,
			UserMobile:       userMobile,
			ProductId:        order.ProductId,
			ProductName:      productName,
			OrderAmount:      order.Amount,
			CommissionAmount: commissionAmount,
			PaymentPlatform:  order.PaymentPlatform,
			PaymentScene:     order.PaymentScene,
			OrderStatus:      order.Status,
			CommissionStatus: commissionStatus,
			CreateTime:       order.CreateTime.Format("2006-01-02 15:04:05"),
			PayTime:          payTime,
			QueryId:          queryId,
		})
	}

	return list
}

// stringsToInterfaces 将字符串数组转换为interface数组
func stringsToInterfaces(strs []string) []interface{} {
	result := make([]interface{}, len(strs))
	for i, str := range strs {
		result[i] = str
	}
	return result
}
