// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"errors"
	"fmt"
	"time"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/department"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/user"
	"git.noahlan.cn/noahlan/ntool-biz/core/orm/nent/types"
)

// DepartmentCreate is the builder for creating a Department entity.
type DepartmentCreate struct {
	config
	mutation *DepartmentMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetCreatedAt sets the "created_at" field.
func (dc *DepartmentCreate) SetCreatedAt(t time.Time) *DepartmentCreate {
	dc.mutation.SetCreatedAt(t)
	return dc
}

// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (dc *DepartmentCreate) SetNillableCreatedAt(t *time.Time) *DepartmentCreate {
	if t != nil {
		dc.SetCreatedAt(*t)
	}
	return dc
}

// SetUpdatedAt sets the "updated_at" field.
func (dc *DepartmentCreate) SetUpdatedAt(t time.Time) *DepartmentCreate {
	dc.mutation.SetUpdatedAt(t)
	return dc
}

// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (dc *DepartmentCreate) SetNillableUpdatedAt(t *time.Time) *DepartmentCreate {
	if t != nil {
		dc.SetUpdatedAt(*t)
	}
	return dc
}

// SetStatus sets the "status" field.
func (dc *DepartmentCreate) SetStatus(t types.Status) *DepartmentCreate {
	dc.mutation.SetStatus(t)
	return dc
}

// SetNillableStatus sets the "status" field if the given value is not nil.
func (dc *DepartmentCreate) SetNillableStatus(t *types.Status) *DepartmentCreate {
	if t != nil {
		dc.SetStatus(*t)
	}
	return dc
}

// SetVersion sets the "version" field.
func (dc *DepartmentCreate) SetVersion(i int64) *DepartmentCreate {
	dc.mutation.SetVersion(i)
	return dc
}

// SetNillableVersion sets the "version" field if the given value is not nil.
func (dc *DepartmentCreate) SetNillableVersion(i *int64) *DepartmentCreate {
	if i != nil {
		dc.SetVersion(*i)
	}
	return dc
}

// SetName sets the "name" field.
func (dc *DepartmentCreate) SetName(s string) *DepartmentCreate {
	dc.mutation.SetName(s)
	return dc
}

// SetLeaderID sets the "leader_id" field.
func (dc *DepartmentCreate) SetLeaderID(i int64) *DepartmentCreate {
	dc.mutation.SetLeaderID(i)
	return dc
}

// SetNillableLeaderID sets the "leader_id" field if the given value is not nil.
func (dc *DepartmentCreate) SetNillableLeaderID(i *int64) *DepartmentCreate {
	if i != nil {
		dc.SetLeaderID(*i)
	}
	return dc
}

// SetRemark sets the "remark" field.
func (dc *DepartmentCreate) SetRemark(s string) *DepartmentCreate {
	dc.mutation.SetRemark(s)
	return dc
}

// SetNillableRemark sets the "remark" field if the given value is not nil.
func (dc *DepartmentCreate) SetNillableRemark(s *string) *DepartmentCreate {
	if s != nil {
		dc.SetRemark(*s)
	}
	return dc
}

// SetParentID sets the "parent_id" field.
func (dc *DepartmentCreate) SetParentID(i int64) *DepartmentCreate {
	dc.mutation.SetParentID(i)
	return dc
}

// SetNillableParentID sets the "parent_id" field if the given value is not nil.
func (dc *DepartmentCreate) SetNillableParentID(i *int64) *DepartmentCreate {
	if i != nil {
		dc.SetParentID(*i)
	}
	return dc
}

// SetID sets the "id" field.
func (dc *DepartmentCreate) SetID(i int64) *DepartmentCreate {
	dc.mutation.SetID(i)
	return dc
}

// SetNillableID sets the "id" field if the given value is not nil.
func (dc *DepartmentCreate) SetNillableID(i *int64) *DepartmentCreate {
	if i != nil {
		dc.SetID(*i)
	}
	return dc
}

// SetParent sets the "parent" edge to the Department entity.
func (dc *DepartmentCreate) SetParent(d *Department) *DepartmentCreate {
	return dc.SetParentID(d.ID)
}

