package windows

import (
	"bsphp/api"
	"bsphp/model"
	"bsphp/windows/login"
	"net/url"
	"sort"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
)

// LoginWindow 登录窗口结构体
type LoginWindow struct {
	app            fyne.App
	window         fyne.Window
	notice         string    // 公告
	api            api.BsPhp // api对象
	isLoginCode    bool      // 是否开启登录验证码
	isRegCode      bool      // 是否开启注册验证码
	isBackCode     bool      // 是否开启找回密码验证码
	isEditCode     bool      // 是否开启修改密码验证码
	isFeedbackCode bool      // 是否开启反馈验证码
}

// NewLoginWindow 创建新的登录窗口c
func NewLoginWindow(a fyne.App) *LoginWindow {
	w := a.NewWindow("登录")
	w.Resize(fyne.NewSize(600, 400))

	lw := &LoginWindow{
		app:    a,
		window: w,
		api: *api.NewBsPhp(
			"http://app.bsphp.com/AppEn.php?appid=82345678&m=9e188d3db15dd4705aecbee4850b4c6a",
			"XVIoRnKSQzrWtXFAfR",
			"0307296d1bad8912c7985061473a6837",
			"POST",
			"in",
			"to",
		),
	}
	// 初始化
	lw.init()
	// 设置表单
	lw.setupUI()
	return lw
}

// 初始化
func (lw *LoginWindow) init() {
	if !lw.api.Connect() {
		dialog.NewConfirm("连接服务器失败", "无法连接到服务器，请检查网络设置或稍后再试。", func(ok bool) {
			lw.app.Quit()
		}, lw.window).Show()
		return
	}
	if !lw.api.GetSeSsl() {
		dialog.NewConfirm("获取SSL失败", "获取BSphpSeSsL失败", func(ok bool) {
			lw.app.Quit()
		}, lw.window).Show()
		return
	}
	lw.notice = lw.api.GetNotice()
	isCode := lw.api.CodeIsOpen("INGES_LOGIN|INGES_RE|INGES_MACK|INGES_SAY")
	if isCode != nil {
		lw.isLoginCode = in("INGES_LOGIN", isCode)
		lw.isRegCode = in("INGES_RE", isCode)
		lw.isBackCode = in("INGES_MACK", isCode)
		lw.isEditCode = in("INGES_SAY", isCode)
		lw.isFeedbackCode = in("INGES_SAY", isCode)
	}

}

// 设置登录表单
func (lw *LoginWindow) setupUI() {
	// 设置公告区
	note := widget.NewCard("公告:", "", widget.NewRichTextWithText(lw.notice))
	// a := widget.NewEntryWithData()
	// a.SetPlaceHolder() = "请输入账号"
	// 设置tabs
	loginTab := login.NewLoginFrom()
	loginTab.SetTestNetwork(lw.TestNetwork)
	loginTab.SetCheckVersion(lw.CheckVersion)
	loginTab.SetLogin(lw.onLogin)
	regTab := login.NewRegForm()
	regTab.SetReg(lw.onReg)
	unBindTab := login.NewUnbindForm()
	unBindTab.SetOnUnbind(lw.onUnbind)
	payTab := login.NewPayForm()
	payTab.SetOnPay(lw.onPay)
	backTab := login.NewBackForm()
	backTab.SetOnBack(lw.onBack)
	editTab := login.NewEditPassForm()
	editTab.SetOnEditPass(lw.onEditPass)

	tabs := container.NewAppTabs(
		container.NewTabItem("登录", container.NewPadded(loginTab)),
		container.NewTabItem("注册", container.NewPadded(regTab)),
		container.NewTabItem("解绑", container.NewPadded(unBindTab)),
		container.NewTabItem("充值", container.NewPadded(payTab)),
		container.NewTabItem("找回密码", container.NewPadded(backTab)),
		container.NewTabItem("修改密码", container.NewPadded(editTab)),
		// container.NewTabItem("意见反馈", img),
	)

	content := container.NewBorder(
		nil, widget.NewCard("", "", tabs), nil, nil,
		note,
	)
	lw.window.SetContent(container.NewPadded(content))
}

// 登录Tab事件
// 1.测试网络连接
func (lw *LoginWindow) TestNetwork() {
	if lw.api.Connect() {
		dialog.NewConfirm("提示", "网络连接成功！", func(b bool) {}, lw.window).Show()
	} else {
		dialog.NewConfirm("提示", "网络连接失败！", func(b bool) {}, lw.window).Show()
	}
}

