package module

import (
	"fmt"
	"strings"
	"time"

	"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/context"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/log"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/persist/tablestoredb"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/recconf"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/utils"
)

type UserCollaborativeTableStoreDao struct {
	tablestore *tablestoredb.TableStore
	itemType   string
	userTable  string
	itemTable  string
	recallName string
}

func NewUserCollaborativeTableStoreDao(config recconf.RecallConfig) *UserCollaborativeTableStoreDao {
	dao := &UserCollaborativeTableStoreDao{}
	tablestore, err := tablestoredb.GetTableStore(config.UserCollaborativeDaoConf.TableStoreName)
	if err != nil {
		log.Error(fmt.Sprintf("%v", err))
		return nil
	}
	dao.tablestore = tablestore
	dao.userTable = config.UserCollaborativeDaoConf.User2ItemTable
	dao.itemTable = config.UserCollaborativeDaoConf.Item2ItemTable
	dao.itemType = config.ItemType
	dao.recallName = config.Name
	return dao
}

func (d *UserCollaborativeTableStoreDao) ListItemsByUser(user *User, context *context.RecommendContext) (ret []*Item) {
	getRowRequest := new(tablestore.GetRowRequest)
	criteria := new(tablestore.SingleRowQueryCriteria)
	putPk := new(tablestore.PrimaryKey)
	putPk.AddPrimaryKeyColumn("user_id", string(user.Id))

	criteria.PrimaryKey = putPk
	criteria.ColumnsToGet = []string{"item_ids"}
	getRowRequest.SingleRowQueryCriteria = criteria
	getRowRequest.SingleRowQueryCriteria.TableName = d.userTable
	getRowRequest.SingleRowQueryCriteria.MaxVersion = 1
	start := time.Now()
	getResp, err := d.tablestore.Client.GetRow(getRowRequest)
	log.Debug(fmt.Sprintf("UserCollaborativeTableStoreDao resp, cost=%d", utils.CostTime(start)))
	if err != nil {
		log.Error(fmt.Sprintf("requestId=%s\tmodule=UserCollaborativeTableStoreDao\terror=%v", context.RecommendId, err))
		return
	}
	if len(getResp.Columns) == 0 {
		log.Info(fmt.Sprintf("requestId=%s\tmodule=UserCollaborativeTableStoreDao\tuid=%s\terr=item ids empty", context.RecommendId, user.Id))
		return
	}

	var ids string

	if str, ok := getResp.Columns[0].Value.(string); ok {
		ids = str
	}
	itemIds := strings.Split(ids, ",")
	if len(itemIds) == 0 {
		log.Info(fmt.Sprintf("module=UserCollaborativeTableStoreDao\tuid=%s\terr=item ids empty", user.Id))
		return
	}

	cpuCount := 4
	maps := make(map[int][]string)
	for i, id := range itemIds {
		maps[i%cpuCount] = append(maps[i%cpuCount], id)
	}

	itemIdCh := make(chan []string, cpuCount)
	for _, ids := range maps {
		itemIdCh <- ids
	}

	itemCh := make(chan []*Item, cpuCount)
	for i := 0; i < cpuCount; i++ {
		go func() {
			result := make([]*Item, 0)
		LOOP:
			for {
				select {
				case ids := <-itemIdCh:
					batchGetRowRequest := new(tablestore.BatchGetRowRequest)
					multiRowQueryCriteria := new(tablestore.MultiRowQueryCriteria)
					multiRowQueryCriteria.ColumnsToGet = []string{"similar_item_ids"}
					multiRowQueryCriteria.TableName = d.itemTable
					multiRowQueryCriteria.MaxVersion = 1

					for _, id := range ids {
						putPk := new(tablestore.PrimaryKey)
						putPk.AddPrimaryKeyColumn("item_id", id)
						multiRowQueryCriteria.AddRow(putPk)
					}
					batchGetRowRequest.MultiRowQueryCriteria = []*tablestore.MultiRowQueryCriteria{multiRowQueryCriteria}

					batchGetResp, err := d.tablestore.Client.BatchGetRow(batchGetRowRequest)
					if err != nil {
						log.Error(fmt.Sprintf("requestId=%s\tmodule=UserCollaborativeTableStoreDao\terror=%v", context.RecommendId, err))
						goto LOOP
					}

					for _, rows := range batchGetResp.TableToRowsResult {
						for _, row := range rows {
							if row.IsSucceed == true && len(row.Columns) > 0 {
								if str, ok := row.Columns[0].Value.(string); ok {
									list := strings.Split(str, ",")
									for _, id := range list {
										strs := strings.Split(id, ":")
										if len(strs) == 1 && strs[0] != "" && strs[0] != "null" {
											item := &Item{
												Id:         ItemId(strs[0]),
												ItemType:   d.itemType,
												RetrieveId: d.recallName,
											}

											result = append(result, item)

										} else if len(strs) == 2 && len(strs[0]) > 0 && strs[0] != "null" {
											item := &Item{
												Id:         ItemId(strs[0]),
												ItemType:   d.itemType,
												RetrieveId: d.recallName,
											}

											result = append(result, item)
										}
									}
								}

							}
						}
					}

				default:
					goto DONE

				}
			}
		DONE:
			itemCh <- result
		}()
	}
	for i := 0; i < cpuCount; i++ {
		items := <-itemCh
		ret = append(ret, items...)
	}
	close(itemCh)
	close(itemIdCh)
	return
}
