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/hero"

	"go_dreamfactory/pb"
	"time"

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

type SociatyBossView struct {
	BaseformView

	itemList            common.ItemList
	rankItemList        common.ItemList //排行榜
	heroListFlag        bool
	teamFlag            bool
	bossFlag            bool
	rankFlag            bool
	heroList            func()
	rankList            func()
	sociatyId           string
	teams               map[int32]*pb.ChallengeTeam
	endTimeLabel        *widget.Label // 赛季结束时间
	settleTimeLabel     *widget.Label // 赛季结算时间
	sociatyRankingLabel *widget.Label // 公会排名
	personRankingLabel  *widget.Label // 个人排名
	ticketLabel         *widget.Label //挑战券
}

func (s *SociatyBossView) CreateView(t *model.TestCase) fyne.CanvasObject {
	s.teams = make(map[int32]*pb.ChallengeTeam)
	s.endTimeLabel = widget.NewLabel("")
	s.settleTimeLabel = widget.NewLabel("")
	s.sociatyRankingLabel = widget.NewLabel("")
	s.personRankingLabel = widget.NewLabel("")
	s.ticketLabel = widget.NewLabel("")

	loadSociaty := func() {
		if err := service.GetPttService().SendToClient(
			t.MainType,
			"",
			&pb.SociatyMineReq{},
		); err != nil {
			logrus.Error(err)
			return
		}
	}
	defer loadSociaty()

	loadSociatyBoss := func() {
		if err := service.GetPttService().SendToClient(
			t.MainType,
			"",
			&pb.SociatyBMainReq{},
		); err != nil {
			logrus.Error(err)
			return
		}
	}
	defer loadSociatyBoss()

	buzhenBtn := widget.NewButton("布阵", s.buzhen)
	challengestartBtn := widget.NewButton("开始挑战", s.challengestart)
	challengefinishBtn := widget.NewButton("挑战结束", s.challengefinish)
	ticketBuyBtn := widget.NewButton("挑战券", s.buy)
	rankBtn := widget.NewButton("排行榜", s.rank)
	btns := container.NewHBox(buzhenBtn, challengestartBtn, challengefinishBtn, ticketBuyBtn, rankBtn)
	bottomLabels := container.NewHBox(
		s.ticketLabel, s.settleTimeLabel, s.endTimeLabel,
	)
	leftLabels := container.NewHBox(
		s.personRankingLabel,
		s.sociatyRankingLabel,
	)
	c := container.NewBorder(btns, bottomLabels, leftLabels, nil)

	s.listenTeams()
	s.listenBossmain()
	return c
}

//加载team数据
func (s *SociatyBossView) listenTeams() {
	if s.teamFlag {
		return
	}
	s.obs.AddListener(observer.EVENT_REQ_RSP, observer.Listener{
		OnNotify: func(d interface{}, args ...interface{}) {
			data := d.(*pb.UserMessage)
			if !(data.MainType == string("sociaty") &&
				data.SubType == "") {
				return
			}
			rsp := &pb.SociatyMineResp{}

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

			if rsp.Sociaty != nil {
				s.sociatyId = rsp.Sociaty.Id
				// s.teams = rsp.Teams
			}

		},
	})
	s.teamFlag = true
}

func (s *SociatyBossView) listenBossmain() {
	if s.bossFlag {
		return
	}

	s.obs.AddListener(observer.EVENT_REQ_RSP, observer.Listener{
		OnNotify: func(d interface{}, args ...interface{}) {
			data := d.(*pb.UserMessage)
			if !(data.MainType == string("sociaty") &&
				data.SubType == "") {
				return
			}
			rsp := &pb.SociatyBMainResp{}

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

			s.teams = rsp.Teams
			s.endTimeLabel.SetText(
				fmt.Sprintf("结束:%s", time.Unix(int64(rsp.EndTime), 0).Format("01-02 15:04:05")),
			)
			s.endTimeLabel.Refresh()
			s.settleTimeLabel.SetText(
				fmt.Sprintf("结算:%s", time.Unix(int64(rsp.SettlementTime), 0).Format("01-02 15:04:05")),
			)
			s.settleTimeLabel.Refresh()

			s.ticketLabel.SetText(
				fmt.Sprintf("挑战券:%d", rsp.Ticket),
			)
			s.ticketLabel.Refresh()

			s.sociatyRankingLabel.SetText(
				fmt.Sprintf("公会排名:%d", rsp.SociatyRanking),
			)
			s.sociatyRankingLabel.Refresh()

			s.personRankingLabel.SetText(
				fmt.Sprintf("个人排名:%d", rsp.PersonalRanking),
			)
			s.personRankingLabel.Refresh()
		},
	})
	s.bossFlag = true
}