// 2.检查版本
func (lw *LoginWindow) CheckVersion() {
	version := lw.api.GetVersion()
	//是否是nil
	if version == "" {
		dialog.NewConfirm("提示", "获取版本失败！", func(b bool) {}, lw.window).Show()
	} else {
		if version != "v1.0" {
			dialog.NewConfirm("提示", "您的软件不是最新版本是否更新", func(b bool) {
				if b {
					url, _ := url.Parse(lw.api.GetURL())
					lw.app.OpenURL(url)
				}
			}, lw.window).Show()
		}
	}
}

// 3.登录按钮点击事件
func (lw *LoginWindow) onLogin(data model.LoginData) {
	username, _ := data.Username.Get()
	password, _ := data.Password.Get()
	code, _ := data.Code.Get()

	result := lw.api.Login(username, password, code, "123213", "213123")
	str, ok := result.(string)
	if ok {
		dialog.NewConfirm("错误:", str, func(b bool) {}, lw.window).Show()
	} else {
		lw.window.Close()
		mainWindow := NewMainWindow(lw.app, lw.api)
		mainWindow.Show()
	}
}

// 注册Tab事件
func (lw *LoginWindow) onReg(data model.RegData) {
	username, _ := data.Username.Get()
	password, _ := data.Password.Get()
	rePassword, _ := data.RePassword.Get()
	code, _ := data.Code.Get()
	phone, _ := data.Phone.Get()
	qq, _ := data.QQ.Get()
	email, _ := data.Email.Get()
	question, _ := data.Question.Get()
	answer, _ := data.Answer.Get()
	result := lw.api.Reg(username, password, rePassword, code, phone, question, answer, qq, email, "", "")
	dialog.NewConfirm("提示", result, func(b bool) {}, lw.window).Show()
}

// 解绑Tab事件
func (lw *LoginWindow) onUnbind(data model.UnbindData) {
	username, _ := data.Username.Get()
	password, _ := data.Password.Get()
	result := lw.api.Unbind(username, password)
	dialog.NewConfirm("提示", result, func(b bool) {}, lw.window).Show()
}

// 充值Tab事件
func (lw *LoginWindow) onPay(data model.PayData) {
	username, _ := data.Username.Get()
	password, _ := data.Password.Get()
	card, _ := data.Card.Get()
	cardPass, _ := data.CardPass.Get()
	result := lw.api.Pay(username, password, true, card, cardPass)
	dialog.NewConfirm("提示", result, func(b bool) {}, lw.window).Show()
}

// 找回密码Tab事件
func (lw *LoginWindow) onBack(data model.BackData) {
	username, _ := data.Username.Get()
	password, _ := data.Password.Get()
	rePassword, _ := data.RePassword.Get()
	code, _ := data.Code.Get()
	question, _ := data.Question.Get()
	answer, _ := data.Answer.Get()
	result := lw.api.BackPass(username, password, rePassword, question, answer, code)
	dialog.NewConfirm("提示", result, func(b bool) {}, lw.window).Show()
}

// 修改密码Tab事件
func (lw *LoginWindow) onEditPass(data model.EditPassData) {
	username, _ := data.Username.Get()
	password, _ := data.Password.Get()
	newpass, _ := data.NewPass.Get()
	rePassword, _ := data.RePassword.Get()
	code, _ := data.Code.Get()
	result := lw.api.EditPass(username, password, newpass, rePassword, code)
	dialog.NewConfirm("提示", result, func(b bool) {}, lw.window).Show()
}

// 意见反馈Tab事件
// func (lw *LoginWindow) onFeedback(data model.FeedbackData) {

// }

// 获取验证码
func (lw *LoginWindow) GetCode() []byte {
	return lw.api.GetCode()
}

// 显示登录窗口
func (lw *LoginWindow) Show() {
	lw.window.Show()
}

func in(target string, str_array []string) bool {
	sort.Strings(str_array)
	index := sort.SearchStrings(str_array, target)
	//index的取值：[0,len(str_array)]
	if index < len(str_array) && str_array[index] == target { //需要注意此处的判断，先判断 &&左侧的条件，如果不满足则结束此处判断，不会再进行右侧的判断
		return true
	}
	return false
}
