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/linestory"
	"go_dreamfactory/pb"
	"strings"

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

type LinestoryMineView struct {
	BaseformView
	friendList func()
	itemList   *common.ItemList
	flag       bool
}

func (this *LinestoryMineView) CreateView(t *model.TestCase) fyne.CanvasObject {
	jqId := widget.NewEntry()
	jqId.PlaceHolder = "章节ID"

	this.form.AppendItem(widget.NewFormItem("章节ID", jqId))

	mine := func() {
		if err := service.GetPttService().SendToClient(
			t.MainType,
			// linestory.LinestorySubTypeChapter,
			"",
			&pb.LinestoryChapterReq{},
		); err != nil {
			logrus.Error(err)
			return
		}
	}
	defer mine()

	// 进入章节
	this.form.OnSubmit = func() {
		if jqId.Text == "" {
			common.ShowTip("输入章节ID")
			return
		}
		if err := service.GetPttService().SendToClient(
			t.MainType,
			// linestory.LinestorySubTypeMaintask,
			"",
			&pb.LinestoryMaintaskReq{
				ChapterId: cast.ToInt32(jqId.Text),
			},
		); err != nil {
			logrus.Error(err)
			return
		}
	}
	this.form.SubmitText = "进入章节"

	// 章节奖励
	this.form.OnCancel = func() {
		if jqId.Text == "" {
			common.ShowTip("输入章节ID")
			return
		}
		if err := service.GetPttService().SendToClient(
			t.MainType,
			// linestory.LinestorySubTypeReceive,
			"",
			&pb.LinestoryReceiveReq{
				ChapterId: cast.ToInt32(jqId.Text),
			},
		); err != nil {
			logrus.Error(err)
			return
		}
	}
	this.form.CancelText = "领奖励"
	this.dataListener()
	return this.form
}

func (this *LinestoryMineView) 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.ModuleLinestory") &&
				data.SubType == "linestory.LinestorySubTypeMaintask") {
				return
			}
			rsp := &pb.LinestoryMaintaskResp{}

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

			var formatStr strings.Builder
			for _, v := range rsp.List {
				formatStr.WriteString(fmt.Sprintf("%d- %v\n", v.TaskId, v.Status))
			}
			this.res.Text = formatStr.String()
			this.res.Refresh()
		},
	})
	this.flag = true
}
