package formview

import (
	"go_dreamfactory/cmd/v2/lib/common"
	"go_dreamfactory/cmd/v2/model"
	"go_dreamfactory/cmd/v2/service"
	"go_dreamfactory/cmd/v2/service/observer"
	"go_dreamfactory/comm"

	// "go_dreamfactory/modules/friend"
	"go_dreamfactory/pb"

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

// 好友审批
type FriendAgreeView struct {
	BaseformView
	itemList common.ItemList
	flag     bool
	greeList func()
}

func (this *FriendAgreeView) CreateView(t *model.TestCase) fyne.CanvasObject {
	this.itemList = *common.NewItemList()

	this.itemList.ItemList = this.itemList.CreateDefaultCheckList()

	this.greeList = func() {
		if err := service.GetPttService().SendToClient(
			string("friend"),
			"",
			&pb.FriendApplyListReq{}); err != nil {
			logrus.Error(err)
		}
	}
	defer this.greeList()

	refreshBtn := widget.NewButtonWithIcon("", theme.ViewRefreshIcon(), func() {
		this.itemList.Reset()
		this.greeList()
	})

	//同意提交
	agreeBtn := widget.NewButtonWithIcon("同意", theme.ConfirmIcon(), func() {
		if len(this.itemList.SelItemIds) == 0 {
			common.ShowTip("请选择项目")
			return
		}
		logrus.Debug(this.itemList.SelItemIds)
		if err := service.GetPttService().SendToClient(
			t.MainType,
			t.SubType,
			&pb.FriendAgreeReq{
				FriendIds: this.itemList.SelItemIds,
			},
		); err != nil {
			logrus.Error(err)
			return
		}
	})

	//拒绝
	refuseBtn := widget.NewButtonWithIcon("拒绝", theme.CancelIcon(), func() {
		if len(this.itemList.SelItemIds) == 0 {
			common.ShowTip("请选择项目")
			return
		}
		if err := service.GetPttService().SendToClient(
			string("friend"),
			"",
			&pb.FriendRefuseReq{
				FriendIds: this.itemList.SelItemIds,
			}); err != nil {
			logrus.Error(err)
			return
		}

	})

	// layout
	buttonBar := container.NewHBox(refreshBtn, agreeBtn, refuseBtn)

	c := container.NewBorder(buttonBar, nil, nil, nil, this.itemList.ItemList)

	this.dataListener()
	return c
}

// listener applyListdata
func (this *FriendAgreeView) dataListener() {
	this.obs.AddListener(observer.EVENT_REQ_RSP, observer.Listener{
		OnNotify: func(d interface{}, args ...interface{}) {
			data := d.(*pb.UserMessage)
			if !(data.MainType == string("friend") &&
				data.SubType == "") {
				return
			}
			rsp := &pb.FriendApplyListResp{}

			if !comm.ProtoUnmarshal(data, rsp) {
				logrus.Error("unmarshal err")
				return
			}

			for _, v := range rsp.List {
				item := common.Item{
					Id:   v.UserId,
					Text: v.NickName,
				}
				this.itemList.AddItem(item)
			}
		},
	})
}