// AddChildIDs adds the "children" edge to the Department entity by IDs.
func (dc *DepartmentCreate) AddChildIDs(ids ...int64) *DepartmentCreate {
	dc.mutation.AddChildIDs(ids...)
	return dc
}

// AddChildren adds the "children" edges to the Department entity.
func (dc *DepartmentCreate) AddChildren(d ...*Department) *DepartmentCreate {
	ids := make([]int64, len(d))
	for i := range d {
		ids[i] = d[i].ID
	}
	return dc.AddChildIDs(ids...)
}

// AddUserIDs adds the "users" edge to the User entity by IDs.
func (dc *DepartmentCreate) AddUserIDs(ids ...int64) *DepartmentCreate {
	dc.mutation.AddUserIDs(ids...)
	return dc
}

// AddUsers adds the "users" edges to the User entity.
func (dc *DepartmentCreate) AddUsers(u ...*User) *DepartmentCreate {
	ids := make([]int64, len(u))
	for i := range u {
		ids[i] = u[i].ID
	}
	return dc.AddUserIDs(ids...)
}

// SetLeader sets the "leader" edge to the User entity.
func (dc *DepartmentCreate) SetLeader(u *User) *DepartmentCreate {
	return dc.SetLeaderID(u.ID)
}

// Mutation returns the DepartmentMutation object of the builder.
func (dc *DepartmentCreate) Mutation() *DepartmentMutation {
	return dc.mutation
}

// Save creates the Department in the database.
func (dc *DepartmentCreate) Save(ctx context.Context) (*Department, error) {
	if err := dc.defaults(); err != nil {
		return nil, err
	}
	return withHooks(ctx, dc.sqlSave, dc.mutation, dc.hooks)
}

// SaveX calls Save and panics if Save returns an error.
func (dc *DepartmentCreate) SaveX(ctx context.Context) *Department {
	v, err := dc.Save(ctx)
	if err != nil {
		panic(err)
	}
	return v
}

// Exec executes the query.
func (dc *DepartmentCreate) Exec(ctx context.Context) error {
	_, err := dc.Save(ctx)
	return err
}

// ExecX is like Exec, but panics if an error occurs.
func (dc *DepartmentCreate) ExecX(ctx context.Context) {
	if err := dc.Exec(ctx); err != nil {
		panic(err)
	}
}

// defaults sets the default values of the builder before save.
func (dc *DepartmentCreate) defaults() error {
	if _, ok := dc.mutation.CreatedAt(); !ok {
		if department.DefaultCreatedAt == nil {
			return fmt.Errorf("ent: uninitialized department.DefaultCreatedAt (forgotten import ent/runtime?)")
		}
		v := department.DefaultCreatedAt()
		dc.mutation.SetCreatedAt(v)
	}
	if _, ok := dc.mutation.UpdatedAt(); !ok {
		if department.DefaultUpdatedAt == nil {
			return fmt.Errorf("ent: uninitialized department.DefaultUpdatedAt (forgotten import ent/runtime?)")
		}
		v := department.DefaultUpdatedAt()
		dc.mutation.SetUpdatedAt(v)
	}
	if _, ok := dc.mutation.Status(); !ok {
		v := department.DefaultStatus
		dc.mutation.SetStatus(v)
	}
	if _, ok := dc.mutation.Version(); !ok {
		v := department.DefaultVersion
		dc.mutation.SetVersion(v)
	}
	if _, ok := dc.mutation.ID(); !ok {
		if department.DefaultID == nil {
			return fmt.Errorf("ent: uninitialized department.DefaultID (forgotten import ent/runtime?)")
		}
		v := department.DefaultID()
		dc.mutation.SetID(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (dc *DepartmentCreate) check() error {
	if _, ok := dc.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Department.created_at"`)}
	}
	if _, ok := dc.mutation.UpdatedAt(); !ok {
		return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Department.updated_at"`)}
	}
	if _, ok := dc.mutation.Status(); !ok {
		return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "Department.status"`)}
	}
	if v, ok := dc.mutation.Status(); ok {
		if err := department.StatusValidator(v); err != nil {
			return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Department.status": %w`, err)}
		}
	}
	if _, ok := dc.mutation.Version(); !ok {
		return &ValidationError{Name: "version", err: errors.New(`ent: missing required field "Department.version"`)}
	}
	if _, ok := dc.mutation.Name(); !ok {
		return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Department.name"`)}
	}
	return nil
}

