package eta_business

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"strings"
	"time"
)

// EtaBusinessContract ETA商家合同表
type EtaBusinessContract struct {
	EtaBusinessContractId int       `orm:"column(eta_business_contract_id);pk"`
	EtaBusinessId         int       `description:"ETA商家ID"`
	SigningTime           time.Time `description:"签约时间"`
	ExpiredTime           time.Time `description:"到期时间"`
	IsFirst               int       `description:"是否为首份签约"`
	CreateTime            time.Time `description:"创建时间"`
	ModifyTime            time.Time `description:"更新时间"`
}

func (m *EtaBusinessContract) TableName() string {
	return "eta_business_contract"
}

func (m *EtaBusinessContract) PrimaryId() string {
	return EtaBusinessContractColumns.EtaBusinessContractId
}

var EtaBusinessContractColumns = struct {
	EtaBusinessContractId string
	EtaBusinessId         string
	SigningTime           string
	ExpiredTime           string
	IsFirst               string
	CreateTime            string
	ModifyTime            string
}{
	EtaBusinessContractId: "eta_business_contract_id",
	EtaBusinessId:         "eta_business_id",
	SigningTime:           "signing_time",
	ExpiredTime:           "expired_time",
	IsFirst:               "is_first",
	CreateTime:            "create_time",
	ModifyTime:            "modify_time",
}

func (m *EtaBusinessContract) Create() (err error) {
	o := orm.NewOrm()
	id, err := o.Insert(m)
	if err != nil {
		return
	}
	m.EtaBusinessContractId = int(id)
	return
}

func (m *EtaBusinessContract) CreateMulti(items []*EtaBusinessContract) (err error) {
	if len(items) == 0 {
		return
	}
	o := orm.NewOrm()
	_, err = o.InsertMulti(len(items), items)
	return
}

func (m *EtaBusinessContract) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(m, cols...)
	return
}

func (m *EtaBusinessContract) Del() (err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	_, err = o.Raw(sql, m.EtaBusinessContractId).Exec()
	return
}

func (m *EtaBusinessContract) GetItemById(id int) (item *EtaBusinessContract, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

func (m *EtaBusinessContract) GetItemByCondition(condition string, pars []interface{}) (err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 %s LIMIT 1`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&m)
	return
}

func (m *EtaBusinessContract) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func (m *EtaBusinessContract) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*EtaBusinessContract, err error) {
	o := orm.NewOrm()
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// CreateMaybeUpdateFirst 新增签约合同, 或同时更新首次签约合同
func (m *EtaBusinessContract) CreateMaybeUpdateFirst(item *EtaBusinessContract, changeFirst bool) (err error) {
	// 直接新增
	o := orm.NewOrm()
	if !changeFirst {
		id, e := o.Insert(item)
		if e != nil {
			return e
		}
		item.EtaBusinessContractId = int(id)
		return
	}

	// 更新签约合同
	tx, e := o.Begin()
	if e != nil {
		return e
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
			return
		}
		_ = tx.Commit()
	}()

	id, e := tx.Insert(item)
	if e != nil {
		err = fmt.Errorf("contract insert err: %s", e.Error())
		return
	}
	item.EtaBusinessContractId = int(id)

	sql := fmt.Sprintf(`UPDATE %s SET %s = 0 WHERE %s = ? AND %s <> ?`, m.TableName(), EtaBusinessContractColumns.IsFirst, EtaBusinessContractColumns.EtaBusinessId, EtaBusinessContractColumns.EtaBusinessContractId)
	_, e = tx.Raw(sql, item.EtaBusinessId, item.EtaBusinessContractId).Exec()
	if e != nil {
		err = fmt.Errorf("update first contract err: %s", e.Error())
		return
	}
	return
}

// UpdateMaybeUpdateFirst 编辑签约合同, 或同时更新首次签约合同
func (m *EtaBusinessContract) UpdateMaybeUpdateFirst(item *EtaBusinessContract, changeFirst bool, updateCols []string) (err error) {
	// 无需修改首次签约则直接更新
	o := orm.NewOrm()
	if !changeFirst {
		e := item.Update(updateCols)
		if e != nil {
			return e
		}
		return
	}

	// 更新首次签约合同
	tx, e := o.Begin()
	if e != nil {
		return e
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
			return
		}
		_ = tx.Commit()
	}()

	_, e = tx.Update(item, updateCols...)
	if e != nil {
		err = fmt.Errorf("contract update err: %s", e.Error())
		return
	}

	sql := fmt.Sprintf(`UPDATE %s SET %s = 0 WHERE %s = ? AND %s <> ?`, m.TableName(), EtaBusinessContractColumns.IsFirst, EtaBusinessContractColumns.EtaBusinessId, EtaBusinessContractColumns.EtaBusinessContractId)
	_, e = tx.Raw(sql, item.EtaBusinessId, item.EtaBusinessContractId).Exec()
	if e != nil {
		err = fmt.Errorf("update first contract err: %s", e.Error())
		return
	}
	return
}

// EtaBusinessContractItem 商家签约信息
type EtaBusinessContractItem struct {
	EtaBusinessContractId int
	EtaBusinessId         int    `description:"ETA商家ID"`
	SigningTime           string `description:"签约时间"`
	ExpiredTime           string `description:"到期时间"`
	ExpireDay             string `description:"到期天数"`
	Using                 bool   `description:"是否当前合约"`
}
