package service

import (
	"encoding/json"
	"fmt"
	"strconv"
	"time"

	"github.com/linmadan/egglib-go/core/application"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/factory"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/notify/adapter"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/notify/command"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/dao"
)

// 个人信息提示

type MessagePersonalService struct {
}

func NewMessagePersonalService() *MessagePersonalService {
	newService := &MessagePersonalService{}
	return newService
}

// 获取今天的周期综合自评消息提示
func (srv *MessagePersonalService) TodayMessageSummaryEvaluationSelf(param *command.GetUserMessageCommand) (map[string]interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()

	nowTime := time.Now()
	evaluationRepo := factory.CreateSummaryEvaluationRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	_, evaluationList, err := evaluationRepo.Find(map[string]interface{}{
		"targetUserId": param.UserId,
		"types":        domain.EvaluationSelf,
		"beginTime":    nowTime,
		"endTime":      nowTime,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "周期综合自评"+err.Error())
	}
	resp := map[string]interface{}{
		"needNotify": false,
		"content":    "",
	}
	if len(evaluationList) == 0 {
		return resp, nil
	}

	messageRepo := factory.CreateMessagePersonalRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	newMessageList := []domain.MessagePersonal{}
	for _, val := range evaluationList {
		payload := map[string]string{
			"id": strconv.Itoa(val.Id),
		}
		payloadStr, _ := json.Marshal(payload)
		cnt, _, err := messageRepo.Find(map[string]interface{}{
			"types":        domain.MessageTypesOther,
			"targetUserId": param.UserId,
			"payload":      string(payloadStr),
			"limit":        1,
		})
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "检查自评消息记录"+err.Error())
		}
		if cnt == 0 {
			newMessageList = append(newMessageList, domain.MessagePersonal{
				Id:           0,
				Types:        domain.MessageTypesOther,
				TargetUserId: val.TargetUser.UserId,
				ReadFlag:     domain.MessageIsRead,
				Title:        fmt.Sprintf("%s综合自评已开启,请前往进行评估.", val.CycleName),
				Content:      fmt.Sprintf("%s综合自评已开启,请前往进行评估.", val.CycleName),
				CreatedAt:    time.Time{},
				UpdatedAt:    time.Time{},
				Payload:      string(payloadStr),
			})
			resp["needNotify"] = true
			resp["content"] = fmt.Sprintf("%s综合自评已开启,请前往进行评估.", val.CycleName)
			break
		}
	}
	for i := range newMessageList {
		err = messageRepo.Save(&newMessageList[i])
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "保存自评消息记录"+err.Error())
		}
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	return resp, nil
}