func (dc *DepartmentCreate) sqlSave(ctx context.Context) (*Department, error) {
	if err := dc.check(); err != nil {
		return nil, err
	}
	_node, _spec := dc.createSpec()
	if err := sqlgraph.CreateNode(ctx, dc.driver, _spec); err != nil {
		if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	if _spec.ID.Value != _node.ID {
		id := _spec.ID.Value.(int64)
		_node.ID = int64(id)
	}
	dc.mutation.id = &_node.ID
	dc.mutation.done = true
	return _node, nil
}

func (dc *DepartmentCreate) createSpec() (*Department, *sqlgraph.CreateSpec) {
	var (
		_node = &Department{config: dc.config}
		_spec = sqlgraph.NewCreateSpec(department.Table, sqlgraph.NewFieldSpec(department.FieldID, field.TypeInt64))
	)
	_spec.OnConflict = dc.conflict
	if id, ok := dc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = id
	}
	if value, ok := dc.mutation.CreatedAt(); ok {
		_spec.SetField(department.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := dc.mutation.UpdatedAt(); ok {
		_spec.SetField(department.FieldUpdatedAt, field.TypeTime, value)
		_node.UpdatedAt = value
	}
	if value, ok := dc.mutation.Status(); ok {
		_spec.SetField(department.FieldStatus, field.TypeEnum, value)
		_node.Status = value
	}
	if value, ok := dc.mutation.Version(); ok {
		_spec.SetField(department.FieldVersion, field.TypeInt64, value)
		_node.Version = value
	}
	if value, ok := dc.mutation.Name(); ok {
		_spec.SetField(department.FieldName, field.TypeString, value)
		_node.Name = value
	}
	if value, ok := dc.mutation.Remark(); ok {
		_spec.SetField(department.FieldRemark, field.TypeString, value)
		_node.Remark = value
	}
	if nodes := dc.mutation.ParentIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   department.ParentTable,
			Columns: []string{department.ParentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(department.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.ParentID = nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := dc.mutation.ChildrenIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   department.ChildrenTable,
			Columns: []string{department.ChildrenColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(department.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := dc.mutation.UsersIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: true,
			Table:   department.UsersTable,
			Columns: department.UsersPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := dc.mutation.LeaderIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: false,
			Table:   department.LeaderTable,
			Columns: []string{department.LeaderColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.LeaderID = nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.Department.Create().
//		SetCreatedAt(v).
//		OnConflict(
//			// Update the row with the new values
//			// the was proposed for insertion.
//			sql.ResolveWithNewValues(),
//		).
//		// Override some of the fields with custom
//		// update values.
//		Update(func(u *ent.DepartmentUpsert) {
//			SetCreatedAt(v+v).
//		}).
//		Exec(ctx)
func (dc *DepartmentCreate) OnConflict(opts ...sql.ConflictOption) *DepartmentUpsertOne {
	dc.conflict = opts
	return &DepartmentUpsertOne{
		create: dc,
	}
}

// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
//	client.Department.Create().
//		OnConflict(sql.ConflictColumns(columns...)).
//		Exec(ctx)
func (dc *DepartmentCreate) OnConflictColumns(columns ...string) *DepartmentUpsertOne {
	dc.conflict = append(dc.conflict, sql.ConflictColumns(columns...))
	return &DepartmentUpsertOne{
		create: dc,
	}
}

type (
	// DepartmentUpsertOne is the builder for "upsert"-ing
	//  one Department node.
	DepartmentUpsertOne struct {
		create *DepartmentCreate
	}

	// DepartmentUpsert is the "OnConflict" setter.
	DepartmentUpsert struct {
		*sql.UpdateSet
	}
)

// SetUpdatedAt sets the "updated_at" field.
func (u *DepartmentUpsert) SetUpdatedAt(v time.Time) *DepartmentUpsert {
	u.Set(department.FieldUpdatedAt, v)
	return u
}

// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *DepartmentUpsert) UpdateUpdatedAt() *DepartmentUpsert {
	u.SetExcluded(department.FieldUpdatedAt)
	return u
}

// SetStatus sets the "status" field.
func (u *DepartmentUpsert) SetStatus(v types.Status) *DepartmentUpsert {
	u.Set(department.FieldStatus, v)
	return u
}

// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *DepartmentUpsert) UpdateStatus() *DepartmentUpsert {
	u.SetExcluded(department.FieldStatus)
	return u
}

// SetVersion sets the "version" field.
func (u *DepartmentUpsert) SetVersion(v int64) *DepartmentUpsert {
	u.Set(department.FieldVersion, v)
	return u
}

// UpdateVersion sets the "version" field to the value that was provided on create.
func (u *DepartmentUpsert) UpdateVersion() *DepartmentUpsert {
	u.SetExcluded(department.FieldVersion)
	return u
}

// AddVersion adds v to the "version" field.
func (u *DepartmentUpsert) AddVersion(v int64) *DepartmentUpsert {
	u.Add(department.FieldVersion, v)
	return u
}

// SetName sets the "name" field.
func (u *DepartmentUpsert) SetName(v string) *DepartmentUpsert {
	u.Set(department.FieldName, v)
	return u
}

// UpdateName sets the "name" field to the value that was provided on create.
func (u *DepartmentUpsert) UpdateName() *DepartmentUpsert {
	u.SetExcluded(department.FieldName)
	return u
}

// SetLeaderID sets the "leader_id" field.
func (u *DepartmentUpsert) SetLeaderID(v int64) *DepartmentUpsert {
	u.Set(department.FieldLeaderID, v)
	return u
}

// UpdateLeaderID sets the "leader_id" field to the value that was provided on create.
func (u *DepartmentUpsert) UpdateLeaderID() *DepartmentUpsert {
	u.SetExcluded(department.FieldLeaderID)
	return u
}

// ClearLeaderID clears the value of the "leader_id" field.
func (u *DepartmentUpsert) ClearLeaderID() *DepartmentUpsert {
	u.SetNull(department.FieldLeaderID)
	return u
}

// SetRemark sets the "remark" field.
func (u *DepartmentUpsert) SetRemark(v string) *DepartmentUpsert {
	u.Set(department.FieldRemark, v)
	return u
}

// UpdateRemark sets the "remark" field to the value that was provided on create.
func (u *DepartmentUpsert) UpdateRemark() *DepartmentUpsert {
	u.SetExcluded(department.FieldRemark)
	return u
}

// ClearRemark clears the value of the "remark" field.
func (u *DepartmentUpsert) ClearRemark() *DepartmentUpsert {
	u.SetNull(department.FieldRemark)
	return u
}

// SetParentID sets the "parent_id" field.
func (u *DepartmentUpsert) SetParentID(v int64) *DepartmentUpsert {
	u.Set(department.FieldParentID, v)
	return u
}

// UpdateParentID sets the "parent_id" field to the value that was provided on create.
func (u *DepartmentUpsert) UpdateParentID() *DepartmentUpsert {
	u.SetExcluded(department.FieldParentID)
	return u
}

// ClearParentID clears the value of the "parent_id" field.
func (u *DepartmentUpsert) ClearParentID() *DepartmentUpsert {
	u.SetNull(department.FieldParentID)
	return u
}

// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
// Using this option is equivalent to using:
//
//	client.Department.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(department.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *DepartmentUpsertOne) UpdateNewValues() *DepartmentUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
		if _, exists := u.create.mutation.ID(); exists {
			s.SetIgnore(department.FieldID)
		}
		if _, exists := u.create.mutation.CreatedAt(); exists {
			s.SetIgnore(department.FieldCreatedAt)
		}
	}))
	return u
}

// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
//	client.Department.Create().
//	    OnConflict(sql.ResolveWithIgnore()).
//	    Exec(ctx)
func (u *DepartmentUpsertOne) Ignore() *DepartmentUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
	return u
}

// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *DepartmentUpsertOne) DoNothing() *DepartmentUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

// Update allows overriding fields `UPDATE` values. See the DepartmentCreate.OnConflict
// documentation for more info.
func (u *DepartmentUpsertOne) Update(set func(*DepartmentUpsert)) *DepartmentUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
		set(&DepartmentUpsert{UpdateSet: update})
	}))
	return u
}

