package sop_task

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"wechat-api/ent"
	"wechat-api/ent/custom_types"
	"wechat-api/ent/label"
	"wechat-api/ent/sopnode"
	"wechat-api/ent/soptask"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

func (l *SopTaskCopyLogic) SopTaskCopy(req *types.CopyReq) (resp *types.BaseMsgResp, err error) {
	isAdmin := l.ctx.Value("isAdmin").(bool)
	organizationId := l.ctx.Value("organizationId").(uint64)

	//  目标组织ID
	var targetOrganizationId uint64
	if isAdmin {
		if req.OrganizationId == 0 {
			targetOrganizationId = organizationId
		} else {
			targetOrganizationId = req.OrganizationId
		}
	} else {
		targetOrganizationId = organizationId
	}

	//  查询任务及阶段
	data, err := l.svcCtx.DB.SopTask.Query().
		Where(soptask.ID(req.Id), soptask.OrganizationIDEQ(organizationId)).
		WithTaskStages().
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	//  开始事务
	tx, err := l.svcCtx.DB.Tx(context.Background())
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	//  创建新任务
	newTask, err := tx.SopTask.Create().
		SetName(*req.Name).
		SetType(data.Type).
		SetOrganizationID(targetOrganizationId).
		Save(l.ctx)
	if err != nil {
		_ = tx.Rollback()
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	//  创建新阶段
	for _, s := range data.Edges.TaskStages {
		newConditionList := make([]custom_types.Condition, 0)
		for _, c := range s.ConditionList {
			newLabels, err := CreateLabels(tx, c.LabelIdList, targetOrganizationId, l.ctx, l.Logger)
			if err != nil {
				_ = tx.Rollback()
				return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
			}
			c.LabelIdList = newLabels
			newConditionList = append(newConditionList, c)
		}
		newLabelAdd, err := CreateLabels(tx, s.ActionLabelAdd, targetOrganizationId, l.ctx, l.Logger)
		if err != nil {
			_ = tx.Rollback()
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
		newLabelDel, err := CreateLabels(tx, s.ActionLabelDel, targetOrganizationId, l.ctx, l.Logger)
		if err != nil {
			_ = tx.Rollback()
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
		newStage, err := tx.SopStage.Create().
			SetTaskID(newTask.ID).
			SetName(s.Name).
			SetConditionType(s.ConditionType).
			SetConditionOperator(s.ConditionOperator).
			SetConditionList(newConditionList).
			SetNotNilActionMessage(s.ActionMessage).
			SetNotNilActionLabelAdd(newLabelAdd).
			SetNotNilActionLabelDel(newLabelDel).
			SetNotNilActionForward(&s.ActionForward).
			SetIndexSort(s.IndexSort).
			Save(l.ctx)
		if err != nil {
			_ = tx.Rollback()
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
		err = CreateNodes(tx, s.ID, 0, newStage.ID, 0, targetOrganizationId, l.ctx, l.Logger)
		if err != nil {
			_ = tx.Rollback()
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
	}

	// 所有操作成功，提交事务
	err = tx.Commit()
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

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

func CreateNodes(tx *ent.Tx, stageId uint64, parentId uint64, newStageId uint64, newParentId uint64, targetOrganizationId uint64, ctx context.Context, logger logx.Logger) (err error) {
	data, err := tx.SopNode.Query().
		Where(sopnode.StageID(stageId), sopnode.ParentID(parentId)).All(ctx)
	if err != nil {
		return nil
	}

	for _, n := range data {
		newLabelAdd, err := CreateLabels(tx, n.ActionLabelAdd, targetOrganizationId, ctx, logger)
		if err != nil {
			_ = tx.Rollback()
			return err
		}
		newLabelDel, err := CreateLabels(tx, n.ActionLabelDel, targetOrganizationId, ctx, logger)
		if err != nil {
			_ = tx.Rollback()
			return err
		}
		newNode, err := tx.SopNode.Create().
			SetStageID(newStageId).
			SetParentID(newParentId).
			SetName(n.Name).
			SetConditionType(n.ConditionType).
			SetConditionList(n.ConditionList).
			SetNotNilNoReplyCondition(&n.NoReplyCondition).
			SetNotNilActionMessage(n.ActionMessage).
			SetNotNilActionLabelAdd(newLabelAdd).
			SetNotNilActionLabelDel(newLabelDel).
			SetNotNilActionForward(&n.ActionForward).
			Save(ctx)
		if err != nil {
			return err
		}
		err = CreateNodes(tx, stageId, n.ID, newStageId, newNode.ID, targetOrganizationId, ctx, logger)
		if err != nil {
			return err
		}
	}
	return nil
}

func CreateLabels(tx *ent.Tx, labels []uint64, targetOrganizationId uint64, ctx context.Context, logger logx.Logger) ([]uint64, error) {
	newLabels := make([]uint64, 0)

	// 查询标签
	data, err := tx.Label.Query().Where(label.IDIn(labels...)).All(ctx)
	if err != nil {
		return nil, err
	}
	// 创建标签
	for _, l := range data {
		// 判断标签是否存在
		ol, err := tx.Label.Query().
			Where(
				label.NameEQ(l.Name),                       // Filter by ID
				label.OrganizationID(targetOrganizationId), // Additional filter by organizationId
			).
			Only(ctx)
		if err != nil && !ent.IsNotFound(err) {
			return nil, err
		}
		if ol != nil {
			newLabels = append(newLabels, ol.ID)
		} else {
			var conditions = "{}"
			nl, err := tx.Label.Create().
				SetType(1).
				SetName(l.Name).
				SetFrom(1).
				SetMode(1).
				SetOrganizationID(targetOrganizationId).
				SetConditions(conditions).
				Save(ctx)
			if err != nil {
				return nil, err
			}
			newLabels = append(newLabels, nl.ID)
		}
	}
	return newLabels, nil
}
