package sop_stage

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

	"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 UpdateSopStageLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *UpdateSopStageLogic) UpdateSopStage(req *types.SopStageInfo) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	// 根据 id 关联查询 task 信息，并判断 task 的状态是否为 1
	data, err := l.svcCtx.DB.SopStage.Query().
		Where(sopstage.ID(*req.Id)).
		WithSopTask().
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}
	task := data.Edges.SopTask
	if task.Status != 1 || task.OrganizationID != organizationId {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	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.UpdateOneID(*req.Id).
		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(req.IndexSort)

	if forward != nil {
		createStmt.SetActionForward(forward)
	} else {
		createStmt.ClearActionForward()
	}

	err = createStmt.Exec(l.ctx)

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

	return &types.BaseMsgResp{Msg: errormsg.UpdateSuccess}, nil
}
