package formview

import (
	"fmt"
	"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/sociaty"
	"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"
	"github.com/spf13/cast"
)

type SociatyTasklistView struct {
	BaseformView
	taskList         func()
	itemList         *common.ItemList
	flag             bool
	activityItemList *common.ItemList
}

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

	this.taskList = func() {
		this.itemList.Reset()
		if err := service.GetPttService().SendToClient(
			"sociaty",
			"tasklist",
			&pb.SociatyTaskListReq{}); err != nil {
			logrus.Error(err)
		}
	}

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

	// 领取
	receiveBtn := widget.NewButton("领取", func() {
		selId := this.itemList.SelItemId
		if selId == "" {
			common.ShowTip("请选择项目")
			return
		}
		if err := service.GetPttService().SendToClient(
			"sociaty",
			"receive",
			&pb.SociatyReceiveReq{
				TaskId: cast.ToInt32(selId),
			}); err != nil {
			logrus.Error(err)
		}
	})

	// activityVal := canvas.NewText("0", nil)
	buttonBar := container.NewHBox(refreshBtn, receiveBtn)

	c1 := container.NewBorder(buttonBar, nil, nil, nil, this.itemList.ItemList)
	// c2 := container.NewBorder(container.NewVBox(container.NewCenter(activityVal), activityBtn), nil, nil, nil, this.activityItemList.ItemList)
	// cols := container.NewGridWithColumns(2, c1, c2)
	this.dataListener()
	return c1
}

func (this *SociatyTasklistView) dataListener() {
	if this.flag {
		return
	}

	this.obs.AddListener(observer.EVENT_REQ_RSP, observer.Listener{
		OnNotify: func(d interface{}, args ...interface{}) {
			data := d.(*pb.UserMessage)
			if !(data.MainType == "sociaty" &&
				data.SubType == "tasklist") {
				return
			}

			rsp := &pb.SociatyTaskListResp{}
			if !comm.ProtoUnmarshal(data, rsp) {
				logrus.Error("unmarshal err")
				return
			}

			for i, v := range rsp.List {
				item := common.Item{
					Id:   cast.ToString(v.TaskId),
					Text: fmt.Sprintf("%d - Id:%v 状态:%d ", i+1, v.TaskId, v.Status),
				}
				this.itemList.AddItem(item)
			}
		},
	})
	this.flag = true
}
