package ui

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

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"github.com/atotto/clipboard"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
)

type toyUserInfo struct {
	toyAdapter

	dataList   *widget.List
	titleLabel *widget.Label

	userInfo *service.UserInfo

	data       binding.ExternalStringList
	obs        observer.Observer
	copyBtn    *widget.Button
	refreshBtn *widget.Button
	logoutBtn  *widget.Button
}

func (this *toyUserInfo) Init(obs observer.Observer) error {
	this.obs = obs
	this.titleLabel = widget.NewLabel(common.USERINFO_PANEL_TITLE)
	this.data = binding.BindStringList(&[]string{})

	// 复制UID button
	this.copyBtn = widget.NewButtonWithIcon("", theme.ContentCopyIcon(), func() {
		if this.userInfo != nil && this.userInfo.DbUser != nil {
			_ = clipboard.WriteAll(this.userInfo.DbUser.Uid)
			common.ShowTip("已复制UID到剪贴板")
		}
	})
	this.copyBtn.Disable()

	// 刷新
	this.refreshBtn = widget.NewButtonWithIcon("", theme.ViewRefreshIcon(), func() {
		if err := service.GetPttService().SendToClient(
			string("user"),
			"info",
			&pb.UserInfoReq{}); err != nil {
			logrus.Error(err)
			return
		}
	})
	this.refreshBtn.Disable()

	// 注销用户
	this.logoutBtn = widget.NewButtonWithIcon("", theme.AccountIcon(), func() {
		// if err := service.GetPttService().SendToClient(
		// 	string("user"),
		// 	user.UserSubTypeInfo,
		// 	&pb.UserInfoReq{}); err != nil {
		// 	logrus.Error(err)
		// 	return
		// }
	})

	// list
	this.dataList = widget.NewListWithData(this.data,
		func() fyne.CanvasObject {
			return widget.NewLabel("template")
		},
		func(i binding.DataItem, o fyne.CanvasObject) {
			o.(*widget.Label).Bind(i.(binding.String))
		},
	)

	// md
	// sign := widget.NewRichTextFromMarkdown(``)
	// layout
	this.widget = widget.NewCard("", "",
		container.NewBorder(container.NewHBox(this.titleLabel, layout.NewSpacer(), this.logoutBtn, this.refreshBtn, this.copyBtn),
			nil, nil, nil, container.NewVScroll(this.dataList)))
	this.widget.Resize(fyne.NewSize(ToyWidth, 750))

	this.dataListener()
	return nil
}

