package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"hongze/hongze_cygx/utils"
	"strconv"
	"time"
)

type CeLueArticleResultApi struct {
	Data       []CeLueArticleResultApidate `json:"data"`
	Code       int                         `json:"code"`
	Msg        string                      `json:"msg"`
	Pagination *Pagination                 `json:"pagination"`
}

type CeLueArticleResultApidate struct {
	CelueHistoryId int      `json:"id"`
	Mobile         string   `json:"phone_number"`
	ArticleId      string   `json:"entity_info"`
	CreateDate     string   `json:"access_time"`
	CrmUser        *CrmUser `json:"user"`
	CompanyName    *CrmUser `json:"crm_company"`
}

type CrmUser struct {
	RealName string `json:"name"`
}

type CrmCompany struct {
	CompanyName string `json:"name"`
}

func GetCeLueArticleCountById(celueHistoryId int) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM cygx_celue_article_history_record WHERE celue_history_id = ? `
	err = o.Raw(sql, celueHistoryId).QueryRow(&count)
	return
}

func GetCeLueArticleListByIds(celueHistoryIds []int) (items []*CygxArticleHistoryRecordAll, err error) {
	if len(celueHistoryIds) == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT celue_history_id FROM cygx_celue_article_history_record WHERE celue_history_id IN (` + utils.GetOrmInReplace(len(celueHistoryIds)) + `) `
	_, err = o.Raw(sql, celueHistoryIds).QueryRows(&items)
	return
}

type CygxCelueArticleHistoryRecord struct {
	Id             int       `orm:"column(id);pk"`
	ArticleId      string    `description:"文章ID"`
	CelueHistoryId int       `description:"策略平台记录的ID"`
	CreateTime     string    `description:"本地创建时间"`
	CreateDateApi  time.Time `description:"图表创建时间"`
	Mobile         string    `description:"手机号"`
	CompanyName    string    `description:"公司名称"`
	RealName       string    `description:"用户姓名"`
	CompanyStatus  string    `description:"公司状态"`
	SellerName     string    `description:"所属销售"`
}

// 新增
func AddCeLueArticle(item *CygxCelueArticleHistoryRecord, mapMobileArticleId map[string]int) (lastId int64, err error) {
	o, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}
	defer func() {
		if err == nil {
			o.Commit()
		} else {
			o.Rollback()
		}
	}()
	lastId, err = o.Insert(item)

	//写入记录到总的统计表
	record := new(CygxArticleHistoryRecordAll)
	articleId, _ := strconv.Atoi(item.ArticleId)
	record.ArticleId = articleId
	record.CelueHistoryId = item.CelueHistoryId
	record.CreateTime = item.CreateTime
	record.ModifyTime = time.Now()
	record.CreateDateApi = time.Now()
	record.Mobile = item.Mobile
	record.CompanyName = item.CompanyName
	record.RealName = item.RealName
	record.Platfor = 2
	record.Source = "CELUE"
	if mapMobileArticleId[fmt.Sprint(item.Mobile, "_", item.ArticleId)] == articleId {
		record.IsDel = 1
	}
	lastId, err = o.Insert(record)
	return
}