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

	jsoniter "github.com/json-iterator/go"

	"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"
)

type SociatyListView struct {
	sociatyList func()
	BaseformView
	itemList   *common.ItemList
	flag       bool
	detailFlag bool
}

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

	this.itemList.ItemList = this.itemList.CreateList()

	this.itemList.ItemList.OnSelected = func(id widget.ListItemID) {
		item := this.itemList.CachedList.Items[id]
		this.itemList.SelItemId = item.Id
		logrus.Debug(item)
		if s, ok := item.Data.(*pb.DBSociaty); ok {
			this.res.Text, _ = jsoniter.MarshalToString(s)
		}
	}

	this.sociatyList = func() {
		this.itemList.Reset()
		if err := service.GetPttService().SendToClient(
			"sociaty",
			"list",
			&pb.SociatyListReq{}); err != nil {
			logrus.Error(err)
		}
	}
	defer this.sociatyList()

	refreshBtn := widget.NewButtonWithIcon("", theme.ViewRefreshIcon(), func() {
		this.itemList.Reset()
		this.sociatyList()
	})

	// 申请
	applyBtn := widget.NewButton("申请", func() {
		selId := this.itemList.SelItemId
		if selId == "" {
			common.ShowTip("请选择要申请的公会")
			return
		}
		logrus.Debugf("%s", selId)
		if err := service.GetPttService().SendToClient(
			t.MainType,
			"apply",
			&pb.SociatyApplyReq{
				SociatyId: selId,
			},
		); err != nil {
			logrus.Error(err)
			return
		}
	})
	//取消申请
	cancalApplyBtn := widget.NewButton("取消申请", func() {
		selId := this.itemList.SelItemId
		if selId == "" {
			common.ShowTip("请选择项目")
			return
		}
		if err := service.GetPttService().SendToClient(
			"sociaty",
			"applycancel",
			&pb.SociatyApplyCancelReq{
				SociatyId: selId,
			}); err != nil {
			logrus.Error(err)
		}
	})

	//过滤
	filter := widget.NewSelect([]string{"全部", "满足条件", "无需审批", "申请中"}, func(s string) {
		this.itemList.Reset()
		var filter pb.SociatyListFilter
		if s == "全部" {
			filter = pb.SociatyListFilter_ALL
		} else if s == "满足条件" {
			filter = pb.SociatyListFilter_CONDI
		} else if s == "无需审批" {
			filter = pb.SociatyListFilter_NOAPPLY
		} else if s == "申请中" {
			filter = pb.SociatyListFilter_APPLYING
		}
		if err := service.GetPttService().SendToClient(
			"sociaty",
			"list",
			&pb.SociatyListReq{
				Filter: filter,
			}); err != nil {
			logrus.Error(err)
		}
	})
	filter.Selected = "全部"

	//搜索
	searchEntry := widget.NewEntry()
	searchEntry.PlaceHolder = "输入公会名称"
	searchBtn := widget.NewButtonWithIcon("", theme.SearchIcon(), func() {
		if searchEntry.Text == "" {
			common.ShowTip("请输入公会名称")
			return
		}
		this.itemList.Reset()
		if err := service.GetPttService().SendToClient(
			"sociaty",
			"search",
			&pb.SociatySearchReq{
				Name: searchEntry.Text,
			}); err != nil {
			logrus.Error(err)
		}
	})

	buttonBar := container.NewHBox(refreshBtn, applyBtn, cancalApplyBtn, filter)
	cBar := container.NewBorder(nil, nil, buttonBar, searchBtn, searchEntry)
	// layout
	c := container.NewBorder(cBar, nil, nil, nil, this.itemList.ItemList)
	//data listener for
	this.dataListener()
	return c
}

func (this *SociatyListView) 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 == "sociaty" &&
				data.SubType == "list" {
				rsp := &pb.SociatyListResp{}

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

				for i, v := range rsp.List {
					dsociaty := v.DbSociaty
					memberCount := len(dsociaty.Members)

					var isApplyCheckLbl string
					if dsociaty.IsApplyCheck {
						isApplyCheckLbl = "需要审核"
					} else {
						isApplyCheckLbl = "无需审核"
					}
					lbl := fmt.Sprintf("%d - %-15s 等级:%-5d 等级限制:%-5d (%d) %10v",
						i+1, dsociaty.Name, dsociaty.Lv, dsociaty.ApplyLv, memberCount, isApplyCheckLbl)
					item := common.Item{
						Id:   dsociaty.Id,
						Text: lbl,
						Data: v,
					}
					this.itemList.AddItem(item)
				}
			} else if data.MainType == "sociaty" &&
				data.SubType == "search" {
				rsp := &pb.SociatySearchResp{}

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

				for i, v := range rsp.List {
					memberCount := len(v.Members)

					item := common.Item{
						Id:   v.Id,
						Text: fmt.Sprintf("%d - %s 等级:%d 等级限制:%d %d人", i+1, v.Name, v.Lv, v.ApplyLv, memberCount),
					}
					this.itemList.AddItem(item)
				}
			}

		},
	})
	this.flag = true
}

// 显示公会明细
func (this *SociatyListView) showSociatyDetailWin() {
	c := container.NewBorder(nil, nil, nil, nil, this.form)
	dconf := dialog.NewCustom("公会详情", "关闭", c, this.w)
	dconf.Resize(fyne.NewSize(800, 500))
	dconf.Show()
	this.form.Refresh()
}

func (this *SociatyListView) formdataListen(item *entryItem) {
	if this.detailFlag {
		return
	}
	this.obs.AddListener(observer.EVENT_REQ_RSP, observer.Listener{
		OnNotify: func(d interface{}, args ...interface{}) {
			data := d.(*pb.UserMessage)
			if !(data.MainType == "sociaty" &&
				data.SubType == "mine") {
				return
			}
			rsp := &pb.SociatyMineResp{}

			if rsp.Sociaty == nil {
				return
			}
			logrus.Debug(rsp.Sociaty)
			item.sociatyName.Text = rsp.Sociaty.Name
			item.notice.Text = rsp.Sociaty.Notice

			this.form.Refresh()
		},
	})
	this.detailFlag = true
}
