// Copyright (c) Shenyang Leading Edge Intelligent Technology Co., Ltd. All rights reserved.

package implments

import (
	"LAPP_LF_MOM_BACKEND/grmi"
	meta "LAPP_LF_MOM_BACKEND/meta/base"
	model "LAPP_LF_MOM_BACKEND/models/base"
	"LAPP_LF_MOM_BACKEND/utils"
	"fmt"
	"github.com/go-xorm/xorm"
	"strconv"
	"strings"
	"time"
	"xorm.io/core"
)

/******************************************************************************
 *
 * @Struct Name              : SnrDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : Snr的数据访问对象实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-19 12:11:47
 *
 ******************************************************************************/
type SnrDAOImplement struct {
	session *xorm.Session
	meta    *grmi.Entity
	plantNr int
	userid  string
}

/******************************************************************************
 *
 * @Function Name            : NewSnrDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个SnrDAOImplement实例
 *
 * @Function Parameters      : xorm会话
 *
 * @Function Parameters      : 基本主键
 *
 * @Return Value             : SnrDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-19 12:11:47
 *
 ******************************************************************************/
func NewSnrDAOImplement(session *xorm.Session, plantNr int, userid string) *SnrDAOImplement {
	return &SnrDAOImplement{session, &meta.Snr, plantNr, userid}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/base/SnrDAO.InsertOne
 *
 ******************************************************************************/
func (impl *SnrDAOImplement) InsertOne(entity *model.Snr) error {
	entity.PlantNr = impl.plantNr
	entity.LastUser = impl.userid
	_, err := impl.session.Table(impl.meta.TableName).Insert(entity)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/base/SnrDAO.DeleteOne
 *
 ******************************************************************************/
func (impl *SnrDAOImplement) DeleteOne(snrId string) error {
	_, err := impl.session.Table(impl.meta.TableName).ID(core.PK{impl.plantNr, snrId}).Delete(impl.meta.Indicator)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}

	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/base/SnrDAO.SelectOne
 *
 ******************************************************************************/
func (impl *SnrDAOImplement) SelectOne(snrId string) (*model.Snr, error) {
	var data model.Snr
	ok, err := impl.session.Table(impl.meta.TableName).ID(core.PK{impl.plantNr, snrId}).Get(&data)
	if err != nil {
		return nil, grmi.NewDataBaseError(err)
	}
	if !ok {
		return nil, nil
	}
	return &data, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/base/SnrDAO.UpdateOne
 *
 ******************************************************************************/
func (impl *SnrDAOImplement) UpdateOne(entity *model.Snr) error {
	entity.PlantNr = impl.plantNr
	entity.LastUser = impl.userid
	_, err := impl.session.Table(impl.meta.TableName).Cols(impl.meta.UpdatingMembers...).ID(entity.GetKey()).Update(entity)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/base/SnrDAO.Insert
 *
 ******************************************************************************/
func (impl *SnrDAOImplement) Insert(entities *[]model.Snr) error {
	for i := 0; i < len(*entities); i++ {
		entity := &(*entities)[i]
		entity.PlantNr = impl.plantNr
		entity.LastUser = impl.userid
	}
	_, err := impl.session.Table(impl.meta.TableName).Insert(entities)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/base/SnrDAO.Delete
 *
 ******************************************************************************/
func (impl *SnrDAOImplement) Delete(entities *[]model.Snr) error {
	for _, entity := range *entities {
		entity.PlantNr = impl.plantNr
		_, err := impl.session.Table(impl.meta.TableName).ID(entity.GetKey()).Delete(impl.meta.Indicator)
		if err != nil {
			return grmi.NewDataBaseError(err)
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/base/SnrDAO.DeleteWhere
 *
 ******************************************************************************/
func (impl *SnrDAOImplement) DeleteWhere(predicates []grmi.Predicate) error {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.Snr_PlantNr.ColumnName)

	session := impl.session.Table(impl.meta.TableName)
	if predicates != nil {
		for _, predicate := range predicates {
			where += predicate.Build()
			parameters = append(parameters, predicate.Values...)
		}
		session = session.Where(where, parameters...)
	} else {
		session = session.Where(where, parameters...)
	}

	_, err := session.Delete(impl.meta.Indicator)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/base/SnrDAO.Select
 *
 ******************************************************************************/
func (impl *SnrDAOImplement) Select(predicates []grmi.Predicate, orderByFields []grmi.Field) ([]model.Snr, error) {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.Snr_PlantNr.ColumnName)

	session := impl.session.Table(impl.meta.TableName)
	if predicates != nil {
		for _, predicate := range predicates {
			where += predicate.Build()
			parameters = append(parameters, predicate.Values...)
		}
		session = session.Where(where, parameters...)
	} else {
		session = session.Where(where, parameters...)
	}

	session = session.OrderBy(meta.Snr_PlantNr.ColumnName)
	if orderByFields != nil {
		for _, field := range orderByFields {
			session = session.OrderBy(field.ColumnName)
		}
	}

	data := make([]model.Snr, 0, 10)
	err := session.Find(&data)
	if err != nil {
		return nil, grmi.NewDataBaseError(err)
	}
	return data, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/base/SnrDAO.SelectAndPaging
 *
 ******************************************************************************/
func (impl *SnrDAOImplement) SelectAndPaging(paging *grmi.Paging, predicates []grmi.Predicate, orderByFields []grmi.Field) (grmi.PagingResult, error) {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.Snr_PlantNr.ColumnName)

	session := impl.session.Table(impl.meta.TableName)
	if predicates != nil {
		for _, predicate := range predicates {
			where += predicate.Build()
			parameters = append(parameters, predicate.Values...)
		}
		session = session.Where(where, parameters...)
	} else {
		session = session.Where(where, parameters...)
	}

	count, err := session.Count(impl.meta.Indicator)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}

	orderBy := " order by " + meta.Snr_PlantNr.ColumnName
	if orderByFields != nil {
		for _, field := range orderByFields {
			orderBy += ", " + field.ColumnName
		}
	}
	parameters = append(parameters, paging.Offset(), paging.Size)
	data := make([]model.Snr, 0, 10)
	if where != "" {
		where = " where " + where
	}
	err = impl.session.Table(impl.meta.TableName).SQL("select * from "+impl.meta.TableName+where+orderBy+" offset ? row fetch next ? row only", parameters...).Find(&data)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	return grmi.PagingResult{Records: data, Count: count, PageNumber: paging.Number, PageSize: paging.Size}, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/base/SnrDAO.Update
 *
 ******************************************************************************/
func (impl *SnrDAOImplement) Update(entities *[]model.Snr) error {
	for i := 0; i < len(*entities); i++ {
		entity := &(*entities)[i]
		entity.PlantNr = impl.plantNr
		entity.LastUser = impl.userid
		_, err := impl.session.Table(impl.meta.TableName).Cols(impl.meta.UpdatingMembers...).ID(entity.GetKey()).Update(entity)
		if err != nil {
			return grmi.NewDataBaseError(err)
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/base/SnrDAO.UpdateWhere
 *
 ******************************************************************************/
func (impl *SnrDAOImplement) UpdateWhere(predicates []grmi.Predicate, entity *model.Snr, columns ...string) error {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.Snr_PlantNr.ColumnName)

	session := impl.session.Table(impl.meta.TableName)
	if predicates != nil {
		for _, predicate := range predicates {
			where += predicate.Build()
			parameters = append(parameters, predicate.Values...)
		}
		session = session.Where(where, parameters...)
	} else {
		session = session.Where(where, parameters...)
	}

	columns = append(columns, meta.Snr_LastUser.ColumnName)
	entity.LastUser = impl.userid
	_, err := impl.session.Table(impl.meta.TableName).Cols(columns...).Update(entity)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}
/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/base/SnrDAO.GetNextSnr
 *
 ******************************************************************************/
func (impl *SnrDAOImplement)GetNextSnr(snr string) (retsnr string, err error) {
	var (
		snrtab                   model.Snr
		lastupdtime              time.Time
		y, l_y, d, l_d, wk, l_wk int
		m, l_m                   time.Month
		layout                   []byte
		i, nextsnr               int
		sql                      string
	)

	snrtab = model.Snr{}
	session := impl.session.Table(impl.meta.TableName)
	if _, err = session.ID(core.PK{impl.plantNr, snr}).Get(&snrtab); err != nil {
		return
	}

	if snrtab.LastNrCreate  == "" {
		nextsnr = snrtab.NextNr
	} else {
		if lastupdtime, err = utils.DateParse(snrtab.LastNrCreate, "YmdHis"); err != nil {
			return
		}
		// 获取下一序列值
		y = time.Now().Year()
		m = time.Now().Month()
		d = time.Now().Day()
		_, wk = time.Now().ISOWeek()
		l_y = lastupdtime.Year()
		l_m = lastupdtime.Month()
		l_d = lastupdtime.Day()
		_, l_wk = lastupdtime.ISOWeek()
		switch strings.ToUpper(snrtab.ResetNrRule) {
		case "DAILY":
			if y == l_y && m == l_m && wk == l_wk && d == l_d {
				nextsnr = snrtab.NextNr
			} else {
				nextsnr = snrtab.StartNr
			}
		case "WEEKLY":
			if y == l_y && m == l_m && wk == l_wk {
				nextsnr = snrtab.NextNr
			} else {
				nextsnr = snrtab.StartNr
			}
		case "MONTHLY":
			if y == l_y && m == l_m {
				nextsnr = snrtab.NextNr
			} else {
				nextsnr = snrtab.StartNr
			}
		case "YEARLY":
			if y == l_y {
				nextsnr = snrtab.NextNr
			} else {
				nextsnr = snrtab.StartNr
			}
		case "NEVER":
			nextsnr = snrtab.NextNr
		default:
			nextsnr = snrtab.NextNr
		}
	}

	// 组合返回值
	layout = []byte(snrtab.Identifierlayout)
	for i = 0; i < len(layout); i++ {
		switch string(layout[i]) {
		case "1": //前缀
			retsnr = retsnr + snrtab.Prefix
		case "2": //日期变量
			retsnr = retsnr + utils.Date(time.Now().Unix(), snrtab.DateFormat)
		case "3": //中缀
			retsnr = retsnr + snrtab.Infix
		case "4": //流水号
			if snrtab.IdentifierFormat == "CHAR" {
				retsnr = retsnr + utils.ConvInt2FormatString(nextsnr, snrtab.Length)
			} else {
				retsnr = retsnr + strconv.Itoa(nextsnr)
			}
		case "5": //后缀
			retsnr = retsnr + snrtab.Postfix
		}
	}
	//更新下一序列值
	// 处理数值超限
	snrtab.NextNr = nextsnr + snrtab.Step
	snrtab.LastNrCreate = utils.Date(time.Now().Unix(), "YYYYMMDDHHmmss")
	snrtab.LastModify = grmi.DateTime(time.Now())
	if snrtab.NextNr > snrtab.EndNr {
		switch strings.ToUpper(snrtab.OverflowHandling) {
		case "NO":
		case "RESET":
			snrtab.NextNr = snrtab.StartNr
		}
	}

	sql = "update `Snr` set NextNr = ?, LastNrCreate = ?, LastModify = ? where PlantNr = ? AND SnrId = ?"
	if _, err = session.Exec(sql, snrtab.NextNr, snrtab.LastNrCreate, snrtab.LastModify, impl.plantNr, snrtab.SnrId); err != nil {
		return
	}

	return
}