package dao

import (
	"fmt"
	"time"
)

type LightrelationVo struct {
	ID                 int    `json:"id"`
	LightID            int    `json:"lightId"`
	RelationType       int    `json:"relationType"`
	Rid                int    `json:"rid"`
	CreateTime         string `json:"createTime"`
	CreateUser         string `json:"createUser"`
	UpdateTime         string `json:"updateTime"`
	UpdateUser         string `json:"updateUser"`
	IsDeleted          int    `json:"isDeleted"`
	TenantID           string `json:"tenantId"`
	IsAutomaticRenewal int    `json:"isAutomaticRenewal"`
	EffectiveDate      string `json:"effectiveDate"`
	EndTime            string `json:"endTime"`
	DeviceSn           string `json:"deviceSn"`
	Location           string `json:"location"`

	LightControlState  string             `json:"lightControlState"`
	IsShowOpts         bool               `json:"isShowOpts"`
	PublicID           int                `json:"publicId"`
	CombinationStrList []interface{}      `gorm:"-" json:"combinationStrList"`
	RunState           string             `json:"runState"`
	Children           *[]LightrelationVo `gorm:"-" json:"children"`
	GroupID            int                `json:"groupId"`
	LampPoleSn         string             `json:"lampPoleSn"`
	LightName          string             `json:"lightName"`
	ControlType        int                `json:"controlType"`
	InstallTime        string             `json:"installTime"`
	LampPoleName       string             `json:"lampPoleName"`
	IsAllYear          int                `json:"isAllYear"`
	PublicName         string             `json:"publicName"`
	StartTime          string             `json:"startTime"`
	LightSn            string             `json:"lightSn"`
	HandSwitch         int                `json:"handSwitch"`
	CombinationStr     string             `json:"combinationStr"`
	LampLng            float64            `json:"lampLng"`
	LampLat            float64            `json:"lampLat"`
}

type IntelligentLightGroupRelation struct {
	IntelligentLight
	LightStrategy
	LightControl
	TimeCondition
	PublicName string `gorm:"_" json:"publicName"`
}

type IntelligentLight struct {
	ID           int       `gorm:"primary key" json:"id"`               //编号
	LightID      int       `gorm:"type:int" json:"lightID"`             //照明策略id
	RelationType int       `gorm:"type:int" json:"relationType"`        //关联类型1=灯控,2=灯杆分组
	Rid          int       `gorm:"type:int" json:"rid"`                 //关联外键ID 根据type类型关联至其表
	TenantId     int       `gorm:"type:int" json:"tenantId"`            //租户ID
	CreateTime   time.Time `gorm:"type:datetime" json:"createTime"`     //新增时间
	CreateUser   int64     `gorm:"type:bigint" json:"createUser"`       //新增记录操作用户ID
	UpdateTime   time.Time `gorm:"type:datetime" json:"updateTime"`     //修改时间
	UpdateUser   int64     `gorm:"type:bigint" json:"updateUser"`       //修改用户
	IsDeleted    int       `gorm:"type:int;default 0" json:"isDeleted"` //是否删除 0=未删除,1=删除
}

func (IntelligentLight) TableName() string {
	return "strategy_intelligent_light"
}

func (c *IntelligentLight) BatchGet(ids []int) ([]IntelligentLight, error) {
	var intelligentLights []IntelligentLight
	err := Db.Debug().Model(&c).Where("light_id in ? and is_deleted = 0", ids).Find(&intelligentLights).Error
	return intelligentLights, err
}

func (c *IntelligentLight) GetByRidAndType() ([]IntelligentLight, error) {
	var intelligentLights []IntelligentLight
	db := Db.Debug().Model(&c).Where("relation_type = ? and is_deleted = 0 and tenant_id = ?",
		c.RelationType, c.TenantId)
	if c.Rid > 0 {
		db = db.Where("rid = ?", c.Rid)
	}
	err := db.Find(&intelligentLights).Error
	return intelligentLights, err
}

func (c *IntelligentLight) GetByGroup2(searchValue string, current, size,
	groupId int) ([]LightrelationVo, error) {
	var groupRelations []LightrelationVo
	where := "lig.tenant_id = ?"
	if groupId != 0 {
		where += fmt.Sprintf(" AND lig.rid in(%v)", groupId)
	}
	sql := `SELECT lig.*,gro.id public_id,gro.pole_group_name public_name,b.light_name,b.light_sn,b.start_time,b.end_time,b.is_all_year,b.is_automatic_renewal
        FROM strategy_intelligent_light lig
        LEFT JOIN device_lamp_pole_group gro ON lig.rid=gro.id
        LEFT JOIN strategy_light b ON b.id=lig.light_id
        WHERE lig.is_deleted=0 AND lig.relation_type=2 AND gro.is_deleted=0
				and ` + where + `
        ORDER BY lig.create_time desc`
	tx := Db.Debug().Raw(sql, c.TenantId).Scan(&groupRelations)
	return groupRelations, tx.Error
}

func (c *IntelligentLight) GetByGroup(searchValue string, current, size,
	groupId int) ([]LightrelationVo, error) {
	var groupRelations []LightrelationVo
	where := " AND con.tenant_id = ?"
	if groupId != 0 {
		where += fmt.Sprintf(" AND con.group_id in(%v)", groupId)
	}
	if searchValue != "" {
		where += fmt.Sprintf(" and (con.sn like '%%v%' or con.name like '%$v%')", searchValue)
	}
	sql := `SELECT
			lig.*,
			con.control_type,
			con.id public_id,
			con.NAME public_name,
			con.sn device_sn,
			con.lamp_pole_name,
			con.lamp_pole_sn,
			con.group_id,
			con.lamp_lat,
			con.lamp_lng,
			con.id as rid,
		
			b.light_name,
			b.light_sn,
			b.start_time,
			b.end_time,
			is_all_year,
			b.is_automatic_renewal,
			con.lamp_pole_location,
			con.install_time 
		FROM
			device_light_control con
			left  JOIN strategy_intelligent_light lig ON  con.id = lig.rid 
			LEFT JOIN strategy_light b ON b.id = lig.light_id
		WHERE
			con.is_deleted = 0
			
			` + where + `
		ORDER BY
			con.create_time asc`
	tx := Db.Debug().Raw(sql, c.TenantId).Scan(&groupRelations)
	return groupRelations, tx.Error

}

func (c IntelligentLight) Update() error {
	return Db.Debug().Model(&c).Where(" id = ? and is_deleted = 0", c.ID).Updates(&c).Error
}

func (c IntelligentLight) Get() (IntelligentLight, error) {
	var intelligentLight IntelligentLight
	err := Db.Debug().Model(&c).Where("is_deleted = 0 and rid = ? and relation_type = ?", c.Rid, c.RelationType).First(&intelligentLight).Error
	return intelligentLight, err
}