package models

import (
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/utils"
	"xorm.io/core"
)

type PmService struct {
	Finr               int           `json:"pm_service-finr" xorm:"not null pk INT(4)"`
	Mainserviceid      string        `json:"pm_service-mainserviceid" xorm:"not null pk VARCHAR(20)"`
	Descr              string        `json:"pm_service-descr" xorm:"not null VARCHAR(40)"`
	Mainttype          string        `json:"pm_service-mainttype" xorm:"not null VARCHAR(14)"`
	Priority           int           `json:"pm_service-priority" xorm:"not null SMALLINT(2)"`
	Enabled            int           `json:"pm_service-enabled" xorm:"not null SMALLINT(2)"`
	Maintbydate        int           `json:"pm_service-maintbydate" xorm:"not null SMALLINT(2)"`
	Duedateinterval    int           `json:"pm_service-duedateinterval" xorm:"not null INT(4)"`
	Nodifydays         int           `json:"pm_service-nodifydays" xorm:"not null INT(4)"`
	Duedateon          string        `json:"pm_service-duedateon" xorm:"not null VARCHAR(8)"`
	Maintbyhour        int           `json:"pm_service-maintbyhour" xorm:"not null SMALLINT(2)"`
	Duehourinterval    int           `json:"pm_service-duehourinterval" xorm:"not null INT(4)"`
	Nodifyhours        int           `json:"pm_service-nodifyhours" xorm:"not null INT(4)"`
	Duehouron          string        `json:"pm_service-duehouron" xorm:"not null VARCHAR(8)"`
	Maintbymileage     int           `json:"pm_service-maintbymileage" xorm:"not null SMALLINT(2)"`
	Duemileageinterval int           `json:"pm_service-duemileageinterval" xorm:"not null INT(4)"`
	Nodifymileages     int           `json:"pm_service-nodifymileages" xorm:"not null INT(4)"`
	Duemileageat       int           `json:"pm_service-duemileageat" xorm:"not null INT(4)"`
	Needschedule       int           `json:"pm_service-needschedule" xorm:"not null INT(4)"`
	Maintimelen        float64       `json:"pm_service-maintimelen" xorm:"not null DECIMAL(16,6)"`
	Timeunit           string        `json:"pm_service-timeunit" xorm:"not null VARCHAR(5)"`
	Lastmodif          string        `json:"pm_service-lastmodif" xorm:"not null VARCHAR(14)"`
	Lastuser           string        `json:"pm_service-lastuser" xorm:"not null VARCHAR(20)"`
	Credatuz           string        `json:"pm_service-credatuz" xorm:"not null VARCHAR(14)"`
	Schedtype          string        `json:"pm_service-schedtype" xorm:"not null VARCHAR(14)"`
	Department         string        `json:"pm_service-department" xorm:"not null VARCHAR(10)"`
	Valst              []PmAttribute `json:"valst" xorm:"-"`
	UnValst            []PmAttribute `json:"unvalst" xorm:"-"`
}

type PMServiceAsset struct {
	PmService `xorm:"extends"`
	PmAssetTemplatelst `xorm:"extends"`
	PmTemplateServicelst `xorm:"extends"`
}

func (t *PmService) TableName() string {
	return "pm_service"
}

// 清除string字段的右侧空格
func (t *PmService) Clipped() {
	utils.TrimStruct(t, *t)
}

//增
func (t *PmService) Add() error {
	e := db.Eloquent.Master()
	snr := new(Snrtab)
	snr.Finr = t.Finr
	//生成ID
	Mainserviceid, err := snr.GetNextSnr("Serviceid")
	t.Mainserviceid = Mainserviceid
	_, err = e.Table("pm_service").Insert(t)
	if err != nil {
		return err
	}
	//批量插入
	alldata := make([]PmServiceAttrlst, 0)
	for k, v := range t.Valst {
		one := PmServiceAttrlst{}
		one.Finr = t.Finr
		one.Mainserviceid = t.Mainserviceid
		one.Pos = k + 1
		one.Attrnr = v.Attrnr
		one.Descr = v.Descr
		one.Attrname = v.Attrname
		one.Parameter = v.Parameter
		one.Credatuz = t.Credatuz
		one.Lastuser = t.Lastuser
		one.Lastmodif = t.Lastmodif
		alldata = append(alldata, one)
	}
	_, err = e.Table("pm_service_attrlst").Insert(&alldata)
	if err != nil {
		return err
	}
	return nil
}

//删
func (t *PmService) Del() bool {
	e := db.Eloquent.Master()
	_, err := e.Where("finr = ? and mainserviceid = ?", t.Finr, t.Mainserviceid).Delete(&PmService{})
	if err != nil {
		return false
	}
	countrole := new(PmServiceAttrlst)
	affw, _ := e.Table("pm_service_attrlst").Where("finr = ? and mainserviceid = ?", t.Finr, t.Mainserviceid).Count(countrole)
	if affw > 0 {
		_, err = e.Where("finr = ? and mainserviceid = ?", t.Finr, t.Mainserviceid).Delete(&PmServiceAttrlst{})
		if err != nil {
			return false
		}
	}

	return true
}

