package models

import (
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/utils"
	"strings"
)

type PmWostatus struct {
	Finr        int    `json:"finr" xorm:"not null pk INT(4)"`
	Worecnr     int    `json:"worecnr" xorm:"not null pk INT(4)"`
	Maintwoid   string `json:"maintwoid" xorm:"not null VARCHAR(18)"`
	Operator    int    `json:"operator" xorm:"not null INT(4)"`
	Wobagtype   string `json:"wobagtype" xorm:"not null VARCHAR(14)"`
	Statusfrom  int    `json:"statusfrom" xorm:"not null INT(4)"`
	Statusto    int    `json:"statusto" xorm:"not null INT(4)"`
	Operatetime string `json:"operatetime" xorm:"not null VARCHAR(14)"`
	Lastmodif   string `json:"lastmodif" xorm:"not null VARCHAR(14)"`
	Lastuser    string `json:"lastuser" xorm:"not null VARCHAR(20)"`
	Credatuz    string `json:"credatuz" xorm:"not null VARCHAR(14)"`
}

func (t *PmWostatus) TableName() string {
	return "pm_wostatus"
}

func (t *PmWostatus) Add() error {
	e := db.Eloquent.Master()
	_, err := e.Table("pm_wostatus").Insert(t)
	if err != nil {
		return err
	}
	return nil
}

//按维护工单调度ID查询日志
func (t *PmWostatus) SelectAllByID() ([]PmWostatus, error) {
	e := db.Eloquent.Master()
	data := make([]PmWostatus, 0)
	err := e.Table("pm_wostatus").Where("finr = ? and maintwoid = ?", t.Finr, t.Maintwoid).Find(&data)

	if err != nil {
		return data, err
	}

	return data, nil
}

//分页
func (t *PmWostatus) GetPage(pageSize int, pageIndex int, searchtime string) ([]PmWostatus, int, error) {
	data := make([]PmWostatus, 0)
	e := db.Eloquent.Master()
	table := e.Table("pm_wostatus").Where("finr = ? ", t.Finr)
	where := "where finr = " + "'" + utils.ValueToString(t.Finr, "") + "'"

	if !utils.ValueIsEmpty(searchtime) {
		searchtimes := strings.Split(searchtime, "-")
		table = table.And("operatetime >= ?", searchtimes[0])
		table = table.And("operatetime <= ?", searchtimes[1])
		where += " and operatetime >= " + "'" + utils.ValueToString(searchtimes[0], "") + "'"
		where += " and operatetime <= " + "'" + utils.ValueToString(searchtimes[1], "") + "'"
	}
	if !utils.ValueIsEmpty(t.Maintwoid) {
		table = table.And("maintwoid = ?", t.Maintwoid)
		where += " and maintwoid = " + "'" + utils.ValueToString(t.Maintwoid, "") + "'"
	}

	Offset := (pageIndex - 1) * pageSize
	err := e.SQL("SELECT TOP " + utils.ValueToString(pageSize, "") + " pm_wostatus.* FROM pm_wostatus " + where + " AND (convert(varchar(10),finr)+convert(varchar(40),worecnr) NOT IN (SELECT TOP " + utils.ValueToString(Offset, "") + " convert(varchar(10),finr)+convert(varchar(40),worecnr) FROM pm_wostatus " + where + " ORDER BY credatuz DESC)) ORDER BY credatuz DESC").Find(&data)
	pcount := new(PmWostatus)
	count, err := table.Count(pcount)
	if err != nil {
		return data, 0, err
	}
	return data, int(count), nil
}
