package price_driven

import (
	"errors"
	"hongze/hongze_yb/models/response"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/models/tables/yb_price_driven"
	"hongze/hongze_yb/models/tables/yb_price_driven_visit_log"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
)

// GetPriceDrivenDetail 获取价格驱动详情
func GetPriceDrivenDetail(varietyTagId int) (resp *response.PriceDrivenItem, errMsg string, err error) {
	resp = new(response.PriceDrivenItem)
	// 获取详情
	item, e := yb_price_driven.GetPriceDrivenByVarietyTagId(varietyTagId)
	if e != nil && e != utils.ErrNoRow {
		errMsg = "获取失败"
		err = errors.New("获取价格驱动信息失败, Err:" + e.Error())
		return
	}
	if item != nil {
		resp.PriceDrivenID = item.PriceDrivenID
		resp.VarietyTagID = item.VarietyTagID
		resp.MainVariable = item.MainVariable
		resp.CoreDrivenType = item.CoreDrivenType
		resp.CoreDrivenContent = item.CoreDrivenContent
		resp.CoreContent = item.CoreContent
		resp.CreateTime = item.CreateTime.Format(utils.FormatDateTime)
		resp.ModifyTime = item.ModifyTime.Format(utils.FormatDateTime)
	}
	return
}

// SavePriceDrivenVisitLog 保存价格驱动访问记录
func SavePriceDrivenVisitLog(priceDrivenId, sourceAgent int, userInfo user.UserInfo) (errMsg string, err error) {
	companyInfo, e := company_product.GetByCompany2ProductId(userInfo.CompanyID, 1)
	if e != nil && e != utils.ErrNoRow {
		errMsg = "保存失败"
		err = errors.New("获取客户信息失败, Err: " + e.Error())
		return
	}
	companyName := "潜在客户"
	companyStatus := "潜在"
	if companyInfo != nil && companyInfo.CompanyID > 0 {
		companyName = companyInfo.CompanyName
		companyStatus = companyInfo.Status
	}
	item, e := yb_price_driven.GetPriceDrivenById(priceDrivenId)
	if e != nil && e != utils.ErrNoRow {
		errMsg = "保存失败"
		err = errors.New("获取价格驱动信息失败, Err:" + e.Error())
		return
	}
	tagId := 0
	tagName := ""
	if item != nil && item.PriceDrivenID > 0 {
		tagId = item.VarietyTagID
		tagName = item.VarietyTagName
	}
	logItem := &yb_price_driven_visit_log.YbPriceDrivenVisitLog{
		PriceDrivenID:  priceDrivenId,
		VarietyTagID:   tagId,
		VarietyTagName: tagName,
		UserID:         int(userInfo.UserID),
		Mobile:         userInfo.Mobile,
		RealName:       userInfo.RealName,
		NickName:       userInfo.NickName,
		CompanyID:      int(userInfo.CompanyID),
		CompanyName:    companyName,
		CompanyStatus:  companyStatus,
		SourceAgent:    sourceAgent,
	}
	if e := logItem.Create(); e != nil {
		errMsg = "保存失败"
		err = errors.New("新增价格驱动访问记录失败, Err: " + e.Error())
		return
	}
	return
}
