// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"errors"
	"fmt"
	"time"
	"wechat-api/ent/employee"
	"wechat-api/ent/predicate"
	"wechat-api/ent/tutorial"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
)

// TutorialUpdate is the builder for updating Tutorial entities.
type TutorialUpdate struct {
	config
	hooks    []Hook
	mutation *TutorialMutation
}

// Where appends a list predicates to the TutorialUpdate builder.
func (tu *TutorialUpdate) Where(ps ...predicate.Tutorial) *TutorialUpdate {
	tu.mutation.Where(ps...)
	return tu
}

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

// SetDeletedAt sets the "deleted_at" field.
func (tu *TutorialUpdate) SetDeletedAt(t time.Time) *TutorialUpdate {
	tu.mutation.SetDeletedAt(t)
	return tu
}

// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (tu *TutorialUpdate) SetNillableDeletedAt(t *time.Time) *TutorialUpdate {
	if t != nil {
		tu.SetDeletedAt(*t)
	}
	return tu
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (tu *TutorialUpdate) ClearDeletedAt() *TutorialUpdate {
	tu.mutation.ClearDeletedAt()
	return tu
}

// SetEmployeeID sets the "employee_id" field.
func (tu *TutorialUpdate) SetEmployeeID(u uint64) *TutorialUpdate {
	tu.mutation.SetEmployeeID(u)
	return tu
}

// SetNillableEmployeeID sets the "employee_id" field if the given value is not nil.
func (tu *TutorialUpdate) SetNillableEmployeeID(u *uint64) *TutorialUpdate {
	if u != nil {
		tu.SetEmployeeID(*u)
	}
	return tu
}

// SetIndex sets the "index" field.
func (tu *TutorialUpdate) SetIndex(i int) *TutorialUpdate {
	tu.mutation.ResetIndex()
	tu.mutation.SetIndex(i)
	return tu
}

// SetNillableIndex sets the "index" field if the given value is not nil.
func (tu *TutorialUpdate) SetNillableIndex(i *int) *TutorialUpdate {
	if i != nil {
		tu.SetIndex(*i)
	}
	return tu
}

// AddIndex adds i to the "index" field.
func (tu *TutorialUpdate) AddIndex(i int) *TutorialUpdate {
	tu.mutation.AddIndex(i)
	return tu
}

// SetTitle sets the "title" field.
func (tu *TutorialUpdate) SetTitle(s string) *TutorialUpdate {
	tu.mutation.SetTitle(s)
	return tu
}

// SetNillableTitle sets the "title" field if the given value is not nil.
func (tu *TutorialUpdate) SetNillableTitle(s *string) *TutorialUpdate {
	if s != nil {
		tu.SetTitle(*s)
	}
	return tu
}

// SetContent sets the "content" field.
func (tu *TutorialUpdate) SetContent(s string) *TutorialUpdate {
	tu.mutation.SetContent(s)
	return tu
}

// SetNillableContent sets the "content" field if the given value is not nil.
func (tu *TutorialUpdate) SetNillableContent(s *string) *TutorialUpdate {
	if s != nil {
		tu.SetContent(*s)
	}
	return tu
}

// SetOrganizationID sets the "organization_id" field.
func (tu *TutorialUpdate) SetOrganizationID(u uint64) *TutorialUpdate {
	tu.mutation.ResetOrganizationID()
	tu.mutation.SetOrganizationID(u)
	return tu
}

// SetNillableOrganizationID sets the "organization_id" field if the given value is not nil.
func (tu *TutorialUpdate) SetNillableOrganizationID(u *uint64) *TutorialUpdate {
	if u != nil {
		tu.SetOrganizationID(*u)
	}
	return tu
}

// AddOrganizationID adds u to the "organization_id" field.
func (tu *TutorialUpdate) AddOrganizationID(u int64) *TutorialUpdate {
	tu.mutation.AddOrganizationID(u)
	return tu
}

// SetEmployee sets the "employee" edge to the Employee entity.
func (tu *TutorialUpdate) SetEmployee(e *Employee) *TutorialUpdate {
	return tu.SetEmployeeID(e.ID)
}

// Mutation returns the TutorialMutation object of the builder.
func (tu *TutorialUpdate) Mutation() *TutorialMutation {
	return tu.mutation
}

// ClearEmployee clears the "employee" edge to the Employee entity.
func (tu *TutorialUpdate) ClearEmployee() *TutorialUpdate {
	tu.mutation.ClearEmployee()
	return tu
}

