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/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 GrowtaskListView struct {
	BaseformView
	taskList func(taskType int32)
	itemList *common.ItemList
	flag     bool
}

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

	this.itemList.ItemList = this.itemList.CreateList()
	this.taskList = func(taskType int32) {
		if err := service.GetPttService().SendToClient(
			string("growtask"),
			"",
			// growtask.GrowtaskSubTypeList,
			&pb.GrowtaskListReq{
				TaskType: taskType,
			}); err != nil {
			logrus.Error(err)
		}
	}
	defer this.taskList(1)
	refreshBtn := widget.NewButtonWithIcon("", theme.ViewRefreshIcon(), func() {
		this.itemList.Reset()
		this.taskList(1)
	})

	selTaskType := widget.NewSelect([]string{"初级", "中级", "高级"}, func(s string) {
		switch s {
		case "初级":
			this.itemList.Reset()
			this.taskList(1)
		case "中级":
			this.itemList.Reset()
			this.taskList(2)
		case "高级":
			this.itemList.Reset()
			this.taskList(3)
		}
	})
	selTaskType.Selected = "初级"

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

	// 进阶领取
	advReceiveBtn := widget.NewButton("进阶领奖", func() {
		if err := service.GetPttService().SendToClient(
			string("growtask"),
			// growtask.GrowtaskSubTypeAdvreceive,
			"",
			&pb.GrowtaskAdvReceiveReq{
				TaskType: 1,
			}); err != nil {
			logrus.Error(err)
		}
	})

	buttonBar := container.NewHBox(refreshBtn, selTaskType, receiveBtn, advReceiveBtn)

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

	this.dataListener()
	return c
}

func (this *GrowtaskListView) 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("growtask") &&
				data.SubType == "") {
				return
			}
			rsp := &pb.GrowtaskListResp{}

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

			for _, v := range rsp.TaskList {
				item := common.Item{
					Id:   cast.ToString(v.Id),
					Text: fmt.Sprintf("taskId:%v status:%v", v.Id, v.Status),
				}
				this.itemList.AddItem(item)
			}

		},
	})
	this.flag = true
}