// 获取关于任务里程碑异常的消息
// 每日一次
func (srv *MessagePersonalService) TodayMessageTaskStageAnomaly(param *command.GetUserMessageCommand) (map[string]interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()

	messageRepo := factory.CreateMessagePersonalRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	cnt, _, err := messageRepo.Find(map[string]interface{}{
		"types":        domain.MessageTypesTaskStage,
		"targetUserId": param.UserId,
		"limit":        1,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "检查任务里程碑异常的消息"+err.Error())
	}
	if cnt > 0 {
		resp := map[string]interface{}{
			"needNotify": false,
			"list":       []adapter.MessageListAdapter{},
		}
		return resp, nil
	}
	userDao := dao.NewUserDao(map[string]interface{}{"transactionContext": transactionContext})

	taskDao := dao.NewTaskDao(map[string]interface{}{"transactionContext": transactionContext})
	// 我作为任务负责人的提醒
	leaderIds := []string{strconv.Itoa(param.UserId)}
	taskStageList, err := taskDao.TaskStageAnomalyByLeader(leaderIds)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "检查任务里程碑异常的消息"+err.Error())
	}
	// 我作为任务相关方
	taskStageList0, err := taskDao.TaskStageAnomalyByRelatedUser(param.UserId)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "检查任务里程碑异常的消息"+err.Error())
	}
	childUser, err := userDao.AllChildUser(param.UserId)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "获取下级员工"+err.Error())
	}
	childUserId := []string{}
	for _, val := range childUser {
		if val.Level == 2 {
			childUserId = append(childUserId, strconv.Itoa(val.Id))
		}
	}
	// 作为上级,我的下级员工的异常里程碑
	var taskList2 []dao.TaskData3
	if len(childUserId) == 0 {
		taskList2, err = taskDao.TaskStageAnomalyByLeader(childUserId)
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "检查任务里程碑异常的消息"+err.Error())
		}
	}
	childUserId2 := []string{}
	for _, val := range childUser {
		if val.Level >= 3 {
			childUserId = append(childUserId, strconv.Itoa(val.Id))
		}
	}
	//  作为上级, 我的下下级员工的异常里程碑
	var taskList3 []dao.TaskData3
	if len(childUserId) == 0 {
		taskList3, err = taskDao.TaskStageAnomalyByLeader(childUserId2)
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "检查任务里程碑异常的消息"+err.Error())
		}
	}

	msgList := []adapter.MessageListAdapter{}
	for _, val := range taskStageList {
		s := fmt.Sprintf("【您负责的项目【%s】里程碑未按时完成,请重点关注,积极寻找上级辅导。】", val.TaskAlias)
		msgList = append(msgList, adapter.MessageListAdapter{
			Content: s,
		})
		payload := map[string]string{
			"task_id":    strconv.Itoa(val.TaskId),
			"task_alias": val.TaskAlias,
			"task_name":  val.TaskName,
		}
		payloadStr, _ := json.Marshal(payload)
		newMessage := domain.MessagePersonal{
			Id:           0,
			Types:        domain.MessageTypesTaskStage,
			TargetUserId: param.UserId,
			ReadFlag:     domain.MessageIsRead,
			Title:        s,
			Content:      s,
			CreatedAt:    time.Time{},
			UpdatedAt:    time.Time{},
			Payload:      string(payloadStr),
		}
		err = messageRepo.Save(&newMessage)
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
		}
	}
	for _, val := range taskList2 {
		s := fmt.Sprintf("【您下级%s负责的项目【%s】里程碑未按时完成,请前往辅导。】", val.LeaderName, val.TaskAlias)
		msgList = append(msgList, adapter.MessageListAdapter{
			Content: s,
		})
		payload := map[string]string{
			"task_id":    strconv.Itoa(val.TaskId),
			"task_alias": val.TaskAlias,
			"task_name":  val.TaskName,
		}
		payloadStr, _ := json.Marshal(payload)
		newMessage := domain.MessagePersonal{
			Id:           0,
			Types:        domain.MessageTypesTaskStage,
			TargetUserId: param.UserId,
			ReadFlag:     domain.MessageIsRead,
			Title:        s,
			Content:      s,
			CreatedAt:    time.Time{},
			UpdatedAt:    time.Time{},
			Payload:      string(payloadStr),
		}
		err = messageRepo.Save(&newMessage)
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
		}
	}
	for _, val := range taskList3 {
		s := fmt.Sprintf("【您下级%s关注的项目【%s】里程碑未按时完成,请前往辅导。】", val.LeaderName, val.TaskAlias)
		msgList = append(msgList, adapter.MessageListAdapter{
			Content: s,
		})
		payload := map[string]string{
			"task_id":    strconv.Itoa(val.TaskId),
			"task_alias": val.TaskAlias,
			"task_name":  val.TaskName,
		}
		payloadStr, _ := json.Marshal(payload)
		newMessage := domain.MessagePersonal{
			Id:           0,
			Types:        domain.MessageTypesTaskStage,
			TargetUserId: param.UserId,
			ReadFlag:     domain.MessageIsRead,
			Title:        s,
			Content:      s,
			CreatedAt:    time.Time{},
			UpdatedAt:    time.Time{},
			Payload:      string(payloadStr),
		}
		err = messageRepo.Save(&newMessage)
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
		}
	}
	//我作为任务相关人
	for _, val := range taskStageList0 {
		s := fmt.Sprintf("【您下级%s关注的项目【%s】里程碑未按时完成,请前往辅导。】", val.LeaderName, val.TaskName)
		msgList = append(msgList, adapter.MessageListAdapter{
			Content: s,
		})
		payload := map[string]string{
			"task_id":    strconv.Itoa(val.TaskId),
			"task_alias": val.TaskAlias,
			"task_name":  val.TaskName,
		}
		payloadStr, _ := json.Marshal(payload)
		newMessage := domain.MessagePersonal{
			Id:           0,
			Types:        domain.MessageTypesTaskStage,
			TargetUserId: param.UserId,
			ReadFlag:     domain.MessageIsRead,
			Title:        s,
			Content:      s,
			CreatedAt:    time.Time{},
			UpdatedAt:    time.Time{},
			Payload:      string(payloadStr),
		}
		err = messageRepo.Save(&newMessage)
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
		}
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}

	resp := map[string]interface{}{
		"needNotify": true,
		"list":       msgList,
	}
	if len(msgList) == 0 {
		resp["needNotify"] = false
	}
	return resp, nil
}