//改
func (t *PmService) Update() bool {
	e := db.Eloquent.Master()

	_, err := e.ID(core.PK{t.Finr, t.Mainserviceid}).Cols("descr", "mainttype", "priority", "enabled", "maintbydate", "duedateinterval", "nodifydays", "duedateon", "maintbyhour", "duehourinterval", "nodifyhours", "duehouron", "maintbymileage", "duemileageinterval", "nodifymileages", "duemileageat", "needschedule", "maintimelen", "timeunit", "lastmodif", "lastuser", "credatuz", "schedtype", "department").Update(t)
	if err != nil {
		return false
	}
	//批量删除
	_, err = e.Table("pm_service_attrlst").Where("finr = ? and mainserviceid = ?", t.Finr, t.Mainserviceid).Delete(&PmServiceAttrlst{})
	if err != nil {
		return false
	}
	//批量插入
	alldata := make([]PmServiceAttrlst, 0)
	for k, v := range t.Valst {
		one := PmServiceAttrlst{}
		one.Finr = t.Finr
		one.Mainserviceid = t.Mainserviceid
		one.Pos = k + 1
		one.Attrnr = v.Attrnr
		one.Descr = v.Descr
		one.Attrname = v.Attrname
		one.Parameter = v.Parameter
		one.Credatuz = t.Credatuz
		one.Lastuser = t.Lastuser
		one.Lastmodif = t.Lastmodif
		alldata = append(alldata, one)
	}
	_, err = e.Table("pm_service_attrlst").Insert(&alldata)
	if err != nil {
		return false
	}
	return true
}

type ServiceAttr struct {
	PmServiceAttrlst `xorm:"extends"`
	PmAttribute      `xorm:"extends"`
}

//查
func (t *PmService) SelectOne() (PmService, error) {
	e := db.Eloquent.Master()
	var data PmService
	_, err := e.ID(core.PK{t.Finr, t.Mainserviceid}).Get(&data)
	if err != nil {
		return data, err
	}
	var datalist []PmAttribute
	var tem []ServiceAttr
	err = e.Table("pm_service_attrlst").Join("Left", "pm_attribute", "pm_attribute.finr = pm_service_attrlst.finr and pm_attribute.attrnr = pm_service_attrlst.attrnr").Where("pm_service_attrlst.finr = ? and pm_service_attrlst.mainserviceid = ?", t.Finr, t.Mainserviceid).Find(&tem)
	if err != nil {
		return data, err
	}
	var attrnrs []int
	for _, v := range tem {
		attrnrs = append(attrnrs, v.PmAttribute.Attrnr)
		v.PmAttribute.Parameter = v.PmServiceAttrlst.Parameter
		datalist = append(datalist, v.PmAttribute)
	}
	data.Valst = datalist

	var attrdata []PmAttribute
	err = e.Table("pm_attribute").NotIn("attrnr", attrnrs).Where("finr = ?", t.Finr).Find(&attrdata)
	if err != nil {
		return data, err
	}

	data.UnValst = attrdata
	return data, nil
}

//查所有
func (t *PmService) SelectAll() ([]PmAttribute, error) {
	e := db.Eloquent.Master()
	var data []PmAttribute
	err := e.Table("pm_attribute").Where("finr = ?", t.Finr).Find(&data)
	if err != nil {
		return data, err
	}
	return data, nil
}

//分页
func (t *PmService) GetPage(descr string, pageSize int, pageIndex int) ([]PmService, int, error) {
	data := make([]PmService, 0)
	e := db.Eloquent.Master()
	table := e.Table("pm_service").Where("finr = ? ", t.Finr)
	parameters := make([]interface{}, 0)
	where := ""
	parameters = append(parameters, t.Finr)
	if descr != "" {
		table = table.And("descr like concat('%',?,'%')", descr)
		where += " and descr like concat('%',?,'%')"
		parameters = append(parameters, descr)
	}
	parameters = append(parameters, (pageIndex-1)*pageSize, pageSize)
	err := e.SQL("SELECT * FROM (SELECT * FROM pm_service where finr = ?"+where+") t order by mainserviceid offset ? row fetch next ? row only", parameters...).Find(&data)
	if err != nil {
		return data, 0, err
	}

	count, err := table.Count(new(PmService))
	if err != nil {
		return nil, 0, err
	}
	for k, _ := range data {
		data[k].Clipped()
	}
	return data, int(count), nil
}

func (t *PmService) Select(assetId int) ([]PMServiceAsset,  error) {
	pmServiceLi := make([]PMServiceAsset, 0)
	e := db.Eloquent.Master()
	query := e.Table(t.TableName()).Join("LEFT", "pm_template_servicelst", "pm_service.finr = pm_template_servicelst.finr and pm_service.mainserviceid = pm_template_servicelst.mainservicenr")
	query = query.Join("LEFT", "pm_asset_templatelst", "pm_template_servicelst.finr = pm_asset_templatelst.finr and pm_template_servicelst.maintemplatenr = pm_asset_templatelst.maintemplatenr")
	err := query.Where("pm_asset_templatelst.assetid = ?", assetId).Find(&pmServiceLi)
	return pmServiceLi, err
}