package formview

import (
	"go_dreamfactory/cmd/v2/model"
	"go_dreamfactory/cmd/v2/service"
	// "go_dreamfactory/comm"
	"go_dreamfactory/pb"
	"go_dreamfactory/utils"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/widget"
	"github.com/sirupsen/logrus"
)

type ListBaseView struct {
	BaseformView
	dataListWidget *widget.List
	dataBinding    binding.UntypedList
	selItemIds     []string //选择的ID
	itemListData   *model.ItemModelList
}

// init data
func (this *ListBaseView) initItemList() {
	this.dataBinding = binding.NewUntypedList()
	this.itemListData = model.NewItemModelList()
}

// create list view with check widget
func (this *ListBaseView) createItemListWithCheck() *widget.List {
	this.dataListWidget = widget.NewListWithData(this.dataBinding,
		func() fyne.CanvasObject {
			return container.NewHBox(
				widget.NewCheck("", func(b bool) {}),
				widget.NewLabelWithStyle("", fyne.TextAlignCenter, fyne.TextStyle{}),
			)
		},
		func(data binding.DataItem, item fyne.CanvasObject) {
			o, _ := data.(binding.Untyped).Get()
			pd := o.(*model.ItemModel)
			item.(*fyne.Container).Objects[0].(*widget.Check).OnChanged = func(b bool) {
				if b {
					this.selItemIds = append(this.selItemIds, pd.Id)
				} else {
					utils.DeleteString(this.selItemIds, pd.Id)
				}
			}
			item.(*fyne.Container).Objects[1].(*widget.Label).SetText(pd.Label)
		},
	)
	return this.dataListWidget
}

// create list , single select
func (this *ListBaseView) createItemList() *widget.List {
	this.dataListWidget = widget.NewListWithData(this.dataBinding,
		func() fyne.CanvasObject {
			return container.NewHBox(
				widget.NewLabelWithStyle("", fyne.TextAlignCenter, fyne.TextStyle{}),
			)
		},
		func(data binding.DataItem, item fyne.CanvasObject) {
			o, _ := data.(binding.Untyped).Get()
			pd := o.(*model.ItemModel)
			item.(*fyne.Container).Objects[0].(*widget.Label).SetText(pd.Label)
		},
	)

	// single select
	this.dataListWidget.OnSelected = func(id widget.ListItemID) {
		sel := this.itemListData.DataList[id]
		this.selItemIds = []string{sel.Id}
	}

	return this.dataListWidget
}

func (this *ListBaseView) listBtnFun() func() {
	return func() {
		if err := service.GetPttService().SendToClient(
			string("friend"),
			// friend.FriendSubTypeApplyList,
			"",
			&pb.FriendApplyListReq{}); err != nil {
			logrus.Error(err)
		}
		this.itemListData = model.NewItemModelList()
	}
}

// set data
func (this *ListBaseView) reloadListData() {
	if this.itemListData != nil {
		d := this.itemListData.AsInterfaceArray()
		this.dataBinding.Set(d)
	}
}