// Save executes the query and returns the number of nodes affected by the update operation.
func (tu *TutorialUpdate) Save(ctx context.Context) (int, error) {
	if err := tu.defaults(); err != nil {
		return 0, err
	}
	return withHooks(ctx, tu.sqlSave, tu.mutation, tu.hooks)
}

// SaveX is like Save, but panics if an error occurs.
func (tu *TutorialUpdate) SaveX(ctx context.Context) int {
	affected, err := tu.Save(ctx)
	if err != nil {
		panic(err)
	}
	return affected
}

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

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

// defaults sets the default values of the builder before save.
func (tu *TutorialUpdate) defaults() error {
	if _, ok := tu.mutation.UpdatedAt(); !ok {
		if tutorial.UpdateDefaultUpdatedAt == nil {
			return fmt.Errorf("ent: uninitialized tutorial.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
		}
		v := tutorial.UpdateDefaultUpdatedAt()
		tu.mutation.SetUpdatedAt(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (tu *TutorialUpdate) check() error {
	if v, ok := tu.mutation.EmployeeID(); ok {
		if err := tutorial.EmployeeIDValidator(v); err != nil {
			return &ValidationError{Name: "employee_id", err: fmt.Errorf(`ent: validator failed for field "Tutorial.employee_id": %w`, err)}
		}
	}
	if v, ok := tu.mutation.OrganizationID(); ok {
		if err := tutorial.OrganizationIDValidator(v); err != nil {
			return &ValidationError{Name: "organization_id", err: fmt.Errorf(`ent: validator failed for field "Tutorial.organization_id": %w`, err)}
		}
	}
	if _, ok := tu.mutation.EmployeeID(); tu.mutation.EmployeeCleared() && !ok {
		return errors.New(`ent: clearing a required unique edge "Tutorial.employee"`)
	}
	return nil
}

func (tu *TutorialUpdate) sqlSave(ctx context.Context) (n int, err error) {
	if err := tu.check(); err != nil {
		return n, err
	}
	_spec := sqlgraph.NewUpdateSpec(tutorial.Table, tutorial.Columns, sqlgraph.NewFieldSpec(tutorial.FieldID, field.TypeUint64))
	if ps := tu.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := tu.mutation.UpdatedAt(); ok {
		_spec.SetField(tutorial.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := tu.mutation.DeletedAt(); ok {
		_spec.SetField(tutorial.FieldDeletedAt, field.TypeTime, value)
	}
	if tu.mutation.DeletedAtCleared() {
		_spec.ClearField(tutorial.FieldDeletedAt, field.TypeTime)
	}
	if value, ok := tu.mutation.Index(); ok {
		_spec.SetField(tutorial.FieldIndex, field.TypeInt, value)
	}
	if value, ok := tu.mutation.AddedIndex(); ok {
		_spec.AddField(tutorial.FieldIndex, field.TypeInt, value)
	}
	if value, ok := tu.mutation.Title(); ok {
		_spec.SetField(tutorial.FieldTitle, field.TypeString, value)
	}
	if value, ok := tu.mutation.Content(); ok {
		_spec.SetField(tutorial.FieldContent, field.TypeString, value)
	}
	if value, ok := tu.mutation.OrganizationID(); ok {
		_spec.SetField(tutorial.FieldOrganizationID, field.TypeUint64, value)
	}
	if value, ok := tu.mutation.AddedOrganizationID(); ok {
		_spec.AddField(tutorial.FieldOrganizationID, field.TypeUint64, value)
	}
	if tu.mutation.EmployeeCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   tutorial.EmployeeTable,
			Columns: []string{tutorial.EmployeeColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(employee.FieldID, field.TypeUint64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := tu.mutation.EmployeeIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   tutorial.EmployeeTable,
			Columns: []string{tutorial.EmployeeColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(employee.FieldID, field.TypeUint64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{tutorial.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return 0, err
	}
	tu.mutation.done = true
	return n, nil
}

// TutorialUpdateOne is the builder for updating a single Tutorial entity.
type TutorialUpdateOne struct {
	config
	fields   []string
	hooks    []Hook
	mutation *TutorialMutation
}

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

// SetDeletedAt sets the "deleted_at" field.
func (tuo *TutorialUpdateOne) SetDeletedAt(t time.Time) *TutorialUpdateOne {
	tuo.mutation.SetDeletedAt(t)
	return tuo
}

// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (tuo *TutorialUpdateOne) SetNillableDeletedAt(t *time.Time) *TutorialUpdateOne {
	if t != nil {
		tuo.SetDeletedAt(*t)
	}
	return tuo
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (tuo *TutorialUpdateOne) ClearDeletedAt() *TutorialUpdateOne {
	tuo.mutation.ClearDeletedAt()
	return tuo
}

// SetEmployeeID sets the "employee_id" field.
func (tuo *TutorialUpdateOne) SetEmployeeID(u uint64) *TutorialUpdateOne {
	tuo.mutation.SetEmployeeID(u)
	return tuo
}

// SetNillableEmployeeID sets the "employee_id" field if the given value is not nil.
func (tuo *TutorialUpdateOne) SetNillableEmployeeID(u *uint64) *TutorialUpdateOne {
	if u != nil {
		tuo.SetEmployeeID(*u)
	}
	return tuo
}

// SetIndex sets the "index" field.
func (tuo *TutorialUpdateOne) SetIndex(i int) *TutorialUpdateOne {
	tuo.mutation.ResetIndex()
	tuo.mutation.SetIndex(i)
	return tuo
}

// SetNillableIndex sets the "index" field if the given value is not nil.
func (tuo *TutorialUpdateOne) SetNillableIndex(i *int) *TutorialUpdateOne {
	if i != nil {
		tuo.SetIndex(*i)
	}
	return tuo
}

// AddIndex adds i to the "index" field.
func (tuo *TutorialUpdateOne) AddIndex(i int) *TutorialUpdateOne {
	tuo.mutation.AddIndex(i)
	return tuo
}

// SetTitle sets the "title" field.
func (tuo *TutorialUpdateOne) SetTitle(s string) *TutorialUpdateOne {
	tuo.mutation.SetTitle(s)
	return tuo
}

// SetNillableTitle sets the "title" field if the given value is not nil.
func (tuo *TutorialUpdateOne) SetNillableTitle(s *string) *TutorialUpdateOne {
	if s != nil {
		tuo.SetTitle(*s)
	}
	return tuo
}

// SetContent sets the "content" field.
func (tuo *TutorialUpdateOne) SetContent(s string) *TutorialUpdateOne {
	tuo.mutation.SetContent(s)
	return tuo
}

// SetNillableContent sets the "content" field if the given value is not nil.
func (tuo *TutorialUpdateOne) SetNillableContent(s *string) *TutorialUpdateOne {
	if s != nil {
		tuo.SetContent(*s)
	}
	return tuo
}

// SetOrganizationID sets the "organization_id" field.
func (tuo *TutorialUpdateOne) SetOrganizationID(u uint64) *TutorialUpdateOne {
	tuo.mutation.ResetOrganizationID()
	tuo.mutation.SetOrganizationID(u)
	return tuo
}

// SetNillableOrganizationID sets the "organization_id" field if the given value is not nil.
func (tuo *TutorialUpdateOne) SetNillableOrganizationID(u *uint64) *TutorialUpdateOne {
	if u != nil {
		tuo.SetOrganizationID(*u)
	}
	return tuo
}

// AddOrganizationID adds u to the "organization_id" field.
func (tuo *TutorialUpdateOne) AddOrganizationID(u int64) *TutorialUpdateOne {
	tuo.mutation.AddOrganizationID(u)
	return tuo
}

// SetEmployee sets the "employee" edge to the Employee entity.
func (tuo *TutorialUpdateOne) SetEmployee(e *Employee) *TutorialUpdateOne {
	return tuo.SetEmployeeID(e.ID)
}

// Mutation returns the TutorialMutation object of the builder.
func (tuo *TutorialUpdateOne) Mutation() *TutorialMutation {
	return tuo.mutation
}

// ClearEmployee clears the "employee" edge to the Employee entity.
func (tuo *TutorialUpdateOne) ClearEmployee() *TutorialUpdateOne {
	tuo.mutation.ClearEmployee()
	return tuo
}

// Where appends a list predicates to the TutorialUpdate builder.
func (tuo *TutorialUpdateOne) Where(ps ...predicate.Tutorial) *TutorialUpdateOne {
	tuo.mutation.Where(ps...)
	return tuo
}

// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (tuo *TutorialUpdateOne) Select(field string, fields ...string) *TutorialUpdateOne {
	tuo.fields = append([]string{field}, fields...)
	return tuo
}

// Save executes the query and returns the updated Tutorial entity.
func (tuo *TutorialUpdateOne) Save(ctx context.Context) (*Tutorial, error) {
	if err := tuo.defaults(); err != nil {
		return nil, err
	}
	return withHooks(ctx, tuo.sqlSave, tuo.mutation, tuo.hooks)
}

// SaveX is like Save, but panics if an error occurs.
func (tuo *TutorialUpdateOne) SaveX(ctx context.Context) *Tutorial {
	node, err := tuo.Save(ctx)
	if err != nil {
		panic(err)
	}
	return node
}

// Exec executes the query on the entity.
func (tuo *TutorialUpdateOne) Exec(ctx context.Context) error {
	_, err := tuo.Save(ctx)
	return err
}

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

// defaults sets the default values of the builder before save.
func (tuo *TutorialUpdateOne) defaults() error {
	if _, ok := tuo.mutation.UpdatedAt(); !ok {
		if tutorial.UpdateDefaultUpdatedAt == nil {
			return fmt.Errorf("ent: uninitialized tutorial.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
		}
		v := tutorial.UpdateDefaultUpdatedAt()
		tuo.mutation.SetUpdatedAt(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (tuo *TutorialUpdateOne) check() error {
	if v, ok := tuo.mutation.EmployeeID(); ok {
		if err := tutorial.EmployeeIDValidator(v); err != nil {
			return &ValidationError{Name: "employee_id", err: fmt.Errorf(`ent: validator failed for field "Tutorial.employee_id": %w`, err)}
		}
	}
	if v, ok := tuo.mutation.OrganizationID(); ok {
		if err := tutorial.OrganizationIDValidator(v); err != nil {
			return &ValidationError{Name: "organization_id", err: fmt.Errorf(`ent: validator failed for field "Tutorial.organization_id": %w`, err)}
		}
	}
	if _, ok := tuo.mutation.EmployeeID(); tuo.mutation.EmployeeCleared() && !ok {
		return errors.New(`ent: clearing a required unique edge "Tutorial.employee"`)
	}
	return nil
}

func (tuo *TutorialUpdateOne) sqlSave(ctx context.Context) (_node *Tutorial, err error) {
	if err := tuo.check(); err != nil {
		return _node, err
	}
	_spec := sqlgraph.NewUpdateSpec(tutorial.Table, tutorial.Columns, sqlgraph.NewFieldSpec(tutorial.FieldID, field.TypeUint64))
	id, ok := tuo.mutation.ID()
	if !ok {
		return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Tutorial.id" for update`)}
	}
	_spec.Node.ID.Value = id
	if fields := tuo.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, tutorial.FieldID)
		for _, f := range fields {
			if !tutorial.ValidColumn(f) {
				return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
			}
			if f != tutorial.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, f)
			}
		}
	}
	if ps := tuo.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := tuo.mutation.UpdatedAt(); ok {
		_spec.SetField(tutorial.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := tuo.mutation.DeletedAt(); ok {
		_spec.SetField(tutorial.FieldDeletedAt, field.TypeTime, value)
	}
	if tuo.mutation.DeletedAtCleared() {
		_spec.ClearField(tutorial.FieldDeletedAt, field.TypeTime)
	}
	if value, ok := tuo.mutation.Index(); ok {
		_spec.SetField(tutorial.FieldIndex, field.TypeInt, value)
	}
	if value, ok := tuo.mutation.AddedIndex(); ok {
		_spec.AddField(tutorial.FieldIndex, field.TypeInt, value)
	}
	if value, ok := tuo.mutation.Title(); ok {
		_spec.SetField(tutorial.FieldTitle, field.TypeString, value)
	}
	if value, ok := tuo.mutation.Content(); ok {
		_spec.SetField(tutorial.FieldContent, field.TypeString, value)
	}
	if value, ok := tuo.mutation.OrganizationID(); ok {
		_spec.SetField(tutorial.FieldOrganizationID, field.TypeUint64, value)
	}
	if value, ok := tuo.mutation.AddedOrganizationID(); ok {
		_spec.AddField(tutorial.FieldOrganizationID, field.TypeUint64, value)
	}
	if tuo.mutation.EmployeeCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   tutorial.EmployeeTable,
			Columns: []string{tutorial.EmployeeColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(employee.FieldID, field.TypeUint64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := tuo.mutation.EmployeeIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   tutorial.EmployeeTable,
			Columns: []string{tutorial.EmployeeColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(employee.FieldID, field.TypeUint64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_node = &Tutorial{config: tuo.config}
	_spec.Assign = _node.assignValues
	_spec.ScanValues = _node.scanValues
	if err = sqlgraph.UpdateNode(ctx, tuo.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{tutorial.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	tuo.mutation.done = true
	return _node, nil
}
