// 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/om"
	common "LAPP_LF_MOM_BACKEND/models/base"
	model "LAPP_LF_MOM_BACKEND/models/om"
	"LAPP_LF_MOM_BACKEND/utils"
	"fmt"
	"github.com/go-xorm/xorm"
	"time"
	"xorm.io/core"
)

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

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/om/WorkOrderDAO.InsertOne
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) InsertOne(entity *model.WorkOrder) 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/om/WorkOrderDAO.DeleteOne
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) DeleteOne(workOrderId string) error {
	_, err := impl.session.Table(impl.meta.TableName).ID(core.PK{impl.plantNr, workOrderId}).Delete(impl.meta.Indicator)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}

	return nil
}

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/om/WorkOrderDAO.SelectOne
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) SelectInfo(workOrderId string) (data model.WorkOrder, err error) {
	ok, err := impl.session.Table(impl.meta.TableName).ID(core.PK{impl.plantNr, workOrderId}).Get(&data)
	if err != nil {
		return data, grmi.NewDataBaseError(err)
	}
	if !ok {
		return data, nil
	}
	return data, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/om/WorkOrderDAO.UpdateOne
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) UpdateOne(entity *model.WorkOrder) error {
	entity.PlantNr = impl.plantNr
	entity.LastUser = impl.userid
	col, err := impl.session.Table(impl.meta.TableName).Cols(impl.meta.UpdatingMembers...).ID(entity.GetKey()).Update(entity)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	if col <= 0 {
		return grmi.NewBusinessError("未更新成功")
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/om/WorkOrderDAO.UpdateOrderOne
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) UpdateOrderOne(entity *model.WorkOrder) error {
	entity.PlantNr = impl.plantNr
	entity.LastUser = impl.userid
	_, err := impl.session.Table(impl.meta.TableName).ID(entity.GetKey()).Update(entity)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/om/WorkOrderDAO.Insert
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) Insert(entities *[]model.WorkOrder) 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/om/WorkOrderDAO.Delete
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) Delete(entities *[]model.WorkOrder) 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/om/WorkOrderDAO.DeleteWhere
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) DeleteWhere(predicates []grmi.Predicate) error {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.WorkOrder_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/om/WorkOrderDAO.Select
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) Select(predicates []grmi.Predicate, orderByFields []grmi.Field) ([]model.WorkOrder, error) {

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

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

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

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.WorkOrder_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.WorkOrder_PlantNr.ColumnName
	if orderByFields != nil {
		for _, field := range orderByFields {
			orderBy += ", " + field.ColumnName
		}
	}
	parameters = append(parameters, paging.Offset(), paging.Size)
	data := make([]model.WorkOrder, 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/om/WorkOrderDAO.Update
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) Update(entities *[]model.WorkOrder) 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/om/WorkOrderDAO.UpdateWhere
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) UpdateWhere(predicates []grmi.Predicate, entity *model.WorkOrder, columns ...string) error {

	parameters := []interface{}{impl.plantNr}
	where := fmt.Sprintf("%s = ?", meta.WorkOrder_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.WorkOrder_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/om/WorkOrderDAO.SelectStartedTasks
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) SelectStartedTasks(startTime time.Time, endTime time.Time, workLineid string) (datalst []model.WorkOrder, err error) {
	var (
		i        int
		wotab    model.WorkOrder
		vdatalst []model.VOmWorkorder
	)
	startData := utils.TimeFormat(startTime, "yyyy-MM-dd HH:mm:ss")
	endData := utils.TimeFormat(endTime, "yyyy-MM-dd HH:mm:ss")
	session := impl.session.Table(impl.meta.TableName)
	if err = session.Join("INNER", "OM_WorkOrderStatus",
		"OM_WorkOrderStatus.PlantNr = OM_WorkOrder.PlantNr and OM_WorkOrderStatus.WorkOrderId = OM_WorkOrder.WorkOrderId").Join("INNER", "OM_WorkOrderQty",
		"OM_WorkOrderQty.PlantNr = OM_WorkOrder.PlantNr and OM_WorkOrderQty.WorkOrderId = OM_WorkOrder.WorkOrderId").Where("OM_WorkOrder.PlantNr = ? and OM_WorkOrder.ProjectId = ? and OM_WorkOrderStatus.Status >= ? and OM_WorkOrder.PlanResourceId = ? and ((OM_WorkOrder.PlanStartTime >= ? and OM_WorkOrder.PlanStartTime < ?) or (OM_WorkOrder.PlanEndTime >= ? and OM_WorkOrder.PlanEndTime < ?))", impl.plantNr, common.ProjectId, common.WO_STATUS_LOCKED, workLineid, startData, endData, startData, endData).Asc("OM_WorkOrder.PlanStartDate").Find(&vdatalst); err != nil {
		return
	}
	datalst = make([]model.WorkOrder, 0)
	for i = 0; i < len(vdatalst); i++ {
		wotab = model.WorkOrder{}
		wotab = vdatalst[i].WorkOrder
		wotab.WorkOrderStatus = vdatalst[i].WorkOrderStatus
		wotab.WorkOrderQty = vdatalst[i].WorkOrderQty
		datalst = append(datalst, wotab)
	}

	return
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/om/WorkOrderDAO.SelectLockedTasks
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) SelectLockedTasks(startTime time.Time, endTime time.Time, workLineid string) (datalst []model.WorkOrder, err error) {
	var (
		i        int
		wotab    model.WorkOrder
		vdatalst []model.VOmWorkorder
	)
	startData := utils.TimeFormat(startTime, "yyyy-MM-dd HH:mm:ss")
	endData := utils.TimeFormat(endTime, "yyyy-MM-dd HH:mm:ss")
	session := impl.session.Table(impl.meta.TableName)
	if err = session.Join("INNER", "OM_WorkOrderStatus",
		"OM_WorkOrderStatus.PlantNr = OM_WorkOrder.PlantNr and OM_WorkOrderStatus.WorkOrderId = OM_WorkOrder.WorkOrderId").Join("INNER", "OM_WorkOrderQty",
		"OM_WorkOrderQty.PlantNr = OM_WorkOrder.PlantNr and OM_WorkOrderQty.WorkOrderId = OM_WorkOrder.WorkOrderId").Where("OM_WorkOrder.PlantNr = ? and OM_WorkOrder.ProjectId = ? and OM_WorkOrderStatus.Status >= ? and OM_WorkOrder.PlanResourceId = ? and ((OM_WorkOrder.PlanStartTime >= ? and OM_WorkOrder.PlanStartTime < ?) or (OM_WorkOrder.PlanEndTime >= ? and OM_WorkOrder.PlanEndTime < ?))", impl.plantNr, common.ProjectId, common.WO_STATUS_PLANNED, workLineid, startData, endData, startData, endData).Asc("OM_WorkOrder.PlanStartDate").Find(&vdatalst); err != nil {
		return
	}
	datalst = make([]model.WorkOrder, 0)
	for i = 0; i < len(vdatalst); i++ {
		wotab = model.WorkOrder{}
		wotab = vdatalst[i].WorkOrder
		wotab.WorkOrderStatus = vdatalst[i].WorkOrderStatus
		wotab.WorkOrderQty = vdatalst[i].WorkOrderQty
		datalst = append(datalst, wotab)
	}

	return
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/om/WorkOrderDAO.SelectPlannedTasks
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) SelectPlannedTasks(startTime time.Time, endTime time.Time, workLineid string) (datalst []model.WorkOrder, err error) {
	var (
		i        int
		wotab    model.WorkOrder
		vdatalst []model.VOmWorkorder
	)
	startData := utils.TimeFormat(startTime, "yyyy-MM-dd HH:mm:ss")
	endData := utils.TimeFormat(endTime, "yyyy-MM-dd HH:mm:ss")
	session := impl.session.Table(impl.meta.TableName)
	if err = session.Join("INNER", "OM_WorkOrderStatus",
		"OM_WorkOrderStatus.PlantNr = OM_WorkOrder.PlantNr and OM_WorkOrderStatus.WorkOrderId = OM_WorkOrder.WorkOrderId").Join("INNER", "OM_WorkOrderQty",
		"OM_WorkOrderQty.PlantNr = OM_WorkOrder.PlantNr and OM_WorkOrderQty.WorkOrderId = OM_WorkOrder.WorkOrderId").Where("OM_WorkOrder.PlantNr = ? and OM_WorkOrder.ProjectId = ? and OM_WorkOrderStatus.Status = ? and OM_WorkOrder.PlanResourceId = ? and ((OM_WorkOrder.PlanStartTime >= ? and OM_WorkOrder.PlanStartTime < ?) or (OM_WorkOrder.PlanEndTime >= ? and OM_WorkOrder.PlanEndTime < ?))", impl.plantNr, common.ProjectId, common.WO_STATUS_PLANNED, workLineid, startData, endData, startData, endData).Find(&vdatalst); err != nil {
		return
	}
	datalst = make([]model.WorkOrder, 0)
	for i = 0; i < len(vdatalst); i++ {
		wotab = model.WorkOrder{}
		wotab = vdatalst[i].WorkOrder
		wotab.WorkOrderStatus = vdatalst[i].WorkOrderStatus
		wotab.WorkOrderQty = vdatalst[i].WorkOrderQty
		datalst = append(datalst, wotab)
	}

	return
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/om/WorkOrderDAO.SelectUnPlannedTasks
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) SelectUnPlannedTasks(workLineid string) (datalst []model.WorkOrder, err error) {
	var (
		i        int
		wotab    model.WorkOrder
		vdatalst []model.VOmWorkorder
	)

	session := impl.session.Table(impl.meta.TableName)
	if err = session.Join("INNER", "OM_WorkOrderStatus",
		"OM_WorkOrderStatus.PlantNr = OM_WorkOrder.PlantNr and OM_WorkOrderStatus.WorkOrderId = OM_WorkOrder.WorkOrderId").Join("INNER", "OM_WorkOrderQty",
		"OM_WorkOrderQty.PlantNr = OM_WorkOrder.PlantNr and OM_WorkOrderQty.WorkOrderId = OM_WorkOrder.WorkOrderId").Where("OM_WorkOrder.PlantNr = ? and OM_WorkOrderStatus.Status = ? and OM_WorkOrder.ProjectId = ? and OM_WorkOrder.PlanResourceId = ? ", impl.plantNr, common.WO_STATUS_UNPLANNED, common.ProjectId, workLineid).Find(&vdatalst); err != nil {
		return
	}
	datalst = make([]model.WorkOrder, 0)
	for i = 0; i < len(vdatalst); i++ {
		wotab = model.WorkOrder{}
		wotab = vdatalst[i].WorkOrder
		wotab.WorkOrderStatus = vdatalst[i].WorkOrderStatus
		wotab.WorkOrderQty = vdatalst[i].WorkOrderQty
		datalst = append(datalst, wotab)
	}

	return
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/om/WorkOrderDAO.SelectByEndDate
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) SelectByEndDate(artId string, endDate string, projectId string) ([]model.WorkOrder, error) {
	data := make([]model.VOmWorkorder, 0, 1)
	parameters := []interface{}{impl.plantNr}
	session := impl.session.Table(impl.meta.TableName)
	statusCondition := fmt.Sprintf("%s = %s and %s = %s",
		meta.WorkOrder_PlantNr.ColumnName,
		meta.WorkOrderStatus_PlantNr.ColumnName,
		meta.WorkOrder_WorkOrderId.ColumnName,
		meta.WorkOrderStatus_WorkOrderId.ColumnName)
	qtyCondition := fmt.Sprintf("%s = %s and %s = %s",
		meta.WorkOrder_PlantNr.ColumnName,
		meta.WorkOrderQty_PlantNr.ColumnName,
		meta.WorkOrder_WorkOrderId.ColumnName,
		meta.WorkOrderQty_WorkOrderId.ColumnName)
	session = session.Join("LEFT", meta.WorkOrderStatus.TableName, statusCondition)
	session = session.Join("LEFT", meta.WorkOrderQty.TableName, qtyCondition)
	where := fmt.Sprintf("%s = ?", meta.WorkOrder_PlantNr.ColumnName)
	where += fmt.Sprintf(" and %s = ? and %s = ? and %s = ? and %s != ?", meta.WorkOrder_ArtId.ColumnName, meta.WorkOrder_PlanEndDate.ColumnName, meta.WorkOrder_ProjectId.ColumnName, meta.WorkOrder_OrderType2.ColumnName)
	parameters = append(parameters, artId, endDate, projectId, model.CacheWorkOrderType)
	err := session.Where(where, parameters...).Find(&data)
	if err != nil {
		return nil, grmi.NewDataBaseError(err)
	}
	result := make([]model.WorkOrder, 0, len(data))
	for _, voWorkOrder := range data {
		var workOrder model.WorkOrder
		workOrder = voWorkOrder.WorkOrder
		workOrder.WorkOrderStatus = voWorkOrder.WorkOrderStatus
		workOrder.WorkOrderQty = voWorkOrder.WorkOrderQty
		result = append(result, workOrder)
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/om/WorkOrderDAO.SelectByPage
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) SelectByPage(projectId, artId, start, end, workOrderId, orderType string, status, pageIndex, pageSize int, workLineIdLi []string) (grmi.PagingResult, error) {
	data := make([]model.VOmWorkorder, 0, 10)
	parameters := []interface{}{impl.plantNr}
	session := impl.session.Table(impl.meta.TableName)
	statusCondition := fmt.Sprintf("%s = %s and %s = %s",
		meta.WorkOrder_PlantNr.ColumnName,
		meta.WorkOrderStatus_PlantNr.ColumnName,
		meta.WorkOrder_WorkOrderId.ColumnName,
		meta.WorkOrderStatus_WorkOrderId.ColumnName)
	qtyCondition := fmt.Sprintf("%s = %s and %s = %s",
		meta.WorkOrder_PlantNr.ColumnName,
		meta.WorkOrderQty_PlantNr.ColumnName,
		meta.WorkOrder_WorkOrderId.ColumnName,
		meta.WorkOrderQty_WorkOrderId.ColumnName)
	session = session.Join("LEFT", meta.WorkOrderStatus.TableName, statusCondition)
	session = session.Join("LEFT", meta.WorkOrderQty.TableName, qtyCondition)
	query := session
	query = query.Where(fmt.Sprintf("%s = ?", meta.WorkOrder_PlantNr.ColumnName), impl.plantNr)
	where := fmt.Sprintf(" left join %s on %s left join %s on %s ", meta.WorkOrderStatus.TableName, statusCondition,
		meta.WorkOrderQty.TableName, qtyCondition)
	where += fmt.Sprintf(" where %s = ? ", meta.WorkOrder_PlantNr.ColumnName)
	if projectId != "" {
		parameters = append(parameters, projectId)
		query = query.Where(fmt.Sprintf("%s = ?", meta.WorkOrder_ProjectId.ColumnName), projectId)
		where += fmt.Sprintf(" and %s = ? ", meta.WorkOrder_ProjectId.ColumnName)
	}
	if artId != "" {
		parameters = append(parameters, artId)
		query = query.Where(fmt.Sprintf("%s = ?", meta.WorkOrder_ArtId.ColumnName), artId)
		where += fmt.Sprintf(" and %s = ? ", meta.WorkOrder_ArtId.ColumnName)
	}
	if start != "" {
		parameters = append(parameters, start)
		query = query.Where(fmt.Sprintf("%s >= ?", meta.WorkOrder_PlanStartTime.ColumnName), start)
		where += fmt.Sprintf(" and %s >= ? ", meta.WorkOrder_PlanStartTime.ColumnName)
	}
	if end != "" {
		parameters = append(parameters, end)
		query = query.Where(fmt.Sprintf("%s <= ?", meta.WorkOrder_PlanStartTime.ColumnName), end)
		where += fmt.Sprintf(" and %s <= ? ", meta.WorkOrder_PlanStartTime.ColumnName)
	}
	if status != 0 {
		parameters = append(parameters, status)
		query = query.Where(fmt.Sprintf("%s = ?", meta.WorkOrderStatus_Status.ColumnName), status)
		where += fmt.Sprintf(" and %s = ? ", meta.WorkOrderStatus_Status.ColumnName)
	}
	if workOrderId != "" {
		parameters = append(parameters, workOrderId)
		query = query.Where(fmt.Sprintf("%s = ?", meta.WorkOrder_WorkOrderId.ColumnName), workOrderId)
		where += fmt.Sprintf(" and %s = ? ", meta.WorkOrder_WorkOrderId.ColumnName)
	}
	if orderType != "" {
		parameters = append(parameters, orderType)
		query = query.Where(fmt.Sprintf("%s = ?", meta.WorkOrder_OrderType.ColumnName), orderType)
		where += fmt.Sprintf(" and %s = ? ", meta.WorkOrder_OrderType.ColumnName)
	}
	query = query.In(meta.WorkOrder_PlanResourceId.ColumnName, workLineIdLi)
	if len(workLineIdLi) == 0 {
		where += " and 1 <> 1 "
	} else {
		var inStr string
		for index, workLineId := range workLineIdLi {
			if index == 0 {
				inStr += fmt.Sprintf(`'%s'`, workLineId)
			} else {
				inStr += fmt.Sprintf(` ,'%s'`, workLineId)
			}
		}
		where += fmt.Sprintf(" and %s in (%s) ", meta.WorkOrder_PlanResourceId.ColumnName, inStr)
	}
	count, err := query.Count(impl.meta.Indicator)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	orderBy := " order by " + meta.WorkOrder_PlantNr.ColumnName + ", " + meta.WorkOrder_WorkOrderId.ColumnName
	parameters = append(parameters, (pageIndex-1)*pageSize, pageSize)
	err = session.SQL(fmt.Sprintf("select %s.*,%s.*,%s.* from ", meta.WorkOrder.TableName, meta.WorkOrderStatus.TableName, meta.WorkOrderQty.TableName)+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: int64(pageIndex), PageSize: int64(pageSize)}, nil
}
/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/om/WorkOrderDAO.SelectLockWorkOrder
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) SelectLockWorkOrder(workLineId string) ([]model.WorkOrder, error) {
	data := make([]model.VOmWorkorder, 0)
	session := impl.session.Table(impl.meta.TableName)
	statusCondition := fmt.Sprintf("%s = %s and %s = %s",
		meta.WorkOrder_PlantNr.ColumnName,
		meta.WorkOrderStatus_PlantNr.ColumnName,
		meta.WorkOrder_WorkOrderId.ColumnName,
		meta.WorkOrderStatus_WorkOrderId.ColumnName)
	qtyCondition := fmt.Sprintf("%s = %s and %s = %s",
		meta.WorkOrder_PlantNr.ColumnName,
		meta.WorkOrderQty_PlantNr.ColumnName,
		meta.WorkOrder_WorkOrderId.ColumnName,
		meta.WorkOrderQty_WorkOrderId.ColumnName)
	session = session.Join("LEFT", meta.WorkOrderStatus.TableName, statusCondition)
	session = session.Join("LEFT", meta.WorkOrderQty.TableName, qtyCondition)
	where := fmt.Sprintf("%s = ? and %s = ? and %s = ? and (%s = ? or %s = ? or %s = ?)",
		meta.WorkOrder_PlantNr.ColumnName,
		meta.WorkOrder_PlanResourceId.ColumnName,
		meta.WorkOrder_ProjectId.ColumnName,
		meta.WorkOrderStatus_Status.ColumnName,
		meta.WorkOrderStatus_Status.ColumnName,
		meta.WorkOrderStatus_Status.ColumnName)
	err := session.Where(where, impl.plantNr, workLineId, common.ProjectId, common.WO_STATUS_LOCKED, common.WO_STATUS_RELEASED, common.WO_STATUS_RUNNING).Asc(meta.WorkOrder_PlanStartTime.ColumnName).Find(&data)
	if err != nil {
		return nil, err
	}
	workOrderLi := make([]model.WorkOrder, 0, len(data))
	for _, item := range data {
		var workOrder model.WorkOrder
		workOrder = item.WorkOrder
		workOrder.WorkOrderStatus = item.WorkOrderStatus
		workOrder.WorkOrderQty = item.WorkOrderQty
		workOrderLi = append(workOrderLi, workOrder)
	}
	return workOrderLi, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/om/WorkOrderDAO.SelectOneJoin
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) SelectOneJoin(workOrderId string) (*model.VOmWorkorder, error) {
	var data model.VOmWorkorder
	session := impl.session.Table(impl.meta.TableName)
	statusCondition := fmt.Sprintf("%s = %s and %s = %s",
		meta.WorkOrder_PlantNr.ColumnName,
		meta.WorkOrderStatus_PlantNr.ColumnName,
		meta.WorkOrder_WorkOrderId.ColumnName,
		meta.WorkOrderStatus_WorkOrderId.ColumnName)
	qtyCondition := fmt.Sprintf("%s = %s and %s = %s",
		meta.WorkOrder_PlantNr.ColumnName,
		meta.WorkOrderQty_PlantNr.ColumnName,
		meta.WorkOrder_WorkOrderId.ColumnName,
		meta.WorkOrderQty_WorkOrderId.ColumnName)
	session = session.Join("LEFT", meta.WorkOrderStatus.TableName, statusCondition)
	session = session.Join("LEFT", meta.WorkOrderQty.TableName, qtyCondition)
	ok, err := session.Where(fmt.Sprintf("%s = ? and %s = ?", meta.WorkOrder_PlantNr.ColumnName, meta.WorkOrder_WorkOrderId.ColumnName), impl.plantNr, workOrderId).Get(&data)
	if err != nil {
		return nil, grmi.NewDataBaseError(err)
	}
	if !ok {
		return nil, nil
	}
	return &data, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/dao/om/WorkOrderDAO.DeleteByProjectAndEndDate
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) DeleteByProjectAndEndDate(projectId string, endDate string, orderType string) error {
	where := fmt.Sprintf("%s = ? and %s = ? and %s = ? and %s = ?", meta.WorkOrder_PlantNr.ColumnName, meta.WorkOrder_ProjectId.ColumnName, meta.WorkOrder_PlanEndDate.ColumnName, meta.WorkOrder_OrderType2.ColumnName)
	workOrderIdLi := make([]string, 0)
	err := impl.session.Table(impl.meta.TableName).Where(where, impl.plantNr, projectId, endDate, orderType).Cols(meta.WorkOrder_WorkOrderId.ColumnName).Find(&workOrderIdLi)
	if err != nil {
		return err
	}
	_, err = impl.session.Table(impl.meta.TableName).In(meta.WorkOrder_WorkOrderId.ColumnName, workOrderIdLi).Delete(impl.meta.Indicator)
	if err != nil {
		return err
	}
	_, err = impl.session.Table(meta.WorkOrderQty.TableName).In(meta.WorkOrderQty_WorkOrderId.ColumnName, workOrderIdLi).Delete(model.WorkOrderQty{})
	if err != nil {
		return err
	}
	_, err = impl.session.Table(meta.WorkOrderStatus.TableName).In(meta.WorkOrderStatus_WorkOrderId.ColumnName, workOrderIdLi).Delete(model.WorkOrderStatus{})
	if err != nil {
		return err
	}
	return nil
}

func (impl *WorkOrderDAOImplement) ClearOldData(end string) (err error) {
	qtySql := `delete from OM_WorkOrderQty where WorkOrderId in (select WorkOrderId from OM_WorkOrder where ProjectId = 'A30' and CreateTime < ?);`
	statusSql := `delete from OM_WorkOrderStatus where WorkOrderId in (select WorkOrderId from OM_WorkOrder where ProjectId = 'A30' and CreateTime < ?);`
	recSql := `delete from OM_WorkOrderStatusRecLst where WorkOrderId in (select WorkOrderId from OM_WorkOrder where ProjectId = 'A30' and CreateTime < ?);`
	woSql := `delete from OM_WorkOrder where ProjectId = 'A30' and CreateTime < ?;`
	_, err = impl.session.Exec(qtySql, end)
	if err != nil {
		return err
	}
	_, err = impl.session.Exec(statusSql, end)
	if err != nil {
		return err
	}
	_, err = impl.session.Exec(recSql, end)
	if err != nil {
		return err
	}
	_, err = impl.session.Exec(woSql, end)
	if err != nil {
		return err
	}
	return nil
}