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 TaskListView struct {
	BaseformView
	itemList common.ItemList
	flag     bool
}

func (this *TaskListView) 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 list button
	taskListBtn := widget.NewButtonWithIcon("任务列表", theme.ConfirmIcon(), func() {
		this.itemList.Reset()
		if err := service.GetPttService().SendToClient(t.MainType, t.SubType, &pb.TaskListReq{
			TaskTag: cast.ToInt32(tagSelect.Selected),
		}); err != nil {
			logrus.Error(err)
		}
	})

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

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

	//data listener for
	this.dataListener()

	return split
}

func (this *TaskListView) 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("") &&
				data.SubType == "task.TaskSubTypeList") {
				return
			}

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

			for _, v := range rsp.List {
				item := common.Item{
					Id:   cast.ToString(v.TaskId),
					Text: fmt.Sprintf("%s 是否完成:%d 是否领奖:%d ", cast.ToString(v.TaskId), v.Status, v.Received),
				}
				this.itemList.AddItem(item)
			}
		},
	})
	this.flag = true
}