func (this *toyUserInfo) dataListener() {
	this.obs.AddListener(observer.EVENT_USERINFO, observer.Listener{
		OnNotify: func(d interface{}, args ...interface{}) {
			time.Sleep(time.Millisecond * 50)
			_ = this.data.Set([]string{})
			if this.copyBtn.Disabled() {
				this.copyBtn.Enable()
			}
			if this.refreshBtn.Disabled() {
				this.refreshBtn.Enable()
			}
			this.userInfo = d.(*service.UserInfo)
			if this.userInfo == nil {
				return
			}

			uid = this.userInfo.DbUser.Uid
			// _ = this.data.Append(fmt.Sprintf("%-3s\t: %s", common.USERINFO_UID, this.userInfo.DbUser.Uid))
			_ = this.data.Append(this.getAcc())           //0
			_ = this.data.Append(this.getSid())           //1
			_ = this.data.Append(this.getName())          //2
			_ = this.data.Append(this.getAvatar())        //3
			_ = this.data.Append(this.getVip())           //4
			_ = this.data.Append(this.getLv())            //5
			_ = this.data.Append(this.getGold())          //6
			_ = this.data.Append(this.getExp())           //7
			_ = this.data.Append(this.getDiamond())       //8
			_ = this.data.Append(this.getTitle())         //9
			_ = this.data.Append(this.getActiveDay())     //10
			_ = this.data.Append(this.getActiveWeek())    //11
			_ = this.data.Append(this.getFriendPoint())   //12
			_ = this.data.Append(this.getModiNameCount()) //13
			_ = this.data.Append(this.getCreateTime())
			_ = this.data.Append(this.getSign())   //15
			_ = this.data.Append(this.getBgp())    //16
			_ = this.data.Append(this.getFigure()) //17
			_ = this.data.Append(this.getVit())    //18

			this.setProp(2, common.USERINFO_NAME, this.userInfo.DbUser.Name)
		},
	})

	this.obs.AddListener(observer.EVENT_REQ_RSP, observer.Listener{
		OnNotify: func(d interface{}, args ...interface{}) {
			data := d.(*pb.UserMessage)
			//change name
			if data.MainType == string("user") &&
				data.SubType == "modifyname" {
				rsp := &pb.UserModifynameResp{}
				if !comm.ProtoUnmarshal(data, rsp) {
					logrus.Error("unmarshal err")
					return
				}
				// updatename
				this.setProp(2, common.USERINFO_NAME, rsp.Name)
			}

			//update info
			if data.MainType == string("user") &&
				data.SubType == "info" {
				rsp := &pb.UserInfoResp{}
				if !comm.ProtoUnmarshal(data, rsp) {
					logrus.Error("unmarshal err")
					return
				}

				if rsp.Data == nil {
					logrus.Debug("没有用户数据返回")
				}

				this.setProp(1, common.USERINFO_SERVER, rsp.Data.Sid)
				this.setProp(2, common.USERINFO_NAME, rsp.Data.Name)
				this.setProp(3, common.USERINFO_AVATAR, rsp.Data.Avatar)
				this.setProp(4, common.USERINFO_VIP, rsp.Data.Vip)
				this.setProp(5, common.USERINFO_LV, rsp.Data.Lv)
				this.setProp(6, common.USERINFO_GOLD, rsp.Data.Gold)
				this.setProp(7, common.USERINFO_EXP, rsp.Data.Exp)
				this.setProp(8, common.USERINFO_DIAMOND, rsp.Data.Diamond)
				this.setProp(9, common.USERINFO_TITLE, rsp.Data.Title)
				this.setProp(10, common.USERINFO_ACTIVE_DAY, rsp.Ex.Activeday)
				this.setProp(11, common.USERINFO_ACTIVE_WEEK, rsp.Ex.Activeweek)
				this.setProp(12, common.USERINFO_FRIENDPOINT, rsp.Ex.FriendPoint)
				this.setProp(13, common.USERINFO_MODINAME, rsp.Ex.ModifynameCount)
				this.setProp(13, common.USERINFO_MODINAME, rsp.Ex.ModifynameCount)
				this.setProp(15, common.USERINFO_SIGN, rsp.Ex.Sign)
				this.setProp(16, "背景", rsp.Data.Bgp)
				this.setProp(17, "形象", rsp.Data.Figure)
				this.setProp(18, "体力", rsp.Data.Ps)
			}
		},
	})

	this.obs.AddListener(observer.EVENT_USER_CHANGE, observer.Listener{
		OnNotify: func(d interface{}, args ...interface{}) {
			data := d.(*model.PushModel)
			// listener gold
			if data.Msg.MainType == string("user") &&
				data.Msg.SubType == "reschange" {
				rsp := &pb.UserResChangedPush{}
				if !comm.ProtoUnmarshal(data.Msg, rsp) {
					logrus.Error("unmarshal err")
					return
				}
				// this.setProp(6, common.USERINFO_GOLD, rsp.Gold)
				// this.setProp(7, common.USERINFO_EXP, rsp.Exp)
				// this.setProp(8, common.USERINFO_DIAMOND, rsp.Diamond)
			}
			// listener exp
			// if data.Msg.MainType == string("user") &&
			// 	data.Msg.SubType == "" {
			//TODO change exp
			// }

		},
	})
}

func (this *toyUserInfo) setProp(idx int, label string, val interface{}) {
	// v, _ := this.data.GetValue(idx)
	// if v != "" {
	logrus.WithFields(logrus.Fields{"idx": idx, "lbl": label, "val": val}).Debug("更新Prop")
	if err := this.data.SetValue(idx, fmt.Sprintf("%-3s\t: %v", label, val)); err != nil {
		logrus.WithFields(logrus.Fields{"idx": idx, "val": val}).Error(err)
	}
	// }
}