// SetUpdatedAt sets the "updated_at" field.
func (u *DepartmentUpsertOne) SetUpdatedAt(v time.Time) *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetUpdatedAt(v)
	})
}

// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *DepartmentUpsertOne) UpdateUpdatedAt() *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateUpdatedAt()
	})
}

// SetStatus sets the "status" field.
func (u *DepartmentUpsertOne) SetStatus(v types.Status) *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetStatus(v)
	})
}

// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *DepartmentUpsertOne) UpdateStatus() *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateStatus()
	})
}

// SetVersion sets the "version" field.
func (u *DepartmentUpsertOne) SetVersion(v int64) *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetVersion(v)
	})
}

// AddVersion adds v to the "version" field.
func (u *DepartmentUpsertOne) AddVersion(v int64) *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.AddVersion(v)
	})
}

// UpdateVersion sets the "version" field to the value that was provided on create.
func (u *DepartmentUpsertOne) UpdateVersion() *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateVersion()
	})
}

// SetName sets the "name" field.
func (u *DepartmentUpsertOne) SetName(v string) *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetName(v)
	})
}

// UpdateName sets the "name" field to the value that was provided on create.
func (u *DepartmentUpsertOne) UpdateName() *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateName()
	})
}

// SetLeaderID sets the "leader_id" field.
func (u *DepartmentUpsertOne) SetLeaderID(v int64) *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetLeaderID(v)
	})
}

