package formview

import (
	"errors"
	"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/task"
	"go_dreamfactory/pb"

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

type TaskActiveListView struct {
	BaseformView
	activeVal *widget.Label
	itemList  *common.ItemList
	flag      bool
}

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

	this.itemList.ItemList = this.itemList.CreateList()

	// select widget
	tagSelect := getTaskTagSelect()
	this.form.AppendItem(widget.NewFormItem(common.APP_TESTCASE_FORM_TASKTAG, tagSelect))

	// task active list button
	taskListBtn := widget.NewButtonWithIcon("活跃度", theme.ConfirmIcon(), func() {
		this.itemList.Reset()
		if err := service.GetPttService().SendToClient(t.MainType, t.SubType, &pb.TaskActiveListReq{
			TaskTag: cast.ToInt32(tagSelect.Selected),
		}); err != nil {
			logrus.Error(err)
		}
	})

	//label
	this.activeVal = widget.NewLabel("")

	//receive button
	receiveBtn := widget.NewButtonWithIcon("领取", theme.ConfirmIcon(), func() {
		selItemId := this.itemList.SelItemId
		if selItemId == "" {
			dialog.ShowError(errors.New("请选择一项"), this.w)
			return
		}
		if err := service.GetPttService().SendToClient(
			t.MainType, "activereceive",
			&pb.TaskActiveReceiveReq{Id: cast.ToInt32(selItemId), TaskTag: cast.ToInt32(tagSelect.Selected)}); err != nil {
			logrus.Error(err)
			return
		}
	})

	// layout
	split := container.NewHSplit(this.itemList.ItemList, container.NewVBox(this.activeVal, this.form, taskListBtn, receiveBtn))
	split.Offset = 1

	//data listener for
	this.dataListener()

	return split
}

func (this *TaskActiveListView) 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 == string("comm.ModuleTask") &&
				data.SubType == "task.TaskSubTypeActiveList") {
				return
			}

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

			this.activeVal.SetText(fmt.Sprintf("当前活跃度:%v", rsp.Active))

			for _, v := range rsp.List {
				item := common.Item{
					Id:   cast.ToString(v.TaskId),
					Text: fmt.Sprintf("任务ID:%s 领取状态:%d", cast.ToString(v.TaskId), v.Received),
				}
				this.itemList.AddItem(item)
			}
		},
	})

	this.flag = true
}
