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

package implments

import (
	"LAPP_ACURA_MOM_BACKEND/grmi"
	meta "LAPP_ACURA_MOM_BACKEND/meta/me"
	model "LAPP_ACURA_MOM_BACKEND/models/me"
	"fmt"
	"github.com/go-xorm/xorm"
	"xorm.io/core"
)

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

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/me/ProductFamilyDAO.InsertOne
 *
 ******************************************************************************/
func (impl *ProductFamilyDAOImplement) InsertOne(entity *model.ProductFamily) 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_ACURA_MOM_BACKEND/dao/me/ProductFamilyDAO.DeleteOne
 *
 ******************************************************************************/
func (impl *ProductFamilyDAOImplement) DeleteOne(productFamilyId string) error {
	_, err := impl.session.Table(impl.meta.TableName).ID(core.PK{impl.plantNr, productFamilyId}).Delete(impl.meta.Indicator)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}

	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/me/ProductFamilyDAO.SelectOne
 *
 ******************************************************************************/
func (impl *ProductFamilyDAOImplement) SelectOne(productFamilyId string) (*model.ProductFamily, error) {
	var data model.ProductFamily
	ok, err := impl.session.Table(impl.meta.TableName).ID(core.PK{impl.plantNr, productFamilyId}).Get(&data)
	if err != nil {
		return nil, grmi.NewDataBaseError(err)
	}
	if !ok {
		return nil, nil
	}
	//先查询配置
	//var relate []model.ProductFamilyRelate
	//err = impl.session.Table(meta.ProductFamilyRelate.TableName).Where("ProductFamilyId = ? and ProjectId=?", data.ProductFamilyId, data.ProjectId).Find(&relate)
	//var productId []string
	//productCount := make(map[string]int)
	//for _, v := range relate {
	//	productId = append(productId, v.ProductId)
	//	productCount[v.ProductId] = v.Count
	//}
	////查询车型配置零件
	//var product []model.Product
	//err = impl.session.Table(meta.Product.TableName).In("ProductId", productId).Find(&product)
	condition := fmt.Sprintf("%s = %s and %s = %s",
		meta.ProductFamilyRelate_PlantNr.ColumnName,
		meta.Product_PlantNr.ColumnName,
		meta.ProductFamilyRelate_ProductId.ColumnName,
		meta.Product_ProductId.ColumnName)
	li := make([]model.ProductFamilyRelateAndProduct, 0, 4)
	session := impl.session.Table(meta.ProductFamilyRelate.TableName).Join("LEFT", meta.Product.TableName, condition)
	err = session.Where(fmt.Sprintf("%s = ?", meta.ProductFamilyRelate_ProductFamilyId.ColumnName), productFamilyId).OrderBy(meta.ProductFamilyRelate_Pos.ColumnName).Find(&li)
	if err != nil {
		return nil, err
	}
	productLi := make([]model.Product, 0, len(li))
	for _, item := range li {
		var product model.Product
		product = item.Product
		product.ProductFamilyId = item.ProductFamilyRelate.ProductFamilyId
		product.ProjectId = item.ProductFamilyRelate.ProjectId
		product.Count = item.ProductFamilyRelate.Count
		productLi = append(productLi, product)
	}
	data.Product = productLi
	return &data, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/me/ProductFamilyDAO.UpdateOne
 *
 ******************************************************************************/
func (impl *ProductFamilyDAOImplement) UpdateOne(entity *model.ProductFamily) 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_ACURA_MOM_BACKEND/dao/me/ProductFamilyDAO.Insert
 *
 ******************************************************************************/
func (impl *ProductFamilyDAOImplement) Insert(entities *[]model.ProductFamily) 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_ACURA_MOM_BACKEND/dao/me/ProductFamilyDAO.Delete
 *
 ******************************************************************************/
func (impl *ProductFamilyDAOImplement) Delete(entities *[]model.ProductFamily) 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_ACURA_MOM_BACKEND/dao/me/ProductFamilyDAO.DeleteWhere
 *
 ******************************************************************************/
func (impl *ProductFamilyDAOImplement) DeleteWhere(predicates []grmi.Predicate) error {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.ProductFamily_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_ACURA_MOM_BACKEND/dao/me/ProductFamilyDAO.SelectAndRelate
 *
 ******************************************************************************/
func (impl *ProductFamilyDAOImplement) SelectAndRelate(predicates []string) ([]model.ProductFamily, error) {

	var data []model.ProductFamily
	err := impl.session.Table(impl.meta.TableName).In(meta.ProductFamily_ProductFamilyId.Name, predicates).Find(&data)
	if err != nil {
		return nil, grmi.NewDataBaseError(err)
	}
	//查询配置
	var relateList []model.ProductFamilyRelate
	err = impl.session.Table(meta.ProductFamilyRelate.TableName).In(meta.ProductFamilyRelate_ProductFamilyId.Name, predicates).Find(&relateList)
	if err != nil {
		return nil, err
	}
	relateMap := make(map[string][]model.ProductFamilyRelate)
	for _, v := range relateList {
		relateMap[v.ProjectId+"[|]"+v.ProductFamilyId] = append(relateMap[v.ProjectId+"[|]"+v.ProductFamilyId], v)
	}
	var projectId []string
	for k, v := range data {
		info, ok := relateMap[v.ProjectId+"[|]"+v.ProductFamilyId]
		if ok {
			data[k].Relate = info
		}
		projectId = append(projectId, v.ProjectId)
	}

	//查询车型
	var project []model.Project
	err = impl.session.Table(meta.Project.TableName).In(meta.Project_ProjectId.Name, projectId).Find(&project)
	projectMap := make(map[string]model.Project)
	for _, v := range project {
		projectMap[v.ProjectId] = v
	}
	for k, v := range data {
		info, ok := projectMap[v.ProjectId]
		if ok {
			data[k].Project = info
		}
	}
	return data, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/me/ProductFamilyDAO.Select
 *
 ******************************************************************************/
func (impl *ProductFamilyDAOImplement) Select(predicates []grmi.Predicate, orderByFields []grmi.Field) ([]model.ProductFamily, error) {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.ProductFamily_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.ProductFamily_PlantNr.ColumnName)
	if orderByFields != nil {
		for _, field := range orderByFields {
			session = session.OrderBy(field.ColumnName)
		}
	}

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/me/ProductFamilyDAO.SelectAndPaging
 *
 ******************************************************************************/
func (impl *ProductFamilyDAOImplement) SelectAndPaging(paging *grmi.Paging, predicates []grmi.Predicate, orderByFields []grmi.Field) (grmi.PagingResult, error) {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.ProductFamily_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.ProductFamily_PlantNr.ColumnName
	if orderByFields != nil {
		for _, field := range orderByFields {
			if orderBy == " order by " {
				orderBy += field.ColumnName
			} else {
				orderBy += ", " + field.ColumnName
			}
		}
	}
	parameters = append(parameters, paging.Offset(), paging.Size)
	data := make([]model.ProductFamily, 0, 10)
	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_ACURA_MOM_BACKEND/dao/me/ProductFamilyDAO.Update
 *
 ******************************************************************************/
func (impl *ProductFamilyDAOImplement) Update(entities *[]model.ProductFamily) 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_ACURA_MOM_BACKEND/dao/me/ProductFamilyDAO.UpdateWhere
 *
 ******************************************************************************/
func (impl *ProductFamilyDAOImplement) UpdateWhere(predicates []grmi.Predicate, entity *model.ProductFamily, columns ...string) error {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.ProductFamily_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.ProductFamily_LastUser.Name)
	entity.LastUser = impl.userid
	_, err := session.Cols(columns...).Update(entity)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}