// 获取关于任务反馈碑异常的消息
// 每日一次
func (srv *MessagePersonalService) TodayMessageTaskRecordAnomaly(param *command.GetUserMessageCommand) (map[string]interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()

	messageRepo := factory.CreateMessagePersonalRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	cnt, _, err := messageRepo.Find(map[string]interface{}{
		"types":        domain.MessageTypesTaskRecord,
		"targetUserId": param.UserId,
		"limit":        1,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "检查任务里程碑异常的消息"+err.Error())
	}
	if cnt > 0 {
		resp := map[string]interface{}{
			"needNotify": false,
			"list":       []adapter.MessageListAdapter{},
		}
		return resp, nil
	}
	userDao := dao.NewUserDao(map[string]interface{}{"transactionContext": transactionContext})

	taskDao := dao.NewTaskDao(map[string]interface{}{"transactionContext": transactionContext})
	// 我作为任务负责人
	leaderIds := []string{strconv.Itoa(param.UserId)}
	taskStageList, err := taskDao.TaskAnomalyByLeader(leaderIds, 2)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "检查任务里程碑异常的消息"+err.Error())
	}
	//获取员工全部子集
	childUser, err := userDao.AllChildUser(param.UserId)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "获取下级员工"+err.Error())
	}
	childUserId := []string{}
	for _, val := range childUser {
		if val.Level == 2 {
			childUserId = append(childUserId, strconv.Itoa(val.Id))
		}
	}
	//我作为上级, 获取我的下一级的异常任务
	var taskStageList2 []dao.TaskData2
	if len(childUserId) == 0 {
		taskStageList2, err = taskDao.TaskAnomalyByLeader(childUserId, 4)
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "检查任务里程碑异常的消息"+err.Error())
		}
	}
	childUserId2 := []string{}
	for _, val := range childUser {
		if val.Level >= 3 {
			childUserId = append(childUserId, strconv.Itoa(val.Id))
		}
	}
	// 我作为上级,获取我的下下级的异常任务
	var taskStageList3 []dao.TaskData2
	if len(childUserId) == 0 {
		taskStageList3, err = taskDao.TaskAnomalyByLeader(childUserId2, 5)
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "检查任务里程碑异常的消息"+err.Error())
		}
	}

	msgList := []adapter.MessageListAdapter{}
	for _, val := range taskStageList {
		s := fmt.Sprintf("【您负责的项目【%s】已超过%s日未反馈进度,请前往该战略任务进行反馈。】", val.Name, val.Anomaly)
		msgList = append(msgList, adapter.MessageListAdapter{
			Content: s,
		})
		payload := map[string]string{
			"id":         strconv.Itoa(val.Id),
			"taskName":   val.Name,
			"taskAlias":  val.Alias,
			"leaderName": val.LeaderName,
		}
		payloadStr, _ := json.Marshal(payload)
		newMessage := domain.MessagePersonal{
			Id:           0,
			Types:        domain.MessageTypesTaskRecord,
			TargetUserId: param.UserId,
			ReadFlag:     domain.MessageIsRead,
			Title:        s,
			Content:      s,
			CreatedAt:    time.Time{},
			UpdatedAt:    time.Time{},
			Payload:      string(payloadStr),
		}
		err = messageRepo.Save(&newMessage)
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
		}
	}
	for _, val := range taskStageList2 {
		s := fmt.Sprintf("【您下级%s负责的项目【%s】已超过%s日未反馈进度,请前往辅导。】", val.LeaderName, val.Name, val.Anomaly)
		msgList = append(msgList, adapter.MessageListAdapter{
			Content: s,
		})
		payload := map[string]string{
			"id":         strconv.Itoa(val.Id),
			"taskName":   val.Name,
			"taskAlias":  val.Alias,
			"leaderName": val.LeaderName,
		}
		payloadStr, _ := json.Marshal(payload)
		newMessage := domain.MessagePersonal{
			Id:           0,
			Types:        domain.MessageTypesTaskRecord,
			TargetUserId: param.UserId,
			ReadFlag:     domain.MessageIsRead,
			Title:        s,
			Content:      s,
			CreatedAt:    time.Time{},
			UpdatedAt:    time.Time{},
			Payload:      string(payloadStr),
		}
		err = messageRepo.Save(&newMessage)
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
		}
	}
	for _, val := range taskStageList3 {
		s := fmt.Sprintf("【您下级%s关注的项目【%s】已超过%s日未反馈进度,请前往辅导。】", val.LeaderName, val.Name, val.Anomaly)
		msgList = append(msgList, adapter.MessageListAdapter{
			Content: s,
		})
		payload := map[string]string{
			"id":         strconv.Itoa(val.Id),
			"taskName":   val.Name,
			"taskAlias":  val.Alias,
			"leaderName": val.LeaderName,
		}
		payloadStr, _ := json.Marshal(payload)
		newMessage := domain.MessagePersonal{
			Id:           0,
			Types:        domain.MessageTypesTaskRecord,
			TargetUserId: param.UserId,
			ReadFlag:     domain.MessageIsRead,
			Title:        s,
			Content:      s,
			CreatedAt:    time.Time{},
			UpdatedAt:    time.Time{},
			Payload:      string(payloadStr),
		}
		err = messageRepo.Save(&newMessage)
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
		}
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}

	resp := map[string]interface{}{
		"needNotify": true,
		"list":       msgList,
	}
	if len(msgList) == 0 {
		resp["needNotify"] = false
	}
	return resp, nil
}

// TodayMessage 任务里程碑变更通知
func (srv *MessagePersonalService) TodayMessageTaskStageModify(param *command.GetUserMessageCommand) (map[string]interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()

	messageRepo := factory.CreateMessagePersonalRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	_, messageList, err := messageRepo.Find(map[string]interface{}{
		"types":        domain.MessageTypesTaskModify,
		"targetUserId": param.UserId,
		"readFlag":     domain.MessageUnread,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "检查个人消息的消息"+err.Error())
	}
	for _, val := range messageList {
		val.ReadFlag = domain.MessageIsRead
		err = messageRepo.Save(val)
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "检查个人消息的消息"+err.Error())
		}
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	msgList := []adapter.MessageListAdapter{}
	for _, val := range messageList {
		msgList = append(msgList, adapter.MessageListAdapter{
			Content: val.Content,
		})
	}
	resp := map[string]interface{}{
		"needNotify": true,
		"list":       msgList,
	}
	if len(msgList) == 0 {
		resp["needNotify"] = false
	}
	return resp, nil
}