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

package implments

import (
	"LAPP_ACURA_MOM_BACKEND/db"
	"LAPP_ACURA_MOM_BACKEND/grmi"
	meta "LAPP_ACURA_MOM_BACKEND/meta/pm"
	model "LAPP_ACURA_MOM_BACKEND/models/pm"
	"LAPP_ACURA_MOM_BACKEND/utils"
	"fmt"
	"github.com/go-xorm/xorm"
	"strconv"
	"strings"
	"xorm.io/core"
)

/******************************************************************************
 *
 * @Struct Name              : WorkOrderDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : WorkOrder的数据访问对象实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-08 13:20:42
 *
 ******************************************************************************/
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-10-08 13:20:42
 *
 ******************************************************************************/
func NewWorkOrderDAOImplement(session *xorm.Session, plantNr int, userid string) *WorkOrderDAOImplement {
	return &WorkOrderDAOImplement{session, &meta.WorkOrder, plantNr, userid}
}

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

	return nil
}

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/pm/WorkOrderDAO.UpdateOne
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) UpdateOne(entity *model.WorkOrder) 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/pm/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_ACURA_MOM_BACKEND/dao/pm/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_ACURA_MOM_BACKEND/dao/pm/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_ACURA_MOM_BACKEND/dao/pm/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_ACURA_MOM_BACKEND/dao/pm/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 {
			if orderBy == " order by " {
				orderBy += field.ColumnName
			} else {
				orderBy += ", " + field.ColumnName
			}
		}
	}
	parameters = append(parameters, paging.Offset(), paging.Size)
	data := make([]model.WorkOrder, 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/pm/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_ACURA_MOM_BACKEND/dao/pm/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.Name)
	entity.LastUser = impl.userid
	_, err := session.Cols(columns...).Update(entity)
	if err != nil {
		return grmi.NewDataBaseError(err)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/pm/WorkOrderDAO.GetPage
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) GetPage(pageSize int, pageIndex int, plantNr int, Assetid int, status int, searchtime string, mainttype string, userId string) ([]model.PmWoService, int, error) {
	data := make([]model.PmWoService, 0)

	e := db.Eloquent.Master()
	assetIdLi := make([]int, 0)
	err := e.Table("PM_UserAssetLst").Where("UserId = ?", userId).Cols("AssetId").Find(&assetIdLi)
	if err != nil {
		return data, 0, err
	}
	serviceIdLi := make([]int, 0)
	err = e.Table("PM_UserServiceLst").Where("UserId = ?", userId).Cols("MainServiceId").Find(&serviceIdLi)
	if err != nil {
		return data, 0, err
	}
	where := `from PM_WorkOrder left join PM_Service on PM_WorkOrder.PlantNr = PM_Service.PlantNr and PM_WorkOrder.MainServiceNr = PM_Service.MainServiceNr`
	where += " where PM_WorkOrder.PlantNr = ? "
	parameters := []interface{}{plantNr}
	table := e.Table(impl.meta.TableName).Where("PM_WorkOrder.PlantNr = ? ", plantNr)
	query := e.Table(impl.meta.TableName)
	table = table.Join("LEFT", "PM_Service", "PM_WorkOrder.PlantNr = PM_Service.PlantNr and PM_WorkOrder.MainServiceNr = PM_Service.MainServiceNr")

	if !utils.ValueIsEmpty(searchtime) {
		searchtimes := strings.Split(searchtime, "-")
		table = table.And("PM_WorkOrder.ActBegTime >= ?", searchtimes[0])
		table = table.And("PM_WorkOrder.ActBegTime <= ?", searchtimes[1])
		where += " and PM_WorkOrder.ActBegTime >= ? "
		where += " and PM_WorkOrder.ActBegTime <= ? "
		parameters = append(parameters, searchtimes[0], searchtimes[1])
	}
	if Assetid > 0 {
		table = table.And("PM_WorkOrder.AssetNr = ?", Assetid)
		where += " and PM_WorkOrder.AssetNr = ? "
		parameters = append(parameters, Assetid)
	}
	if status == 80 {
		table = table.And("PM_WorkOrder.Status = 80")
		where += " and PM_WorkOrder.Status = 80 "

	} else {
		statusLi := []int{26, 40}
		table = table.In("PM_WorkOrder.Status", statusLi)
		where += " and PM_WorkOrder.Status in (26, 40) "
	}
	if mainttype != "" {
		table = table.Where("PM_WorkOrder.MaintType = ?", mainttype)
		where += " and PM_WorkOrder.MaintType = ? "
		parameters = append(parameters, mainttype)
	}
	table = table.In("PM_WorkOrder.AssetNr", assetIdLi)
	table = table.In("PM_WorkOrder.MainServiceNr", serviceIdLi)
	if len(assetIdLi) > 0 {
		inAssetStr := "("
		for index, assetId := range assetIdLi {
			inAssetStr += strconv.Itoa(assetId)
			if index != len(assetIdLi)-1 {
				inAssetStr += ","
			}
		}
		inAssetStr += ")"
		where = where + " and PM_WorkOrder.AssetNr in " + inAssetStr + " "
	} else {
		where += " and 1 = 2 "
	}
	if len(serviceIdLi) > 0 {
		inServiceStr := "("
		for index, serviceId := range serviceIdLi {
			inServiceStr += strconv.Itoa(serviceId)
			if index != len(serviceIdLi)-1 {
				inServiceStr += ","
			}
		}
		inServiceStr += ")"
		where = where + " and PM_WorkOrder.MainServiceNr in " + inServiceStr + " "
	} else {
		where += " and 1 = 2 "
	}

	orderBy := " order by PM_WorkOrder.PlantNr "
	offset := (pageIndex - 1) * pageSize
	querySql := `select PM_WorkOrder.*,PM_Service.* ` + where + orderBy + " offset ? row fetch next ? row only"
	parameters = append(parameters, offset, pageSize)
	err = query.SQL(querySql, parameters...).Find(&data)
	if err != nil {
		fmt.Println("err:", err)
		return data, 0, err
	}

	pcount := new(model.PmWoService)
	count, err := table.Count(pcount)
	if err != nil {
		fmt.Println("err2:", err)
		return data, 0, err
	}
	//now := time.Now()
	//for index, item := range data {
	//	closeTimeStr := item.SchedEndTime
	//	closeTime, err := time.ParseInLocation("20060102150405", closeTimeStr, utils.TimezoneLocation)
	//	if err != nil {
	//		continue
	//	}
	//	if now.Before(closeTime) {
	//		item.UrgencyDegree = UngencyStatusNot
	//	} else {
	//		item.UrgencyDegree = UngencyStatusYes
	//	}
	//	data[index] = item
	//}
	return data, int(count), nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/dao/pm/WorkOrderDAO.SelectLastOne
 *
 ******************************************************************************/
func (impl *WorkOrderDAOImplement) SelectLastOne(PlantNr,MainServiceNr,AssetNr int) (model.WorkOrder, error) {
	var data model.WorkOrder
	ok, err := impl.session.Table(impl.meta.TableName).Where("PlantNr = ? and MainServiceNr = ? and AssetNr = ?", PlantNr, MainServiceNr, AssetNr).OrderBy("SchedBegTime desc").Get(&data)

	if err != nil {
		return data, grmi.NewDataBaseError(err)
	}
	if !ok {
		return data, nil
	}


	return data, nil
}
