package formview

import (
	"bufio"
	"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/hero"
	"go_dreamfactory/pb"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/layout"
	fyne_storage "fyne.io/fyne/v2/storage"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
)

type HeroZhaomuView struct {
	BaseformView
	flag           bool
	exportFolder   *widget.Entry
	resultCountLbl *widget.Label
	resultCount    int
	f              *os.File
}

// 打开目录
func openFolder(entry *widget.Entry, w fyne.Window) {
	dConf := dialog.NewFolderOpen(func(lu fyne.ListableURI, err error) {
		if lu == nil {
			return
		}
		entry.Text = lu.Path()
		entry.Refresh()
	}, w)
	luri, _ := fyne_storage.ListerForURI(fyne_storage.NewFileURI("."))
	dConf.SetLocation(luri)
	dConf.SetConfirmText("打开")
	dConf.SetDismissText("取消")
	dConf.Resize(fyne.NewSize(750, 500))
	dConf.Show()
}

func (this *HeroZhaomuView) CreateView(t *model.TestCase) fyne.CanvasObject {

	var ckType, ckCount string
	// 抽卡类型  0 1 2 3 4
	ckTypeSelect := widget.NewSelect([]string{"普通", "魔法", "功夫", "科技", "月能"}, func(s string) {
		switch s {
		case "普通":
			ckType = "0"
		case "魔法":
			ckType = "1"
		case "功夫":
			ckType = "2"
		case "科技":
			ckType = "3"
		case "月能":
			ckType = "4"
		default:
			ckType = "0"
		}

	})
	ckTypeSelect.Selected = "选择"

	//数量
	ckCountSelect := widget.NewSelect([]string{"单抽", "十连抽"}, func(s string) {
		if s == "单抽" {
			ckCount = "1"
		} else if s == "十连抽" {
			ckCount = "10"
		}
	})
	ckCountSelect.Selected = "选择"

	//循环次数
	loopCount := widget.NewEntry()
	loopCount.PlaceHolder = "循环抽卡次数"

	//结果导出目录
	this.exportFolder = widget.NewEntry()
	this.exportFolder.PlaceHolder = "请选择保存结果的目录"

	form := widget.NewForm(
		widget.NewFormItem("抽卡类型", ckTypeSelect),
		widget.NewFormItem("单抽/十连", ckCountSelect),
		widget.NewFormItem("循环次数", loopCount),
		widget.NewFormItem("导出", container.NewBorder(nil, nil, nil,
			widget.NewButtonWithIcon("", theme.FolderIcon(), func() {
				openFolder(this.exportFolder, this.w)
			}), this.exportFolder)),
	)
	form.Items[3].HintText = "文件名默认result.txt"

	choukaBtnFunc := func() {
		if ckTypeSelect.Selected == "选择" {
			common.ShowTip("请选择抽卡类型")
			return
		}

		if ckCountSelect.Selected == "选择" {
			common.ShowTip("请选择单抽/十连")
			return
		}
		if err := service.GetPttService().SendToClient(t.MainType, t.SubType,
			&pb.HeroDrawCardReq{
				DrawType:  cast.ToInt32(ckType),
				DrawCount: cast.ToInt32(ckCount),
			}); err != nil {
			logrus.Error(err)
		}
	}
	choukaBtn := widget.NewButton("抽卡", choukaBtnFunc)
	choukaBtn.Importance = widget.HighImportance

	this.resultCountLbl = widget.NewLabel("共抽卡:")
	//抽卡并导出结果
	choukaAndExport := func() {
		this.resultCount = 0
		if loopCount.Text == "" || cast.ToInt(loopCount.Text) <= 0 {
			common.ShowTip("请设置正确的循环次数")
			return
		}
		if this.exportFolder.Text == "" {
			common.ShowTip("请设置导出目录")
			return
		}
		filePath := filepath.Join(this.exportFolder.Text, "result.txt")
		var err error
		this.f, err = os.OpenFile(filePath, os.O_CREATE|os.O_APPEND|os.O_RDWR, os.ModeAppend|os.ModePerm)
		if err != nil {
			logrus.Error(err.Error())
			return
		}
		defer this.f.Close()

		for i := 0; i < cast.ToInt(loopCount.Text); i++ {
			choukaBtnFunc()
			time.Sleep(time.Millisecond * 20)
		}
	}

	choukaAndExportBtn := widget.NewButton("抽卡并导出", choukaAndExport)
	choukaAndExportBtn.Importance = widget.MediumImportance

	openExplor := func(dir string) {
		if dir == "" {
			common.ShowTip("资源管理器路径错误")
			return
		}
		if runtime.GOOS == "windows" {
			if err := exec.Command("explorer", filepath.Join(dir)).Start(); err != nil {
				dialog.ShowError(errors.WithMessage(err, "请确认Json目录是否填写正确"), this.w)
				return
			}
		}
	}
	//资源目录
	explorBtn := widget.NewButtonWithIcon("打开目录", theme.FolderIcon(), func() {
		openExplor(this.exportFolder.Text)
	})
	explorBtn.Importance = widget.LowImportance

	btns := container.NewHBox(this.resultCountLbl, layout.NewSpacer(), explorBtn, choukaAndExportBtn, choukaBtn)
	c := container.NewBorder(nil, btns, nil, nil, form)
	this.resListener()
	return c
}

// 监听抽卡结果
func (this *HeroZhaomuView) resListener() {
	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("hero") &&
				data.SubType == " hero.DrawCard") {
				return
			}

			rsp := &pb.HeroDrawCardResp{}

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

			write := bufio.NewWriterSize(this.f, 1024)
			for _, v := range rsp.Data {
				for _, o := range v.Atno {
					if o.A == "hero" && o.T != "" {
						logrus.Debug(o.T)
						write.WriteString(o.T + "\r\n")
					}
				}
				this.resultCount++
				this.resultCountLbl.SetText("共抽卡:" + cast.ToString(this.resultCount))
				this.resultCountLbl.Refresh()
			}
			write.Flush()
		},
	})

	this.flag = true
}