// UpdateLeaderID sets the "leader_id" field to the value that was provided on create.
func (u *DepartmentUpsertOne) UpdateLeaderID() *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateLeaderID()
	})
}

// ClearLeaderID clears the value of the "leader_id" field.
func (u *DepartmentUpsertOne) ClearLeaderID() *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.ClearLeaderID()
	})
}

// SetRemark sets the "remark" field.
func (u *DepartmentUpsertOne) SetRemark(v string) *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetRemark(v)
	})
}

// UpdateRemark sets the "remark" field to the value that was provided on create.
func (u *DepartmentUpsertOne) UpdateRemark() *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateRemark()
	})
}

// ClearRemark clears the value of the "remark" field.
func (u *DepartmentUpsertOne) ClearRemark() *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.ClearRemark()
	})
}

// SetParentID sets the "parent_id" field.
func (u *DepartmentUpsertOne) SetParentID(v int64) *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetParentID(v)
	})
}

// UpdateParentID sets the "parent_id" field to the value that was provided on create.
func (u *DepartmentUpsertOne) UpdateParentID() *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateParentID()
	})
}

// ClearParentID clears the value of the "parent_id" field.
func (u *DepartmentUpsertOne) ClearParentID() *DepartmentUpsertOne {
	return u.Update(func(s *DepartmentUpsert) {
		s.ClearParentID()
	})
}

// Exec executes the query.
func (u *DepartmentUpsertOne) Exec(ctx context.Context) error {
	if len(u.create.conflict) == 0 {
		return errors.New("ent: missing options for DepartmentCreate.OnConflict")
	}
	return u.create.Exec(ctx)
}

// ExecX is like Exec, but panics if an error occurs.
func (u *DepartmentUpsertOne) ExecX(ctx context.Context) {
	if err := u.create.Exec(ctx); err != nil {
		panic(err)
	}
}

// Exec executes the UPSERT query and returns the inserted/updated ID.
func (u *DepartmentUpsertOne) ID(ctx context.Context) (id int64, err error) {
	node, err := u.create.Save(ctx)
	if err != nil {
		return id, err
	}
	return node.ID, nil
}

// IDX is like ID, but panics if an error occurs.
func (u *DepartmentUpsertOne) IDX(ctx context.Context) int64 {
	id, err := u.ID(ctx)
	if err != nil {
		panic(err)
	}
	return id
}

// DepartmentCreateBulk is the builder for creating many Department entities in bulk.
type DepartmentCreateBulk struct {
	config
	builders []*DepartmentCreate
	conflict []sql.ConflictOption
}

