package models

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

type PmAsset struct {
	Finr           int          `xorm:"not null pk INT(4)" json:"pm_asset-finr"`
	Assetid        int          `xorm:"not null pk INT(4)" json:"pm_asset-assetid"`
	Descr          string       `xorm:"VARCHAR(40)" json:"pm_asset-descr"`
	Assetname      string       `xorm:"VARCHAR(18)" json:"pm_asset-assetname"`
	Assettype      string       `xorm:"VARCHAR(20)" json:"pm_asset-assettype"`
	Model          string       `xorm:"VARCHAR(14)" json:"pm_asset-model"`
	Year           string       `xorm:"VARCHAR(4)" json:"pm_asset-year"`
	Serialno       string       `xorm:"VARCHAR(40)" json:"pm_asset-serialno"`
	Tagno          string       `xorm:"VARCHAR(40)" json:"pm_asset-tagno"`
	Maker          string       `xorm:"VARCHAR(40)" json:"pm_asset-maker"`
	Locaid         int          `xorm:"not null INT(4)" json:"pm_asset-locaid"`
	Assetstatus    int          `xorm:"not null INT(4)" json:"pm_asset-assetstatus"`
	Operator       int          `xorm:"not null INT(4)" json:"pm_asset-operator"`
	Weekmodelid    int          `xorm:"not null INT(4)" json:"pm_asset-weekmodelid"`
	Workcalendarid int          `xorm:"not null INT(4)" json:"pm_asset-workcalendarid"`
	Costcenterid   string       `xorm:"VARCHAR(12)" json:"pm_asset-costcenterid"`
	Lastmodif      string       `xorm:"VARCHAR(14)" json:"pm_asset-lastmodif"`
	Lastuser       string       `xorm:"VARCHAR(20)" json:"pm_asset-lastuser"`
	Credatuz       string       `xorm:"VARCHAR(14)" json:"pm_asset-credatuz"`
	Valst          []PmTemplate `json:"valst" xorm:"-"`
	UnValst        []PmTemplate `json:"unvalst" xorm:"-"`
}

func (t *PmAsset) TableName() string {
	return "pm_asset"
}

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

//增
func (t *PmAsset) Add() error {
	e := db.Eloquent.Master()
	snr := new(Snrtab)
	snr.Finr = t.Finr
	affw, err := snr.GetNextSnr("Assetid")
	if err != nil {
		return err
	}
	t.Assetid = utils.ValueToInt(affw, 0)
	_, err = e.Table("pm_asset").Insert(t)
	if err != nil {
		return err
	}
	//批量插入
	alldata := make([]PmAssetTemplatelst, 0)
	for k, v := range t.Valst {
		dataone := PmAssetTemplatelst{}
		dataone.Finr = t.Finr
		dataone.Assetid = t.Assetid
		dataone.Maintemplatenr = v.Maintemplatenr
		dataone.Pos = k + 1
		dataone.Credatuz = t.Credatuz
		dataone.Lastmodif = t.Lastmodif
		dataone.Lastuser = t.Lastmodif
		alldata = append(alldata, dataone)
	}
	_, err = e.Table("pm_asset_templatelst").Insert(&alldata)
	if err != nil {
		return err
	}
	return nil
}

//删
func (t *PmAsset) Del() error {
	e := db.Eloquent.Master()
	_, err := e.Where("finr = ? and assetid = ?", t.Finr, t.Assetid).Delete(&PmAsset{})
	if err != nil {
		return err
	}
	countrole := new(PmAssetTemplatelst)
	affw, _ := e.Table("pm_asset_templatelst").Where("finr = ? and assetid = ?", t.Finr, t.Assetid).Count(countrole)
	if affw > 0 {
		_, err = e.Where("finr = ? and assetid = ?", t.Finr, t.Assetid).Delete(&PmAssetTemplatelst{})
		if err != nil {
			return err
		}
	}

	return nil
}

