package sop_task

import (
	"context"
	"wechat-api/ent"
	"wechat-api/ent/messagerecords"
	"wechat-api/ent/soptask"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetSopTaskRecordListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetSopTaskRecordListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSopTaskRecordListLogic {
	return &GetSopTaskRecordListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *GetSopTaskRecordListLogic) GetSopTaskRecordList(req *types.IDReq) (resp *types.SopTaskRecordListResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	data, err := l.svcCtx.DB.SopTask.Query().
		Where(soptask.ID(req.Id), soptask.OrganizationIDEQ(organizationId)).
		WithTaskStages(func(query *ent.SopStageQuery) {
			query.WithStageNodes()
		}).
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	var sopTaskRecordList []types.SopTaskRecordInfo
	for _, s := range data.Edges.TaskStages {
		// 在message_records 表中统计 source_type=3, source_id=s.ID的记录数，以及其中status=3的记录数
		sst, _ := l.SopTaskRecord(3, s.ID, s.Name)
		sopTaskRecordList = append(sopTaskRecordList, *sst)
		for _, n := range s.Edges.StageNodes {
			nst, _ := l.SopTaskRecord(4, n.ID, n.Name)
			sopTaskRecordList = append(sopTaskRecordList, *nst)
		}
	}

	resp = &types.SopTaskRecordListResp{
		Data: sopTaskRecordList,
	}

	return resp, nil
}

func (l *GetSopTaskRecordListLogic) SopTaskRecord(sourceType int, sourceId uint64, name string) (resp *types.SopTaskRecordInfo, err error) {
	stageTotalCount, _ := l.svcCtx.DB.MessageRecords.Query().
		Where(messagerecords.SourceType(sourceType), messagerecords.SourceID(sourceId)).
		Count(l.ctx)
	stageSuccessCount, _ := l.svcCtx.DB.MessageRecords.Query().
		Where(messagerecords.SourceTypeEQ(sourceType), messagerecords.SourceID(sourceId), messagerecords.Status(3)).
		Count(l.ctx)
	totalCountInt64 := int64(stageTotalCount)
	successCountInt64 := int64(stageSuccessCount)
	failureCount := totalCountInt64 - successCountInt64
	successRate := int64(0)
	if totalCountInt64 != 0 {
		successRate = successCountInt64 * 100 / totalCountInt64
	}
	return &types.SopTaskRecordInfo{
		SourceType:   &sourceType,
		SourceId:     &sourceId,
		Name:         &name,
		TotalCount:   &totalCountInt64,
		SuccessCount: &successCountInt64,
		FailureCount: &failureCount,
		SuccessRate:  &successRate,
	}, nil
}
