package models

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

type PmTemplate struct {
	Finr            int         `json:"pm_template-finr" xorm:"not null pk INT(4)"`
	Maintemplatenr  int         `json:"pm_template-maintemplatenr" xorm:"not null pk INT(4)"`
	Descr           string      `json:"pm_template-descr" xorm:"not null VARCHAR(40)"`
	Trackbydate     int         `json:"pm_template-trackbydate" xorm:"not null SMALLINT(2)"`
	Trackbyprimeter int         `json:"pm_template-trackbyprimeter" xorm:"not null SMALLINT(2)"`
	Primeteruom     string      `json:"pm_template-primeteruom" xorm:"not null VARCHAR(20)"`
	Trackbysecmeter int         `json:"pm_template-trackbysecmeter" xorm:"not null SMALLINT(2)"`
	Secmeteruom     string      `json:"pm_template-secmeteruom" xorm:"not null VARCHAR(20)"`
	Lastmodif       string      `json:"pm_template-lastmodif" xorm:"not null VARCHAR(14)"`
	Lastuser        string      `json:"pm_template-lastuser" xorm:"not null VARCHAR(20)"`
	Credatuz        string      `json:"pm_template-credatuz" xorm:"not null VARCHAR(14)"`
	Valst           []PmService `json:"valst" xorm:"-"`
	UnValst         []PmService `json:"unvalst" xorm:"-"`
}

func (t *PmTemplate) TableName() string {
	return "pm_template"
}

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

//增
func (t *PmTemplate) Add() error {
	e := db.Eloquent.Master()
	snr := new(Snrtab)
	snr.Finr = t.Finr
	//生成ID
	Maintemplatenr, err := snr.GetNextSnr("Templateid")
	t.Maintemplatenr = utils.ValueToInt(Maintemplatenr,0)
	_, err = e.Table("pm_template").Insert(t)
	if err != nil {
		return err
	}
	//批量插入
	alldata := make([]PmTemplateServicelst, 0)
	for k, v := range t.Valst {
		one := PmTemplateServicelst{}
		one.Finr = t.Finr
		one.Pos = k + 1
		one.Descr = v.Descr
		one.Maintemplatenr = t.Maintemplatenr
		one.Mainservicenr = utils.ValueToInt(v.Mainserviceid, 0)
		one.Credatuz = t.Credatuz
		one.Lastuser = t.Lastuser
		one.Lastmodif = t.Lastmodif
		alldata = append(alldata, one)
	}
	_, err = e.Table("pm_template_servicelst").Insert(&alldata)
	if err != nil {
		return err
	}
	return nil
}

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

	return nil
}

//改
func (t *PmTemplate) Update() error {
	e := db.Eloquent.Master()
	_, err := e.ID(core.PK{t.Finr, t.Maintemplatenr}).Update(t)
	if err != nil {
		return err
	}
	//批量删除
	_, err = e.Table("pm_template_servicelst").Where("finr = ? and maintemplatenr = ?", t.Finr, t.Maintemplatenr).Delete(&PmTemplateServicelst{})
	if err != nil {
		return err
	}
	//批量插入
	alldata := make([]PmTemplateServicelst, 0)
	for k, v := range t.Valst {
		one := PmTemplateServicelst{}
		one.Finr = t.Finr
		one.Pos = k + 1
		one.Descr = v.Descr
		one.Maintemplatenr = t.Maintemplatenr
		one.Mainservicenr = utils.ValueToInt(v.Mainserviceid, 0)
		one.Credatuz = t.Credatuz
		one.Lastuser = t.Lastuser
		one.Lastmodif = t.Lastmodif
		alldata = append(alldata, one)
	}
	_, err = e.Table("pm_template_servicelst").Insert(&alldata)
	if err != nil {
		return err
	}
	return nil
}

type TemplateService struct {
	PmTemplateServicelst `xorm:"extends"`
	PmService            `xorm:"extends"`
}

//查
func (t *PmTemplate) SelectOne() (PmTemplate, error) {
	e := db.Eloquent.Master()
	var data PmTemplate
	_, err := e.ID(core.PK{t.Finr, t.Maintemplatenr}).Get(&data)
	if err != nil {
		return data, err
	}
	var datalist []PmService
	var tem []TemplateService
	err = e.Table("pm_template_servicelst").Join("left", "pm_service", "pm_template_servicelst.finr=pm_service.finr and pm_template_servicelst.mainservicenr=pm_service.mainserviceid").Where("pm_template_servicelst.finr = ? and pm_template_servicelst.maintemplatenr = ?", t.Finr, t.Maintemplatenr).Find(&tem)
	if err != nil {
		return data, err
	}
	var maintemplatenrs []int
	for _, v := range tem {
		dataone := PmService{}
		dataone.Mainserviceid = v.Mainserviceid
		dataone.Descr = v.PmService.Descr
		maintemplatenrs = append(maintemplatenrs, v.Maintemplatenr)
		datalist = append(datalist, dataone)
	}
	data.Valst = datalist

	var attrdata []PmService
	err = e.Table("pm_service").NotIn("mainserviceid", maintemplatenrs).Where("finr = ?", t.Finr).Find(&attrdata)
	if err != nil {
		return data, err
	}

	data.UnValst = attrdata
	return data, nil
}

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

//查所有模板
func (t *PmTemplate) SelectArr() ([]PmTemplate, error) {
	e := db.Eloquent.Master()
	data := make([]PmTemplate, 0)
	err := e.Table("pm_template").Where("finr = ?", t.Finr).Find(&data)
	if err != nil {
		return data, err
	}
	return data, nil
}

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

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