//改
func (t *PmAsset) Update() error {
	e := db.Eloquent.Master()
	_, err := e.ID(core.PK{t.Finr, t.Assetid}).Update(t)
	if err != nil {
		return err
	}
	//批量删除
	_, err = e.Table("pm_asset_templatelst").Where("finr = ? and assetid = ?", t.Finr, t.Assetid).Delete(&PmAssetTemplatelst{})
	if err != nil {
		return err
	}
	//批量插入
	alldata := make([]PmAssetTemplatelst, 0)
	for k, v := range t.Valst {
		dataone := PmAssetTemplatelst{}
		dataone.Finr = t.Finr
		dataone.Assetid = t.Assetid
		dataone.Maintemplatenr = v.Maintemplatenr
		dataone.Pos = k + 1
		dataone.Credatuz = t.Credatuz
		dataone.Lastmodif = t.Lastmodif
		dataone.Lastuser = t.Lastmodif
		alldata = append(alldata, dataone)
	}
	_, err = e.Table("pm_asset_templatelst").Insert(&alldata)
	if err != nil {
		return err
	}
	return nil
}

type TemplateAsset struct {
	PmAssetTemplatelst `xorm:"extends"`
	PmTemplate         `xorm:"extends"`
}

//查
func (t *PmAsset) SelectOne() (PmAsset, error) {
	e := db.Eloquent.Master()
	var data PmAsset
	_, err := e.ID(core.PK{t.Finr, t.Assetid}).Get(&data)
	if err != nil {
		return data, err
	}
	var datalist []PmTemplate
	var tem []TemplateAsset
	err = e.Table("pm_asset_templatelst").Join("left", "pm_template", "pm_asset_templatelst.finr=pm_template.finr and pm_asset_templatelst.maintemplatenr=pm_template.maintemplatenr").Where("pm_asset_templatelst.finr = ? and pm_asset_templatelst.assetid = ?", t.Finr, t.Assetid).Find(&tem)
	if err != nil {
		return data, err
	}
	var Maintemplatenrs []int
	for _, v := range tem {
		dataone := PmTemplate{}
		dataone.Maintemplatenr = v.PmAssetTemplatelst.Maintemplatenr
		dataone.Descr = v.PmTemplate.Descr
		Maintemplatenrs = append(Maintemplatenrs, v.PmAssetTemplatelst.Maintemplatenr)
		datalist = append(datalist, dataone)
	}
	data.Valst = datalist

	var templatedata []PmTemplate
	err = e.Table("pm_template").NotIn("maintemplatenr", Maintemplatenrs).Where("finr = ?", t.Finr).Find(&templatedata)
	if err != nil {
		return data, err
	}

	data.UnValst = templatedata
	return data, nil
}

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

//分页
func (t *PmAsset) GetPage(descr string, pageSize int, pageIndex int) ([]PmAsset, int, error) {
	data := make([]PmAsset, 0)
	e := db.Eloquent.Master()
	table := e.Table("pm_asset").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_asset where finr = ?"+where+") t order by assetid offset ? row fetch next ? row only", parameters...).Find(&data)
	if err != nil {
		return data, 0, err
	}

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

//查资产对应的服务
func (t *PmAsset) SelectServices() ([]PmService, error) {
	data := make([]CreateData, 0)
	serves := make([]PmService, 0)
	//第一步，多表联查出所有的数据
	e := db.Eloquent.Master()
	query := e.Table("pm_asset")
	query = query.Join("INNER", "pm_asset_templatelst", "pm_asset.finr = pm_asset_templatelst.finr and pm_asset.assetid = pm_asset_templatelst.assetid")
	query = query.Join("INNER", "pm_template", "pm_template.finr = pm_asset_templatelst.finr and pm_template.maintemplatenr = pm_asset_templatelst.maintemplatenr")
	query = query.Join("INNER", "pm_template_servicelst", "pm_template.finr = pm_template_servicelst.finr and pm_template.maintemplatenr = pm_template_servicelst.maintemplatenr")
	query = query.Join("INNER", "pm_service", "pm_service.finr = pm_template_servicelst.finr and pm_service.mainserviceid = pm_template_servicelst.mainservicenr")

	err := query.Where("pm_asset.finr = ? and pm_asset.assetid = ?", t.Finr, t.Assetid).Find(&data)
	if err != nil {
		return serves, err
	}
	for _, v := range data {
		one := PmService{}
		one = v.PmService
		serves = append(serves, one)
	}
	return serves, nil
}
