package rigger

import (
	"fmt"
	"net/http"

	"ciyon/web/admin"
	c "ciyon/zciyon"
)

func Chgpass_update(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, userid := admin.Verifyfast(r, c.CiyDB, post)
	if userid == 0 {
		return false
	}
	oldpass := post.Get("oldpass")
	newpass := post.Get("newpass")
	if oldpass == "" {
		return c.ErrJSON(w, "请输入原密码")
	}
	if newpass == "" {
		return c.ErrJSON(w, "请输入新密码")
	}

	csql := c.NewCiySQL("zc_admin")
	csql.Where("id", userid)
	userrow, err := c.CiyDB.Getone(csql)
	if userrow == nil {
		return c.ErrJSON(w, "遇到读取错误", err)
	}
	if c.Tostr(userrow["password"]) != oldpass {
		return c.ErrJSON(w, "原密码错误")
	}

	err = c.CiyDB.Tran(func() error {
		updata := map[string]any{}
		updata["password"] = newpass
		csql = c.NewCiySQL("zc_admin")
		csql.Where("id", userid)
		_, err = c.CiyDB.Update(csql, updata)
		if err != nil {
			return fmt.Errorf("更新失败:%v", err)
		}
		admin.SaveLog(c.CiyDB, "PASSWORD", "已修改密码")
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, "事务"+err.Error())
	}
	return c.SuccJSON(w, r)
}
