package customer

import (
	"errors"
	"spaceofcheng/services/models"
	"spaceofcheng/services/models/cases"
	"spaceofcheng/services/models/customer"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/service/events"
	"spaceofcheng/services/utils"
	"strconv"
)

// CustomerServ 系统处理
type CustomerServ struct {
	ctx     *utils.Context
	dao     *customer.CustomerDAO
	casedao *cases.CaseDAO
}

// NewCustomerServ 初始化
func NewCustomerServ(ctx *utils.Context) *CustomerServ {
	return &CustomerServ{
		ctx:     ctx,
		dao:     customer.NewCustomerDAO(ctx),
		casedao: cases.NewCaseDAO(ctx),
	}
}

// GetCustWithWXList 获取客户列表
func (s *CustomerServ) GetCustWithWXList(phone string, page ...int) ([]customer.CustWithWX, int64, error) {
	return s.dao.CustWithWXList(phone, page...)
}

// GetCustWithWXByID 获取客户列表
func (s *CustomerServ) GetCustWithWXByID(custID string) (*customer.CustWithWX, error) {
	cust, err := s.dao.GetCustWithWXByID(custID)
	if err != nil {
		utils.LogError(err.Error())
		return nil, err
	}

	if cust.Status != models.STATUS_NORMAL {
		return nil, errors.New("用户状态异常")
	}

	return cust, nil
}

// GetCustUserByID 获取用户信息(自定义内容)
func (s *CustomerServ) GetCustUserByID(userID string) (*UserProfile, error) {
	user, err := s.dao.GetUserByID(userID)
	if err != nil {
		utils.LogError(err.Error())
		return nil, err
	}

	if user.Status != models.STATUS_NORMAL {
		return nil, errors.New("用户状态异常")
	}

	userProfile := UserProfile{
		UserId:     user.UserId,
		UserName:   user.UserName,
		RealName:   user.RealName,
		Sex:        user.Sex,
		WorkNo:     user.WorkNo,
		Email:      user.Email,
		Phone:      user.Phone,
		Headimgurl: user.Headimgurl,
	}

	return &userProfile, nil
}

// BindWechatUser 绑定微信用户
func (s *CustomerServ) BindWechatUser(userMap *model.TaUserMapping, phone string) (*model.TaCustomer, error) {
	user, err := s.dao.GetUserByPhone(phone)
	if err != nil {
		utils.LogError(err.Error())
		return nil, err
	}

	if user == nil || user.Status == models.STATUS_DEL {
		return nil, errors.New("当前手机号未绑定管理员")
	}

	cust, err := s.dao.GetCustomerByPhone(phone)
	if err != nil {
		utils.LogError(err.Error())
		return nil, err
	}

	if cust == nil {
		wxInfoRaw := s.ctx.Get("wxInfo")
		if wxInfoRaw == nil {
			return nil, errors.New("请确定使用微信端登录")
		}

		wxInfo := wxInfoRaw.(map[string]interface{})
		newCust, err := s.SaveNewCustomer(wxInfo, "", "", user.UserId)
		if err != nil {
			utils.LogError(err.Error())
			return nil, err
		}
		cust = newCust
	}

	if cust.Status != models.STATUS_NORMAL {
		return nil, errors.New("用户状态不正确")
	}

	// triggerRegiteEvent 触发注册事件
	utils.EmitEvent(events.EvtRegiste, *cust)

	if cust.CustomerId == userMap.UserId {
		return cust, nil
	}

	// 更新用户映射信息
	userMap.UserId = cust.CustomerId
	if err := s.dao.UpdateUserMapping(userMap, []string{"user_id"}); err != nil {
		utils.LogError("更新用户映射信息失败:" + err.Error())
		return nil, errors.New("映射用户信息失败")
	}

	return cust, nil
}