// 挑战开始
func (s *SociatyBossView) challengestart() {
	if err := service.GetPttService().SendToClient(
		string("sociaty"),
		"",
		&pb.SociatyBChallengeStartReq{
			SociatyId: s.sociatyId,
		},
	); err != nil {
		logrus.Error(err)
		return
	}
}

// 挑战结束
func (s *SociatyBossView) challengefinish() {
	if err := service.GetPttService().SendToClient(
		string("sociaty"),
		"",
		&pb.SociatyBChallengeFinishReq{
			Ptype: pb.PlayType_sociaty,
			Report: &pb.BattleReport{
				Costtime: 180,    //游戏耗时
				Harm:     180300, //伤害值
			},
		},
	); err != nil {
		logrus.Error(err)
		return
	}
}

// 购买挑战券
func (s *SociatyBossView) buy() {
	ticketEntry := widget.NewEntry()
	layout := widget.NewForm(widget.NewFormItem("数量", ticketEntry))
	layout.OnSubmit = func() {
		if ticketEntry.Text == "" || ticketEntry.Text == "0" {
			common.ShowTip("数量不正确")
			return
		}
		if err := service.GetPttService().SendToClient(
			string("sociaty"),
			"",
			&pb.SociatyBuyReq{
				Atn: &pb.UserAssets{
					// A: comm.AttrType,
					// T: comm.ResDiamond,
					N: cast.ToInt32(ticketEntry.Text),
				},
			},
		); err != nil {
			logrus.Error(err)
			return
		}
	}
	dconf := dialog.NewCustom("购买挑战券", "关闭", layout, s.w)
	dconf.Resize(fyne.NewSize(800, 500))
	dconf.Show()
}

//布阵
func (s *SociatyBossView) buzhen() {
	//英雄列表
	s.itemList = *common.NewItemList()
	s.itemList.ItemList = s.itemList.CreateDefaultCheckList()

	s.heroList = func() {
		if err := service.GetPttService().SendToClient(string("hero"), "list", &pb.HeroListReq{}); err != nil {
			logrus.Error(err)
			return
		}
	}
	defer s.heroList()
	s.HeroDataListener()

	//队伍数据

	addHero1 := widget.NewButton("添加至一队", nil)
	addHero2 := widget.NewButton("添加至二队", nil)
	addHero3 := widget.NewButton("添加至三队", nil)
	saveBuzhen := widget.NewButton("保存布阵", nil)

	btns := container.NewHBox(addHero1, addHero2, addHero3, saveBuzhen)
	content := container.NewGridWithRows(3)
	team1 := container.NewGridWithColumns(5)
	//refresh team1
	team1Box := container.NewHBox(widget.NewLabel("一队:"), team1)
	if t, ok := s.teams[1]; ok {
		for _, heroId := range t.Formation.Format {
			team1.AddObject(widget.NewLabel(common.LastChars(heroId, 4)))
		}
	}

	team2 := container.NewGridWithColumns(5)
	team2Box := container.NewHBox(widget.NewLabel("二队:"), team2)
	team3 := container.NewGridWithColumns(5)
	team3Box := container.NewHBox(widget.NewLabel("三队:"), team3)

	content.AddObject(team1Box)
	content.AddObject(team2Box)
	content.AddObject(team3Box)

	// 添加一队英雄
	addHero1.OnTapped = func() {
		team1 = container.NewGridWithColumns(5)
		if t, ok := s.teams[1]; ok {
			for _, heroId := range t.Formation.Format {
				team1.AddObject(widget.NewLabel(common.LastChars(heroId, 4)))
			}
		}
		bf := &pb.BattleFormation{}
		for _, id := range s.itemList.SelItemIds {
			team1.AddObject(widget.NewLabel(common.LastChars(id, 4)))
			bf.Format = append(bf.Format, id)
		}
		if s.teams == nil {
			s.teams = make(map[int32]*pb.ChallengeTeam)
		}
		s.teams[1] = &pb.ChallengeTeam{Formation: bf}
		team1.Refresh()
		team1Box.Refresh()
	}

	// 添加二队英雄
	addHero2.OnTapped = func() {
		team2 = container.NewGridWithColumns(5)
		if t, ok := s.teams[2]; ok {
			for _, heroId := range t.Formation.Format {
				team2.AddObject(widget.NewLabel(common.LastChars(heroId, 4)))
			}
		}
		bf := &pb.BattleFormation{}
		for _, id := range s.itemList.SelItemIds {
			team2.AddObject(widget.NewLabel(common.LastChars(id, 4)))
			bf.Format = append(bf.Format, id)
		}
		if s.teams == nil {
			s.teams = make(map[int32]*pb.ChallengeTeam)
		}
		s.teams[2] = &pb.ChallengeTeam{Formation: bf}
	}

	// 添加三队英雄
	addHero3.OnTapped = func() {
		team3 = container.NewGridWithColumns(5)
		if t, ok := s.teams[3]; ok {
			for _, heroId := range t.Formation.Format {
				team3.AddObject(widget.NewLabel(common.LastChars(heroId, 4)))
			}
		}
		bf := &pb.BattleFormation{}
		for _, id := range s.itemList.SelItemIds {
			team3.AddObject(widget.NewLabel(common.LastChars(id, 4)))
			bf.Format = append(bf.Format, id)
		}
		if s.teams == nil {
			s.teams = make(map[int32]*pb.ChallengeTeam)
		}
		s.teams[3] = &pb.ChallengeTeam{Formation: bf}
	}

	// 保存阵容
	saveBuzhen.OnTapped = func() {
		// var fs []*pb.BattleFormation
		// for _, v := range s.teams {
		// 	heroIds := []string{}
		// 	for _, id := range v.Infos {
		// 		heroIds = append(heroIds, id.HeroId)
		// 	}
		// 	fs = append(fs, &pb.BattleFormation{
		// 		Format: heroIds,
		// 	})
		// }
		if err := service.GetPttService().SendToClient(string("sociaty"),
			"", &pb.SociatyBFormationReq{
				SociatyId: s.sociatyId,
				Teams:     s.teams,
			}); err != nil {
			logrus.Error(err)
			return
		}
	}

	split := container.NewHSplit(s.itemList.ItemList, content)
	split.Offset = 0.55
	layout := container.NewBorder(btns, nil, nil, nil, split)
	dconf := dialog.NewCustom("布阵", "关闭", layout, s.w)
	dconf.Resize(fyne.NewSize(800, 500))
	dconf.Show()
}

