package sop_stage

import (
	"context"
	"wechat-api/ent/custom_types"
	"wechat-api/ent/sopstage"
	"wechat-api/ent/soptask"

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

	"github.com/suyuan32/simple-admin-common/msg/errormsg"

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

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

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

func (l *CreateSopStageLogic) CreateSopStage(req *types.SopStageInfo) (*types.SopStageCreateResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	// 根据 task_id 查询 task 是否存在
	task, err := l.svcCtx.DB.SopTask.Query().
		Where(soptask.ID(*req.TaskId), soptask.OrganizationIDEQ(organizationId)).
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	// 判断 task 的状态是否为 1
	if task.Status != 1 {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	// 查询某 task_id 下的 stage 的数量
	count, err := l.svcCtx.DB.SopStage.Query().Where(sopstage.TaskIDEQ(*req.TaskId)).Count(l.ctx)
	count += 1

	var conditionList []custom_types.Condition
	if len(req.ConditionList) > 0 {
		conditionList = make([]custom_types.Condition, len(req.ConditionList))
		for i, condition := range req.ConditionList {
			conditionList[i] = custom_types.Condition{
				Equal:       condition.Equal,
				LabelIdList: condition.LabelIdList,
			}
		}
	}

	var actionMessage []custom_types.Action
	if len(req.ActionMessage) > 0 {
		actionMessage = make([]custom_types.Action, len(req.ActionMessage))
		for i, condition := range req.ActionMessage {
			if condition.Type == 1 {
				actionMessage[i] = custom_types.Action{
					Type:    condition.Type,
					Content: condition.Content,
				}
			} else {
				actionMessage[i] = custom_types.Action{
					Type:    condition.Type,
					Content: condition.Content,
					Meta: &custom_types.Meta{
						Filename: condition.Meta.Filename,
					},
				}
			}
		}
	}

	var forward *custom_types.ActionForward
	if req.ActionForward != nil {
		forward = &custom_types.ActionForward{}
		forward.Wxid = req.ActionForward.Wxid
		var forwardAction []custom_types.Action
		if len(req.ActionForward.Action) > 0 {
			forwardAction = make([]custom_types.Action, len(req.ActionForward.Action))
			for i, condition := range req.ActionForward.Action {
				if condition.Type == 1 {
					forwardAction[i] = custom_types.Action{
						Type:    condition.Type,
						Content: condition.Content,
					}
				} else {
					forwardAction[i] = custom_types.Action{
						Type:    condition.Type,
						Content: condition.Content,
						Meta: &custom_types.Meta{
							Filename: condition.Meta.Filename,
						},
					}
				}
			}
		}
		forward.Action = forwardAction
	} else {
		forward = nil
	}

	createStmt := l.svcCtx.DB.SopStage.Create().
		SetNotNilStatus(req.Status).
		SetNotNilTaskID(req.TaskId).
		SetNotNilName(req.Name).
		SetNotNilConditionType(req.ConditionType).
		SetNotNilConditionOperator(req.ConditionOperator).
		SetNotNilConditionList(conditionList).
		SetNotNilActionMessage(actionMessage).
		SetNotNilActionLabelAdd(req.ActionLabelAdd).
		SetNotNilActionLabelDel(req.ActionLabelDel).
		SetNotNilIndexSort(&count)
	if forward != nil {
		createStmt.SetActionForward(forward)
	}
	newStage, err := createStmt.Save(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	return &types.SopStageCreateResp{BaseDataInfo: types.BaseDataInfo{Msg: errormsg.CreateSuccess}, Data: newStage.ID}, nil
}