// BindWechatCust 绑定微信用户
func (s *CustomerServ) BindWechatCust(userMap *model.TaUserMapping, phone, caseID, userID string) (*model.TaCustomer, error) {
	cust, err := s.dao.GetCustomerByPhone(phone)
	if err != nil {
		utils.LogError(err.Error())
		return nil, err
	}

	// 用户不存在, 则新增
	if cust == nil {
		wxInfoRaw := s.ctx.Get("wxInfo")
		if wxInfoRaw == nil {
			return nil, errors.New("请确定使用微信端登录")
		}

		wxInfo := wxInfoRaw.(map[string]interface{})
		newCust, err := s.SaveNewCustomer(wxInfo, caseID, userID, "")
		if err != nil {
			utils.LogError(err.Error())
			return nil, err
		}

		cust = newCust
	}

	if cust.Status != models.STATUS_NORMAL {
		return nil, errors.New("用户状态不正确")
	}

	// 如果客户ID 与映射表中一致, 说明已经绑定过了
	if cust.CustomerId == userMap.UserId {
		return cust, nil
	}

	// triggerRegiteEvent 触发注册事件
	utils.EmitEvent(events.EvtRegiste, *cust)

	// 更新用户映射信息
	userMap.UserId = cust.CustomerId
	if err := s.dao.UpdateUserMapping(userMap, []string{"user_id"}); err != nil {
		utils.LogError("更新用户映射信息失败:" + err.Error())
		return nil, errors.New("映射用户信息失败")
	}

	return cust, nil
}

// SaveNewCustomer 新增客户
func (s *CustomerServ) SaveNewCustomer(wxInfo map[string]interface{}, caseID, arID, userID string) (*model.TaCustomer, error) {
	if caseID == "" && arID == "" && userID == "" {
		return nil, errors.New("新增信息失败, 无法确认人员类型")
	}

	// 微信相关字段
	nickyName := wxInfo["nickname"].(string)
	sex := wxInfo["sex"].(string)
	headimgurl := wxInfo["headimgurl"].(string)

	sexInt, _ := strconv.Atoi(sex)
	if sexInt == 0 {
		sexInt = 1 // 默认男性
	}

	cust := model.TaCustomer{
		CustomerName: nickyName,
		Name:         nickyName,
		Sex:          sexInt,
		Headimgurl:   headimgurl,
	}

	// 校验案场信息
	if caseID != "" {
		cs, err := s.casedao.GetCaseByID(caseID)
		if err != nil {
			utils.LogError(err.Error())
			return nil, err
		}

		if cs == nil || cs.Status == models.STATUS_DEL {
			return nil, errors.New("系统无该推荐案场")
		}

		cust.OrgId = cs.OrgId
		cust.RecommendCase = cs.CaseId
	}

	// 校验推荐人
	if arID != "" {
		ar, err := s.dao.GetUserByID(arID)
		if err != nil {
			utils.LogError(err.Error())
			return nil, err
		}

		if ar == nil || ar.Status == models.STATUS_DEL {
			return nil, errors.New("系统无该推荐人")
		}

		cust.OrgId = ar.OrgId
		cust.RecommendId = ar.UserId
		cust.RecommendName = ar.RealName
	}

	// 系统用户
	if userID != "" {
		user, err := s.dao.GetUserByID(userID)
		if err != nil {
			utils.LogError(err.Error())
			return nil, err
		}

		if user != nil && user.Status != models.STATUS_DEL {
			cust.CustomerId = userID
		}
	}

	if err := s.dao.SaveCustomer(&cust); err != nil {
		utils.LogError("更新客户信息失败: " + err.Error())
		return nil, errors.New("更新客户信息失败")
	}

	account := new(model.TaCustomerAccount)
	account.CustomerId = cust.CustomerId
	account.CustomerName = cust.CustomerName
	account.OrgId = cust.OrgId
	account.Amount = "0"
	account.Points = "0"
	account.PayedAmount = "0"
	account.PayedPoints = "0"

	if err := s.dao.SaveAccount(account); err != nil {
		utils.LogError("插入账户信息失败: " + err.Error())
		return nil, errors.New("更新客户信息失败")
	}

	return &cust, nil
}