func (this *toyUserInfo) getAcc() string {
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_ACC, this.userInfo.DbUser.Binduid)
}

func (this *toyUserInfo) getSid() string {
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_SERVER, this.userInfo.DbUser.Sid)
}

func (this *toyUserInfo) getName() string {
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_NAME, this.userInfo.DbUser.Name)
}

func (this *toyUserInfo) getAvatar() string {
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_AVATAR, this.userInfo.DbUser.Avatar)
}

func (this *toyUserInfo) getVip() string {
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_VIP, cast.ToString(this.userInfo.DbUser.Vip))
}

func (this *toyUserInfo) getLv() string {
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_LV, cast.ToString(this.userInfo.DbUser.Lv))
}

func (this *toyUserInfo) getGold() string {
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_GOLD, cast.ToString(this.userInfo.DbUser.Gold))
}

func (this *toyUserInfo) getExp() string {
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_EXP, cast.ToString(this.userInfo.DbUser.Exp))
}

func (this *toyUserInfo) getDiamond() string {
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_DIAMOND, cast.ToString(this.userInfo.DbUser.Diamond))
}

func (this *toyUserInfo) getTitle() string {
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_TITLE, cast.ToString(this.userInfo.DbUser.Exp))
}

func (this *toyUserInfo) getFigure() string {
	return fmt.Sprintf("%-3s\t: %s", "形象", cast.ToString(this.userInfo.DbUser.Figure))
}

func (this *toyUserInfo) getBgp() string {
	return fmt.Sprintf("%-3s\t: %s", "背景", cast.ToString(this.userInfo.DbUser.Bgp))
}

func (this *toyUserInfo) getVit() string {
	return fmt.Sprintf("%-3s\t: %s", "体力", cast.ToString(this.userInfo.DbUser.Ps))
}

func (this *toyUserInfo) getActiveDay() string {
	if this.userInfo.DbUserExpand == nil {
		return fmt.Sprintf("%-3s\t: %s", common.USERINFO_ACTIVE_DAY, cast.ToString(0))
	}
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_ACTIVE_DAY, cast.ToString(this.userInfo.DbUserExpand.Activeday))
}

func (this *toyUserInfo) getActiveWeek() string {
	if this.userInfo.DbUserExpand == nil {
		return fmt.Sprintf("%-3s\t: %s", common.USERINFO_ACTIVE_WEEK, cast.ToString(0))
	}
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_ACTIVE_WEEK, cast.ToString(this.userInfo.DbUserExpand.Activeweek))
}

func (this *toyUserInfo) getFriendPoint() string {
	if this.userInfo.DbUserExpand == nil {
		return fmt.Sprintf("%-3s\t: %s", common.USERINFO_FRIENDPOINT, cast.ToString(0))
	}
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_FRIENDPOINT, cast.ToString(this.userInfo.DbUserExpand.FriendPoint))
}

func (this *toyUserInfo) getModiNameCount() string {
	if this.userInfo.DbUserExpand == nil {
		return fmt.Sprintf("%-3s\t: %s", common.USERINFO_MODINAME, "")
	}
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_MODINAME, cast.ToString(this.userInfo.DbUserExpand.ModifynameCount))
}

func (this *toyUserInfo) getSign() string {
	if this.userInfo.DbUserExpand == nil {
		return fmt.Sprintf("%-3s\t: %s", common.USERINFO_SIGN, "")
	}
	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_SIGN, cast.ToString(this.userInfo.DbUserExpand.Sign))
}

func (this *toyUserInfo) getCreateTime() string {
	ctime := this.userInfo.DbUser.Ctime
	if ctime <= 0 {
		return ""
	}
	tt := time.Unix(ctime, 0)

	return fmt.Sprintf("%-3s\t: %s", common.USERINFO_CREATETM, tt.Format(time.RFC3339))
}
