package exporter

import (
	"context"
	"time"

	"gorm.io/gorm"

	"github.com/break/junhong_cmp_fiber/pkg/constants"
)

// ExchangeDataSource 换货记录导出数据源。
type ExchangeDataSource struct {
	db *gorm.DB
}

// NewExchangeDataSource 创建换货记录导出数据源。
func NewExchangeDataSource(db *gorm.DB) *ExchangeDataSource {
	return &ExchangeDataSource{db: db}
}

// Scene 返回导出场景编码。
func (s *ExchangeDataSource) Scene() string {
	return constants.ExportTaskSceneExchange
}

// Count 统计换货记录导出行数。
func (s *ExchangeDataSource) Count(ctx context.Context, params ExportParams) (int, error) {
	var total int64
	query := s.applyFilters(s.baseQuery(ctx), params)
	if err := query.Count(&total).Error; err != nil {
		return 0, err
	}
	return int(total), nil
}

// Headers 返回换货记录导出表头。
func (s *ExchangeDataSource) Headers(context.Context, ExportParams) ([]string, error) {
	return []string{
		"换货单号", "换货类型", "换货原因", "问题描述/备注", "旧资产类型", "旧资产标识符", "新资产标识符",
		"收货人姓名", "收货人电话", "收货地址", "快递公司", "快递单号", "状态", "创建人", "创建时间",
	}, nil
}

// Fetch 按 offset/limit 查询换货记录导出数据。
func (s *ExchangeDataSource) Fetch(ctx context.Context, params ExportParams, offset, limit int) ([][]string, error) {
	if limit <= 0 {
		return [][]string{}, nil
	}

	var items []exchangeExportRow
	query := s.applyFilters(s.baseQuery(ctx), params).
		Select(`
			e.exchange_no,
			e.flow_type,
			e.exchange_reason,
			COALESCE(e.remark, '') AS remark,
			e.old_asset_type,
			e.old_asset_identifier,
			e.new_asset_identifier,
			e.recipient_name,
			e.recipient_phone,
			e.recipient_address,
			e.express_company,
			e.express_no,
			e.status,
			e.created_at,
			COALESCE(ac.username, '') AS creator_name
		`).
		Joins("LEFT JOIN tb_account AS ac ON ac.id = e.creator").
		Order("e.id ASC").
		Limit(limit).
		Offset(offset)
	if err := query.Scan(&items).Error; err != nil {
		return nil, err
	}

	rows := make([][]string, 0, len(items))
	for _, item := range items {
		rows = append(rows, []string{
			item.ExchangeNo,
			constants.GetExchangeFlowTypeName(item.FlowType),
			item.ExchangeReason,
			item.Remark,
			formatExchangeAssetType(item.OldAssetType),
			item.OldAssetIdentifier,
			item.NewAssetIdentifier,
			item.RecipientName,
			item.RecipientPhone,
			item.RecipientAddress,
			item.ExpressCompany,
			item.ExpressNo,
			constants.GetExchangeStatusName(item.Status),
			item.CreatorName,
			item.CreatedAt.Format(exportTimeLayout),
		})
	}
	return rows, nil
}

func (s *ExchangeDataSource) baseQuery(ctx context.Context) *gorm.DB {
	return s.db.WithContext(ctx).Table("tb_exchange_order AS e").Where("e.deleted_at IS NULL")
}

func (s *ExchangeDataSource) applyFilters(query *gorm.DB, params ExportParams) *gorm.DB {
	query = applyExportShopScope(query, params, "e.shop_id")
	if status, ok := filterInt(params.Filters, "status"); ok {
		query = query.Where("e.status = ?", status)
	}
	if flowType, ok := filterString(params.Filters, "flow_type"); ok {
		query = query.Where("COALESCE(NULLIF(e.flow_type, ''), ?) = ?", constants.ExchangeFlowTypeShipping, flowType)
	}
	query = applyExchangeAssetKeyword(query, "old", filterValue(params.Filters, "old_asset_keyword"))
	query = applyExchangeAssetKeyword(query, "new", filterValue(params.Filters, "new_asset_keyword"))
	if start, ok := filterTime(params.Filters, "created_at_start"); ok {
		query = query.Where("e.created_at >= ?", start)
	}
	if end, ok := filterTime(params.Filters, "created_at_end"); ok {
		query = query.Where("e.created_at <= ?", end)
	}
	return query
}

func applyExchangeAssetKeyword(query *gorm.DB, side, keyword string) *gorm.DB {
	if keyword == "" {
		return query
	}
	like := "%" + keyword + "%"
	cardIDs := query.Session(&gorm.Session{NewDB: true}).Table("tb_iot_card").Select("id").
		Where("deleted_at IS NULL").
		Where("iccid LIKE ? OR msisdn LIKE ? OR virtual_no LIKE ?", like, like, like)
	deviceIDs := query.Session(&gorm.Session{NewDB: true}).Table("tb_device").Select("id").
		Where("deleted_at IS NULL").
		Where("virtual_no LIKE ? OR imei LIKE ? OR sn LIKE ?", like, like, like)
	prefix := "e." + side
	return query.Where(
		"("+prefix+"_asset_type = ? AND "+prefix+"_asset_id IN (?)) OR ("+prefix+"_asset_type = ? AND "+prefix+"_asset_id IN (?))",
		constants.ExchangeAssetTypeIotCard, cardIDs, constants.ExchangeAssetTypeDevice, deviceIDs,
	)
}

func filterValue(filters map[string]any, key string) string {
	value, _ := filterString(filters, key)
	return value
}

func formatExchangeAssetType(assetType string) string {
	switch assetType {
	case constants.ExchangeAssetTypeIotCard:
		return "物联网卡"
	case constants.ExchangeAssetTypeDevice:
		return "设备"
	case "":
		return ""
	default:
		return "未知"
	}
}

type exchangeExportRow struct {
	ExchangeNo         string    `gorm:"column:exchange_no"`
	FlowType           string    `gorm:"column:flow_type"`
	ExchangeReason     string    `gorm:"column:exchange_reason"`
	Remark             string    `gorm:"column:remark"`
	OldAssetType       string    `gorm:"column:old_asset_type"`
	OldAssetIdentifier string    `gorm:"column:old_asset_identifier"`
	NewAssetIdentifier string    `gorm:"column:new_asset_identifier"`
	RecipientName      string    `gorm:"column:recipient_name"`
	RecipientPhone     string    `gorm:"column:recipient_phone"`
	RecipientAddress   string    `gorm:"column:recipient_address"`
	ExpressCompany     string    `gorm:"column:express_company"`
	ExpressNo          string    `gorm:"column:express_no"`
	Status             int       `gorm:"column:status"`
	CreatorName        string    `gorm:"column:creator_name"`
	CreatedAt          time.Time `gorm:"column:created_at"`
}
