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
}

func GetCygxMorningMeetingReviewChapterListByIds2(meetingreviewchaptIds []int) (items []*models.CygxMorningMeetingReviewLogResp, 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.GetCygxMorningMeetingReviewChapterList2(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
}

// 添加晨会精华操作日志
func AddCygxMorningMeetingReviewLog(itemReq *models.CygxMorningMeetingReviewLog, operate, opUserName string, opUserId, status int) (mapPvResp, mapUvResp map[int]int) {

	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("添加晨会精华操作日志 失败，AddCygxMorningMeetingReviewLog Err："+err.Error(), 3)
		}
	}()
	itemReq.LogId = 0
	//item := new(models.CygxMorningMeetingReviewLog)
	//item.MeetingTime = itemReq.MeetingTime
	//item.CreateTime = time.Now()
	//item.ModifyTime = time.Now()
	//item.IndustryId = itemReq.IndustryId
	//item.IndustryName = itemReq.IndustryName
	//item.ChartPermissionName = itemReq.ChartPermissionName
	//item.ChartPermissionId = itemReq.ChartPermissionId
	//item.IndustrialSubjectIds = itemReq.IndustrialSubjectIds
	//item.MeetingId = int(itemReq.MeetingId)
	//item.Content = itemReq.Content
	//item.ReportLink = itemReq.ReportLink
	//item.LinkArticleId = itemReq.LinkArticleId
	//item.Title = itemReq.Title
	//itemReq.Remark = remark
	itemReq.Operate = operate
	itemReq.OpUserName = opUserName
	itemReq.OpUserId = opUserId

	logId, e := models.AddCygxMorningMeetingReviewLog(itemReq)
	if e != nil {
		err = errors.New("AddCygxMorningMeetingReviewLog, Err: " + e.Error())
		return
	}
	if status == 2 {
		go SendWxMsgMorningMeetingApproveSubmit(int(logId)) ///晨会点评提交新内容审核时，给合规（指定手机号15721524062、15221002612）发送模板消息
	} else {
		go SendWxMsgMorningMeetingApproveResult(int(logId), status) //晨会点评内容完成审核时，给提交人发送模板消息
	}
	return
}

//func init() {
//	HandleMorningMeetingReviewPush(145)
//}

// 处理晨会精华发布之后的逻辑
func HandleMorningMeetingReviewPush(meetingId int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("处理晨会精华发布之后的逻辑 失败，AddCygxMorningMeetingReviewLog Err："+err.Error(), 3)
		}
	}()
	listchapter, e := models.GetCygxMorningMeetingReviewsListById(meetingId)
	if e != nil {
		err = errors.New("GetCygxMorningMeetingReviewsListById, Err: " + e.Error())
		return
	}
	for _, item := range listchapter {
		go SendWxMsgWithCygxMorningMeeting(int(meetingId), item.IndustryId, item.IndustryName)
		go UpdateIndustrialManagementTimeLineDateList3ByRedisAdd(item.IndustryId) //处理产业管理时间线相关内容的数据
		go UpdateMeetingreviewchaptResourceData(item.Id)                          //写入首页最新  cygx_resource_data 表
		go AddComprehensiveMeetingreviewchapt(item.Id)                            //Es添加晨会精华
	}
	return
}

//func init() {
//	//SendWxMsgMorningMeetingApproveResult(1, 1)
//	SendWxMsgMorningMeetingApproveSubmit(1)
//}

// 晨会点评内容完成审核时，给提交人发送模板消息（服务销售openID取销售原账号对应的openID，根据姓名匹配查询）
func SendWxMsgMorningMeetingApproveResult(logId, status int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("晨会点评内容完成审核时，给提交人发送模板消息失败 logId ", logId, err.Error()), 2)
		}
	}()
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string

	logDetail, e := models.GetCygxMorningMeetingReviewLogByLogId(logId)
	if e != nil {
		err = errors.New("GetCygxMorningMeetingReviewLogByLogId, Err: " + e.Error())
		return
	}
	meetingId := logDetail.MeetingId
	reviewDetail, e := models.GetMorningMeetingReviewById(meetingId)
	if e != nil {
		err = errors.New("GetMorningMeetingReviewById, Err: " + e.Error())
		return
	}

	//获取建会人员信息
	admin, e := models.GetSysAdminById(reviewDetail.OpUserId)
	if e != nil {
		err = errors.New("GetMorningMeetingReviewById, Err: " + e.Error())
		return
	}
	mobile := admin.Mobile
	openIdList, e := models.GetWxOpenIdByMobileList(mobile)
	if e != nil {
		err = errors.New("GetWxOpenIdByMobileList, Err: " + e.Error())
		return
	}
	if len(openIdList) == 0 {
		return
	}

	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	redirectUrl := ""

	keyword1 = "晨会点评内容审核"
	if status == 1 {
		meetDetail, e := models.GetCygxMorningMeetingReviewChapterDetailByMeetingId(meetingId)
		if e != nil {
			err = errors.New("GetCygxMorningMeetingReviewChapterDetailByMeetingId, Err: " + e.Error())
			return
		}
		keyword2 = "已通过审核，点击查看详情"
		redirectUrl = utils.WX_MSG_PATH_INDUSTRY_DETAIL + strconv.Itoa(meetDetail.IndustryId) + "&IsSendWx=1&ChapterId=" + strconv.Itoa(meetDetail.Id)
	} else {
		keyword2 = "未通过审核，点击查看驳回原因"
		redirectUrl = utils.WX_MSG_PATH_MORNING_MEETING_LOG_DETAIL + strconv.Itoa(logId)
		if utils.RunMode != "release" {
			redirectUrl = ""
		}
	}

	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdArticleUserRemind
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(meetingId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

// 晨会点评提交新内容审核时，给合规（指定手机号15721524062、15221002612）发送模板消息
func SendWxMsgMorningMeetingApproveSubmit(logId int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("晨会点评内容完成审核时，给提交人发送模板消息失败 logId ", logId, err.Error()), 2)
		}
	}()
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string

	logDetail, e := models.GetCygxMorningMeetingReviewLogByLogId(logId)
	if e != nil {
		err = errors.New("GetCygxMorningMeetingReviewLogByLogId, Err: " + e.Error())
		return
	}
	meetingId := logDetail.MeetingId

	////获取建会人员信息
	//admin, e := models.GetSysAdminById(logDetail.OpUserId)
	//if e != nil {
	//	err = errors.New("GetMorningMeetingReviewById, Err: " + e.Error())
	//	return
	//}

	keyword1 = logDetail.OpUserName
	keyword2 = "--"
	keyword3 = time.Now().Format(utils.FormatDateTime)
	keyword4 = "提交了晨会点评待审核"

	configCode := "cygx_morning_meeting_mobile"
	detailConfig, e := models.GetConfigByCode(configCode)
	if e != nil {
		err = errors.New("GetConfigByCode, Err: " + e.Error())
		return
	}

	mobile := detailConfig.ConfigValue
	openIdList, e := models.GetWxOpenIdByMobileList(mobile)
	if e != nil {
		err = errors.New("GetWxOpenIdByMobileList, Err: " + e.Error())
		return
	}
	if len(openIdList) == 0 {
		return
	}

	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	redirectUrl := ""

	redirectUrl = utils.WX_MSG_PATH_MORNING_MEETING_LOG_DETAIL + strconv.Itoa(logId)
	if utils.RunMode != "release" {
		redirectUrl = ""
	}

	sendInfo := new(SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdAskMsgXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(meetingId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}