// Save creates the Department entities in the database.
func (dcb *DepartmentCreateBulk) Save(ctx context.Context) ([]*Department, error) {
	specs := make([]*sqlgraph.CreateSpec, len(dcb.builders))
	nodes := make([]*Department, len(dcb.builders))
	mutators := make([]Mutator, len(dcb.builders))
	for i := range dcb.builders {
		func(i int, root context.Context) {
			builder := dcb.builders[i]
			builder.defaults()
			var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
				mutation, ok := m.(*DepartmentMutation)
				if !ok {
					return nil, fmt.Errorf("unexpected mutation type %T", m)
				}
				if err := builder.check(); err != nil {
					return nil, err
				}
				builder.mutation = mutation
				var err error
				nodes[i], specs[i] = builder.createSpec()
				if i < len(mutators)-1 {
					_, err = mutators[i+1].Mutate(root, dcb.builders[i+1].mutation)
				} else {
					spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
					spec.OnConflict = dcb.conflict
					// Invoke the actual operation on the latest mutation in the chain.
					if err = sqlgraph.BatchCreate(ctx, dcb.driver, spec); err != nil {
						if sqlgraph.IsConstraintError(err) {
							err = &ConstraintError{msg: err.Error(), wrap: err}
						}
					}
				}
				if err != nil {
					return nil, err
				}
				mutation.id = &nodes[i].ID
				if specs[i].ID.Value != nil && nodes[i].ID == 0 {
					id := specs[i].ID.Value.(int64)
					nodes[i].ID = int64(id)
				}
				mutation.done = true
				return nodes[i], nil
			})
			for i := len(builder.hooks) - 1; i >= 0; i-- {
				mut = builder.hooks[i](mut)
			}
			mutators[i] = mut
		}(i, ctx)
	}
	if len(mutators) > 0 {
		if _, err := mutators[0].Mutate(ctx, dcb.builders[0].mutation); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

// SaveX is like Save, but panics if an error occurs.
func (dcb *DepartmentCreateBulk) SaveX(ctx context.Context) []*Department {
	v, err := dcb.Save(ctx)
	if err != nil {
		panic(err)
	}
	return v
}

// Exec executes the query.
func (dcb *DepartmentCreateBulk) Exec(ctx context.Context) error {
	_, err := dcb.Save(ctx)
	return err
}

// ExecX is like Exec, but panics if an error occurs.
func (dcb *DepartmentCreateBulk) ExecX(ctx context.Context) {
	if err := dcb.Exec(ctx); err != nil {
		panic(err)
	}
}

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.Department.CreateBulk(builders...).
//		OnConflict(
//			// Update the row with the new values
//			// the was proposed for insertion.
//			sql.ResolveWithNewValues(),
//		).
//		// Override some of the fields with custom
//		// update values.
//		Update(func(u *ent.DepartmentUpsert) {
//			SetCreatedAt(v+v).
//		}).
//		Exec(ctx)
func (dcb *DepartmentCreateBulk) OnConflict(opts ...sql.ConflictOption) *DepartmentUpsertBulk {
	dcb.conflict = opts
	return &DepartmentUpsertBulk{
		create: dcb,
	}
}

// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
//	client.Department.Create().
//		OnConflict(sql.ConflictColumns(columns...)).
//		Exec(ctx)
func (dcb *DepartmentCreateBulk) OnConflictColumns(columns ...string) *DepartmentUpsertBulk {
	dcb.conflict = append(dcb.conflict, sql.ConflictColumns(columns...))
	return &DepartmentUpsertBulk{
		create: dcb,
	}
}

// DepartmentUpsertBulk is the builder for "upsert"-ing
// a bulk of Department nodes.
type DepartmentUpsertBulk struct {
	create *DepartmentCreateBulk
}

// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
//	client.Department.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(department.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *DepartmentUpsertBulk) UpdateNewValues() *DepartmentUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
		for _, b := range u.create.builders {
			if _, exists := b.mutation.ID(); exists {
				s.SetIgnore(department.FieldID)
			}
			if _, exists := b.mutation.CreatedAt(); exists {
				s.SetIgnore(department.FieldCreatedAt)
			}
		}
	}))
	return u
}

// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
//	client.Department.Create().
//		OnConflict(sql.ResolveWithIgnore()).
//		Exec(ctx)
func (u *DepartmentUpsertBulk) Ignore() *DepartmentUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
	return u
}

// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *DepartmentUpsertBulk) DoNothing() *DepartmentUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

// Update allows overriding fields `UPDATE` values. See the DepartmentCreateBulk.OnConflict
// documentation for more info.
func (u *DepartmentUpsertBulk) Update(set func(*DepartmentUpsert)) *DepartmentUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
		set(&DepartmentUpsert{UpdateSet: update})
	}))
	return u
}

// SetUpdatedAt sets the "updated_at" field.
func (u *DepartmentUpsertBulk) SetUpdatedAt(v time.Time) *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetUpdatedAt(v)
	})
}

// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *DepartmentUpsertBulk) UpdateUpdatedAt() *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateUpdatedAt()
	})
}

// SetStatus sets the "status" field.
func (u *DepartmentUpsertBulk) SetStatus(v types.Status) *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetStatus(v)
	})
}

// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *DepartmentUpsertBulk) UpdateStatus() *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateStatus()
	})
}

// SetVersion sets the "version" field.
func (u *DepartmentUpsertBulk) SetVersion(v int64) *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetVersion(v)
	})
}

// AddVersion adds v to the "version" field.
func (u *DepartmentUpsertBulk) AddVersion(v int64) *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.AddVersion(v)
	})
}

// UpdateVersion sets the "version" field to the value that was provided on create.
func (u *DepartmentUpsertBulk) UpdateVersion() *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateVersion()
	})
}

// SetName sets the "name" field.
func (u *DepartmentUpsertBulk) SetName(v string) *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetName(v)
	})
}

// UpdateName sets the "name" field to the value that was provided on create.
func (u *DepartmentUpsertBulk) UpdateName() *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateName()
	})
}

// SetLeaderID sets the "leader_id" field.
func (u *DepartmentUpsertBulk) SetLeaderID(v int64) *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetLeaderID(v)
	})
}

// UpdateLeaderID sets the "leader_id" field to the value that was provided on create.
func (u *DepartmentUpsertBulk) UpdateLeaderID() *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateLeaderID()
	})
}

// ClearLeaderID clears the value of the "leader_id" field.
func (u *DepartmentUpsertBulk) ClearLeaderID() *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.ClearLeaderID()
	})
}

// SetRemark sets the "remark" field.
func (u *DepartmentUpsertBulk) SetRemark(v string) *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetRemark(v)
	})
}

// UpdateRemark sets the "remark" field to the value that was provided on create.
func (u *DepartmentUpsertBulk) UpdateRemark() *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateRemark()
	})
}

// ClearRemark clears the value of the "remark" field.
func (u *DepartmentUpsertBulk) ClearRemark() *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.ClearRemark()
	})
}

// SetParentID sets the "parent_id" field.
func (u *DepartmentUpsertBulk) SetParentID(v int64) *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.SetParentID(v)
	})
}

// UpdateParentID sets the "parent_id" field to the value that was provided on create.
func (u *DepartmentUpsertBulk) UpdateParentID() *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.UpdateParentID()
	})
}

// ClearParentID clears the value of the "parent_id" field.
func (u *DepartmentUpsertBulk) ClearParentID() *DepartmentUpsertBulk {
	return u.Update(func(s *DepartmentUpsert) {
		s.ClearParentID()
	})
}

// Exec executes the query.
func (u *DepartmentUpsertBulk) Exec(ctx context.Context) error {
	for i, b := range u.create.builders {
		if len(b.conflict) != 0 {
			return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the DepartmentCreateBulk instead", i)
		}
	}
	if len(u.create.conflict) == 0 {
		return errors.New("ent: missing options for DepartmentCreateBulk.OnConflict")
	}
	return u.create.Exec(ctx)
}

// ExecX is like Exec, but panics if an error occurs.
func (u *DepartmentUpsertBulk) ExecX(ctx context.Context) {
	if err := u.create.Exec(ctx); err != nil {
		panic(err)
	}
}
