package services

import (
	"context"
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"strconv"
	"strings"
	"time"
)

//
//func init() {
//
//	for i := 180; i > 0; i-- {
//		MakeMorningMeetingReviews(i)
//	}
//
//}

func MakeMorningMeetingReviews(cont context.Context) (err error) {
	//func MakeMorningMeetingReviews(day int) (err error) {
	//func init12(day int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("定时生成晨会精华汇总失败，err:"+err.Error(), 2)
		}
	}()
	day := 0
	hourstr := " 10:30:00 "
	DayTime := time.Now().AddDate(0, 0, -day)
	startSize := 0
	pageSize := 100
	var condition string
	var pars []interface{}
	startDate := DayTime.AddDate(0, 0, -1).Format(utils.FormatDate) + hourstr
	endDate := DayTime.Format(utils.FormatDate) + hourstr

	condition = ` 	AND publish_time  = ? `
	pars = append(pars, endDate)
	total, err := models.GetCygxMorningMeetingGatherCount(condition, pars)
	if err != nil {
		return
	}
	if total > 0 {
		return
	}
	pars = make([]interface{}, 0)
	condition = ` 	AND publish_time  BETWEEN ?   AND  ? `
	pars = append(pars, startDate, endDate)

	list, err := models.GetCygxMorningMeetingReviewsList(condition, pars, startSize, pageSize)
	if err != nil {
		return
	}
	if len(list) == 0 {
		return
	}
	item := new(models.CygxMorningMeetingGather)
	for _, v := range list {
		item.MeetingIds += strconv.Itoa(v.Id) + ","
	}
	item.MeetingIds = strings.TrimRight(item.MeetingIds, ",")
	item.Title = utils.GetTimeDateHourAndDay(DayTime) + "（" + utils.StrDateTimeToWeek(DayTime.Format(utils.FormatDateTime)) + "）" + "|晨会精华"
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	item.PublishTime = endDate
	item.Status = 1
	err = models.AddCygxMorningMeetingGather(item)
	return
}

// 添加晨会点评点击记录
func AddCygxMorningMeetingReviewChapterHistory(user *models.WxUserItem, articleId int, sourcePage string) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("添加晨会点评点击记录失败 ，AddCygxMorningMeetingReviewChapterHistory err"+err.Error(), "id:", articleId, "sourcePage:", sourcePage, "userid:", user.UserId), 2)
		}
	}()
	detail, e := models.GetCygxMorningMeetingReviewChapterDetail(articleId)
	if e != nil {
		err = errors.New("GetCygxMorningMeetingReviewChapterDetail, Err: " + e.Error())
		return
	}
	historyRecord := new(models.CygxMorningMeetingReviewChapterHistory)
	historyRecord.UserId = user.UserId
	historyRecord.ArticleId = articleId
	historyRecord.SourcePage = sourcePage
	historyRecord.CreateTime = time.Now()
	historyRecord.Mobile = user.Mobile
	historyRecord.Email = user.Email
	historyRecord.CompanyId = user.CompanyId
	historyRecord.CompanyName = user.CompanyName
	historyRecord.MeetingId = int(detail.MeetingId)
	historyRecord.RegisterPlatform = utils.REGISTER_PLATFORM
	sellerItem, e := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetSellerByCompanyIdCheckFicc, Err: " + e.Error())
		return
	}
	historyRecord.RealName = user.RealName
	if sellerItem != nil {
		historyRecord.SellerName = sellerItem.RealName
	}
	_, e = models.AddCygxMorningMeetingReviewChapterHistory(historyRecord)
	if e != nil {
		err = errors.New("AddCygxMorningMeetingReviewChapterHistorymodels, Err: " + e.Error())
		return
	}
	return
}

// 通过晨会精华子ID，获取出参列表详情
func GetCygxMorningMeetingReviewChapterListByIds(meetingreviewchaptIds []int) (items []*models.CygxMorningMeetingGatherDetailListResp, err error) {
	lenArr := len(meetingreviewchaptIds)
	if lenArr == 0 {
		return
	}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("通过晨会精华子ID，获取出参列表详情失败 ，GetCygxMorningMeetingReviewChapterListByIds err"+err.Error(), "meetingreviewchaptIds:", meetingreviewchaptIds), 2)
		}
	}()
	var condition string
	var pars []interface{}

	pars = make([]interface{}, 0)
	condition = ` AND c.id IN (` + utils.GetOrmInReplace(lenArr) + `)`
	pars = append(pars, meetingreviewchaptIds)

	//查询晨会
	listrMeet, e := models.GetCygxMorningMeetingReviewChapterList(condition, pars)
	if e != nil {
		err = errors.New("GetCygxMorningMeetingReviewChapterList, Err: " + e.Error())
		return
	}

	//获取晨会相关的标的
	var subjectIds []string
	for _, v := range listrMeet {
		if v.IndustrialSubjectIds != "" {
			slice := strings.Split(v.IndustrialSubjectIds, ",")
			for _, vS := range slice {
				subjectIds = append(subjectIds, vS)
			}
		}
	}

	lensubjectIds := len(subjectIds)
	if lensubjectIds > 0 {
		//获取标的信息
		pars = make([]interface{}, 0)
		condition = ` AND industrial_subject_id  IN (` + utils.GetOrmInReplace(lensubjectIds) + `)`
		pars = append(pars, subjectIds)
		listsubject, e := models.GetCygxIndustrialSubjectListCondition(condition, pars)
		if e != nil {
			err = errors.New("GetCygxIndustrialSubjectListCondition, Err: " + e.Error())
			return
		}

		var meetSubjectItems = make(map[string]*models.CygxIndustrialSubject)
		for _, v := range listsubject {
			meetSubjectItems[strconv.Itoa(v.IndustrialSubjectId)] = v
		}

		//建立标的与晨会的映射关系
		for _, v := range listrMeet {
			if v.IndustrialSubjectIds != "" {
				slice := strings.Split(v.IndustrialSubjectIds, ",")
				for _, vS := range slice {
					if meetSubjectItems[vS] != nil {
						v.ListSubject = append(v.ListSubject, meetSubjectItems[vS])
					}
				}
			}
		}
	}
	items = listrMeet
	return
}