// 排行榜
func (s *SociatyBossView) rank() {
	s.rankItemList = *common.NewItemList()
	s.rankItemList.ItemList = s.itemList.CreateList()

	s.rankList = func() {
		if err := service.GetPttService().SendToClient(string("sociaty"), "brank", &pb.SociatyBRankReq{
			RankType: 1,
		}); err != nil {
			logrus.Error(err)
			return
		}
	}
	defer s.rankList()

	layout := container.NewBorder(nil, nil, nil, nil, s.rankItemList.ItemList)

	dconf := dialog.NewCustom("排行榜", "关闭", layout, s.w)
	dconf.Resize(fyne.NewSize(800, 500))
	dconf.Show()
	s.listenRank()
}

func (this *SociatyBossView) listenRank() {
	if this.rankFlag {
		return
	}

	this.obs.AddListener(observer.EVENT_REQ_RSP, observer.Listener{
		OnNotify: func(d interface{}, args ...interface{}) {
			data := d.(*pb.UserMessage)
			if !(data.MainType == string("sociaty") &&
				data.SubType == "") {
				return
			}

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

			for _, v := range rsp.Rank {
				item := common.Item{
					Text: fmt.Sprintf("%d 昵称:%v 公会:%s Lv:%d 积分:%d",
						v.Ranking, v.Name, v.SociatyName, v.Lv, v.Integral),
				}
				this.itemList.AddItem(item)
			}
		},
	})

	this.rankFlag = true
}

func (this *SociatyBossView) HeroDataListener() {
	if this.heroListFlag {
		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 == "") {
				return
			}
			rsp := &pb.HeroListResp{}

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

			for i, v := range rsp.List {
				item := common.Item{
					Id: v.Id,
					Text: fmt.Sprintf("%d ID:%v Star:%d Lv:%d Type:%d Count:%d",
						i+1, v.HeroID, v.Star, v.Lv, v.CardType, v.SameCount),
				}
				this.itemList.AddItem(item)
			}
		},
	})
	this.heroListFlag = true
}
