package customer

import (
	"errors"
	"net/http"
	"spaceofcheng/services/controllers"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/service/customer"
	"spaceofcheng/services/utils"
)

// CustomerController 用户
type CustomerController struct {
	serv *customer.CustomerServ
	controllers.BaseController
}

// Constructor 初始化 Controller
// @Title Constructor
// @Description 初始化 Controller, 系统自动调用
func (c *CustomerController) Constructor() {
	c.serv = customer.NewCustomerServ(c.Context)
}

// CustWXList 获取客户列表
func (c *CustomerController) CustWXList() {
	phone := c.GetString("phone")
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pagesize")

	custList, total, err := c.serv.GetCustWithWXList(phone, page, pageSize)
	if err != nil {
		utils.LogError("获取客户列表失败: " + err.Error())
		c.ResponseError(
			errors.New("获取客户列表失败"),
			http.StatusInternalServerError,
		)
	}

	c.ResponseJSON(map[string]interface{}{
		"list":     custList,
		"pagenum":  total,
		"page":     page,
		"pagesize": pageSize,
	})
}

// GetCustWXByID 获取用户信息
func (c *CustomerController) GetCustWXByID() {
	userMapRaw := c.Context.Get("userMap")
	if userMapRaw == nil {
		c.ResponseError(errors.New("获取用户信息失败, 请确认使用微信浏览"))
	}

	userMap := userMapRaw.(model.TaUserMapping)

	custID := userMap.UserId
	cust, err := c.serv.GetCustWithWXByID(custID)
	if err != nil {
		utils.LogError(err)
		c.ResponseError(errors.New("获取用户信息失败, 请重试"))
	}

	c.ResponseJSON(map[string]interface{}{
		"customer": cust,
	})
}

// SignIn 微信登录
func (c *CustomerController) SignIn() {
	phone := c.GetString("phone")
	captcha := c.GetString("captcha")

	if err := utils.ValidCaptcha(phone, captcha); err != nil {
		c.ResponseError(err)
	}

	userMapping := c.Context.Get("userMap").(model.TaUserMapping)

	cust, err := c.serv.BindWechatUser(&userMapping, phone)
	if err != nil {
		c.ResponseError(err)
	}

	c.SetSession(controllers.SNCustID, cust.CustomerId)

	c.ResponseJSON("ok")
}

// SignUp 注册会员
func (c *CustomerController) SignUp() {
	phone := c.GetString("phone")
	captcha := c.GetString("captcha")
	csID := c.GetString("case")
	arID := c.GetString("sales")

	if phone == "" || captcha == "" || csID == "" || arID == "" {
		c.ResponseError(errors.New("请填写完整注册信息"))
	}

	if c.RunMode != "dev" {
		if err := utils.ValidCaptcha(phone, captcha); err != nil {
			c.ResponseError(err)
		}
	}

	userMapping := c.Context.Get("userMap").(model.TaUserMapping)

	cust, err := c.serv.BindWechatCust(&userMapping, phone, csID, arID)
	if err != nil {
		c.ResponseError(err)
	}

	c.SetSession(controllers.SNCustID, cust.CustomerId)

	c.ResponseJSON("ok")
}
