package sql

import (
	"fmt"

	"github.com/88250/lute"
	"github.com/88250/lute/ast"
	"github.com/88250/lute/parse"
	"github.com/siyuan-note/siyuan/kernel/av"
	"github.com/siyuan-note/siyuan/kernel/filesys"
	"github.com/siyuan-note/siyuan/kernel/treenode"
	"github.com/siyuan-note/siyuan/kernel/util"
)

func RenderAttributeViewKanban(attrView *av.AttributeView, view *av.View, query string, depth *int, cachedAttrViews map[string]*av.AttributeView) (ret *av.Kanban) {
	viewable := attrView.RenderedViewables[view.ID]
	if nil != viewable {
		ret = viewable.(*av.Kanban)
		return
	}

	ret = &av.Kanban{
		BaseInstance:           av.NewViewBaseInstance(view),
		CoverFrom:              view.Kanban.CoverFrom,
		CoverFromAssetKeyID:    view.Kanban.CoverFromAssetKeyID,
		CardAspectRatio:        view.Kanban.CardAspectRatio,
		CardSize:               view.Kanban.CardSize,
		FitImage:               view.Kanban.FitImage,
		DisplayFieldName:       view.Kanban.DisplayFieldName,
		FillColBackgroundColor: view.Kanban.FillColBackgroundColor,
		Fields:                 []*av.KanbanField{},
		Cards:                  []*av.KanbanCard{},
	}

	// 组装字段
	for _, field := range view.Kanban.Fields {
		key, getErr := attrView.GetKey(field.ID)
		if nil != getErr {
			// 找不到字段则在视图中删除
			removeMissingField(attrView, view, field.ID)
			continue
		}

		ret.Fields = append(ret.Fields, &av.KanbanField{
			BaseInstanceField: &av.BaseInstanceField{
				ID:           key.ID,
				Name:         key.Name,
				Type:         key.Type,
				Icon:         key.Icon,
				Wrap:         field.Wrap,
				Hidden:       field.Hidden,
				Desc:         key.Desc,
				Calc:         field.Calc,
				Options:      key.Options,
				NumberFormat: key.NumberFormat,
				Template:     key.Template,
				Relation:     key.Relation,
				Rollup:       key.Rollup,
				Date:         key.Date,
				Created:      key.Created,
				Updated:      key.Updated,
			},
		})
	}

	cardsValues := generateAttrViewItems(attrView, view) // 生成卡片
	filterNotFoundAttrViewItems(cardsValues)             // 过滤掉不存在的卡片

	// 批量加载绑定块对应的树
	var ialIDs []string
	for _, keyValues := range cardsValues {
		for _, kValues := range keyValues {
			blockVal := kValues.GetBlockValue()
			if nil != blockVal && !blockVal.IsDetached {
				ialIDs = append(ialIDs, blockVal.Block.ID)
			}
		}
	}
	boundTrees := filesys.LoadTrees(ialIDs)

	// 生成卡片字段值
	for cardID, cardValues := range cardsValues {
		var kanbanCard av.KanbanCard
		for _, field := range ret.Fields {
			var fieldValue *av.KanbanFieldValue
			for _, keyValues := range cardValues {
				if keyValues.Key.ID == field.ID {
					fieldValue = &av.KanbanFieldValue{
						BaseValue: &av.BaseValue{
							ID:        keyValues.Values[0].ID,
							Value:     keyValues.Values[0],
							ValueType: field.Type,
						},
					}
					break
				}
			}
			if nil == fieldValue {
				fieldValue = &av.KanbanFieldValue{
					BaseValue: &av.BaseValue{
						ID:        cardID[:14] + ast.NewNodeID()[14:],
						ValueType: field.Type,
					},
				}
			}
			kanbanCard.ID = cardID

			filedDateIsTime := false
			if nil != field.Date {
				filedDateIsTime = field.Date.FillSpecificTime
			}
			fillAttributeViewBaseValue(fieldValue.BaseValue, field.ID, cardID, field.NumberFormat, field.Template, filedDateIsTime)
			kanbanCard.Values = append(kanbanCard.Values, fieldValue)
		}

		fillAttributeViewKanbanCardCover(attrView, view, cardValues, &kanbanCard, cardID, luteEngine, boundTrees)
		ret.Cards = append(ret.Cards, &kanbanCard)
	}

	// 回填补全数据
	fillAttributeViewKeyValues(attrView, ret)

	// 批量获取块属性以提升性能
	ials := BatchGetBlockAttrsWitTrees(ialIDs, boundTrees)

	// 渲染自动生成的字段值，比如关联、汇总、创建时间和更新时间
	fillAttributeViewAutoGeneratedValues(attrView, ret, ials, depth, cachedAttrViews)

	// 最后渲染模板字段，这样模板就可以使用汇总、关联、创建时间和更新时间的值了
	renderTemplateErr := fillAttributeViewTemplateValues(attrView, view, ret, ials)
	if nil != renderTemplateErr {
		util.PushErrMsg(fmt.Sprintf(util.Langs[util.Lang][44], util.EscapeHTML(renderTemplateErr.Error())), 30000)
	}

	filterByQuery(query, ret)
	manualSort(view, ret)
	return
}

func fillAttributeViewKanbanCardCover(attrView *av.AttributeView, view *av.View, cardValues []*av.KeyValues, kanbanCard *av.KanbanCard, cardID string, luteEngine *lute.Lute, trees map[string]*parse.Tree) {
	switch view.Kanban.CoverFrom {
	case av.CoverFromNone:
	case av.CoverFromContentImage:
		blockValue := getBlockValue(cardValues)
		if blockValue.IsDetached {
			break
		}

		tree := trees[blockValue.Block.ID]
		if nil == tree {
			break
		}
		node := treenode.GetNodeInTree(tree, blockValue.Block.ID)
		if nil == node {
			break
		}

		if ast.NodeDocument == node.Type {
			if titleImg := treenode.GetDocTitleImgPath(node); "" != titleImg {
				kanbanCard.CoverURL = titleImg
				break
			}

			if titleImgCSS := node.IALAttr("title-img"); "" != titleImgCSS {
				kanbanCard.CoverURL = titleImgCSS
				break
			}
		}

		ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
			if !entering {
				return ast.WalkContinue
			}

			if ast.NodeImage != n.Type {
				return ast.WalkContinue
			}

			dest := n.ChildByType(ast.NodeLinkDest)
			if nil == dest {
				return ast.WalkContinue
			}
			kanbanCard.CoverURL = dest.TokensStr()
			return ast.WalkStop
		})

		if "" == kanbanCard.CoverURL {
			kanbanCard.CoverContent = renderCoverContentBlock(node, luteEngine)
			return
		}
	case av.CoverFromAssetField:
		if "" == view.Kanban.CoverFromAssetKeyID {
			break
		}

		assetValue := attrView.GetValue(view.Kanban.CoverFromAssetKeyID, cardID)
		if nil == assetValue || 1 > len(assetValue.MAsset) {
			break
		}

		p := assetValue.MAsset[0].Content
		if util.IsAssetsImage(p) {
			kanbanCard.CoverURL = p
		}
		return
	case av.CoverFromContentBlock:
		blockValue := getBlockValue(cardValues)
		if blockValue.IsDetached {
			break
		}

		tree := trees[blockValue.Block.ID]
		if nil == tree {
			break
		}
		node := treenode.GetNodeInTree(tree, blockValue.Block.ID)
		if nil == node {
			break
		}
		kanbanCard.CoverContent = renderCoverContentBlock(node, luteEngine)
	}
}
