package service

import (
	"fmt"
	"iot_manager_service/app/device/dao"
	"iot_manager_service/app/device/edge_service"
	"iot_manager_service/app/device/model"
	"iot_manager_service/app/system/service"
	"iot_manager_service/util/cache"
	"iot_manager_service/util/common"
	"strconv"
	"time"
)

var IntelligentLightingService = new(intelligentLightingService)

type intelligentLightingService struct{}

func (s *intelligentLightingService) GetDetailByLight(tenantId string, id int, reqType int) (model.RspIntelligentLightDetail,
	*common.Errors) {
	detail := model.RspIntelligentLightDetail{}
	if reqType == 2 {
		lightControl, _ := LightControlService.GetByGroupId(id)
		if lightControl != nil {
			lightControlOne := lightControl[0]
			for i, control := range lightControl {
				_, state := cache.GetDeviceState(control.Sn)
				lightControl[i].Status, _ = strconv.Atoi(state)
			}
			lightControlOne.LampPoleName = lightControlOne.LampPoleName + "(" + lightControlOne.LampPoleSn + ")"
			detail.LightControlList = lightControl
			detail.LampPoleName = lightControlOne.LampPoleName
			//id = lightControl[0].ID
		}

	} else {
		lightControl, _ := LightControlService.GetOne(id)
		if lightControl != nil {
			_, state := cache.GetDeviceState(lightControl.Sn)
			lightControl.Status, _ = strconv.Atoi(state)
			lightControl.LampPoleName = lightControl.LampPoleName + "(" + lightControl.LampPoleSn + ")"
			detail.LightControlList = []dao.LightControl{*lightControl}
			detail.LampPoleName = lightControl.LampPoleName
		}
	}
	//fmt.Printf("id = %v", id)
	detail.LightRelMap = s.GetLightRelation(tenantId, id, reqType)
	return detail, nil
}

func (s *intelligentLightingService) GetLightRelation(tenantId string, rId, relationType int) model.IntelligentLightSimple {
	detail := model.IntelligentLightSimple{}

	// 获取照明策略关联
	intelligentLight := dao.IntelligentLight{
		Rid:          rId,
		RelationType: relationType,
		TenantId:     tenantId,
	}
	relations, _ := intelligentLight.GetByRidAndType()
	//fmt.Printf("rId = %v", rId)
	//fmt.Printf("relations = %v", relations)
	if len(relations) == 0 {
		return detail
	}
	lightId := relations[0].LightID

	// 获取策略详情（日期，如果是年，使用当前年起始日期）
	lightStrategy, _ := LightStrategyService.GetOne(lightId)

	if lightStrategy == nil {
		return detail
	}
	//获取灯控名称和SN
	detail.LightName = lightStrategy.LightName
	detail.LightSn = lightStrategy.LightSn

	//全年
	if lightStrategy.IsAllYear == model.IsYear {
		year := time.Now().Year()
		detail.EffectiveDate = fmt.Sprintf("%d-01-01 ~ %d-12-31", year, year)
	} else {
		detail.EffectiveDate = lightStrategy.StartTime + " ~ " + lightStrategy.EndTime
	}

	// 获取策略时间（每日的时间策略）
	timeConditions := TimeConditionService.GetByLightId(lightId)
	for _, timeCondition := range timeConditions {
		if timeCondition.StartTime == "" && timeCondition.EndTime == "" {
			timeCondition.StartTime = "日落"
			timeCondition.EndTime = "日出"
		}
		detail.TimeConditionList = append(detail.TimeConditionList, model.TimeConditionSimple{
			Luminance: strconv.Itoa(timeCondition.Luminance) + "%",
			Times:     timeCondition.StartTime + " ~ " + timeCondition.EndTime,
		})
	}

	return detail
}

func (s *intelligentLightingService) BatchGet(ids []int) []dao.IntelligentLight {
	// 创建查询实例
	intelligent := &dao.IntelligentLight{}
	intelligentLights, err := intelligent.BatchGet(ids)
	if err != nil {
		return nil
	}
	return intelligentLights
}

func (s *intelligentLightingService) List(tenantId string, searchValue string, current, size,
	groupId int) ([]dao.LightrelationVo, int64, error) {
	var result []dao.LightrelationVo
	//获取策略关联信息
	intelligent := &dao.IntelligentLight{
		RelationType: model.RelationTypeLampPoleGroup,
		TenantId:     tenantId,
	}
	//println("fasdf")
	list, err := intelligent.GetByGroup2(searchValue, current, size, groupId)
	if err != nil {
		return nil, 0, err
	}
	for _, intelligentLight := range list {
		_, state := cache.GetDeviceState(intelligentLight.LightSn)
		intelligentLight.RunState = state
		intelligentLight.RelationType = 2
		intelligentLight.DeviceSn = "全组"
		intelligentLight.IsShowOpts = true
		result = append(result, intelligentLight)
	}
	var total int64
	for i, vo := range result {
		groupId := vo.Rid
		group2, count, _ := intelligent.GetByGroup(searchValue, current, size, groupId)
		for i2, group := range group2 {
			_, state := cache.GetDeviceState(group.DeviceSn)
			group.RunState = state
			group.RelationType = 1
			if vo.PublicID == group.GroupID {
				group.IsShowOpts = true
			}
			// 灯状态
			switchState := cache.GetSwitchState(group.DeviceSn)
			group.LightControlState = "2"
			if switchState {
				group.LightControlState = "1"
			}
			group2[i2] = group

		}
		//total += 1
		total = count
		result[i].Children = &group2
	}
	return result, total, nil
}

// Relation 保存策略
func (s *intelligentLightingService) Relation(userId int64, tenantId string, publicId int, lightId int, relationType int) error {
	intelligent := &dao.IntelligentLight{
		LightID:      lightId,
		Rid:          publicId,
		TenantId:     tenantId,
		RelationType: relationType,
	}
	//TODO：如果是同步组的，下方的都要修改???
	if relationType == 2 {
	}
	intelligentLight, err := intelligent.Get()
	if err != nil {
		panic(err)
	}
	intelligentLight.LightID = lightId
	intelligentLight.Update()
	//TODO：这里要调用边缘接口同步
	//fmt.Printf("intelligentLight = %v", intelligentLight)

	service.OperationHisService.Save(userId, tenantId, common.OperationStrategyRelation, common.ModuleTypeLightStrategy,
		common.DeviceTypeLightControl, common.GetDeviceObject(publicId, "保存策略"+string(lightId)), common.OperationSuccess)
	return nil
}

// Recovery 恢复到分组
func (s *intelligentLightingService) Recovery(userId int64, tenantId string, groupId int, id int) error {
	//1.IntelligentLight查出 `relation_type` = '2' AND `rid` = '67'  查出组中的 light_id
	//2.IntelligentLight保存 上面 的light_id 到 id中
	intelligent := &dao.IntelligentLight{
		Rid:          groupId,
		TenantId:     tenantId,
		RelationType: 2,
	}
	intelligentLight, err := intelligent.Get()
	if err != nil {
		panic(err)
	}
	lightID := intelligentLight.LightID
	intelligent2 := &dao.IntelligentLight{
		ID:      id,
		LightID: lightID,
	}
	//TODO：这里要调用边缘接口同步
	intelligent2.Update()
	service.OperationHisService.Save(userId, tenantId, common.OperationStrategyRelation, common.ModuleTypeLightStrategy,
		common.DeviceTypeLightControl, common.GetDeviceObject(id, "恢复到分组"+string(lightID)), common.OperationSuccess)
	return nil
}

// ChangeHandSwitch 开灯控制
func (s *intelligentLightingService) ChangeHandSwitch(userId int64, tenantId string, handSwitch int, handType int, publicId int, handTime int, luminance int, explain string, name string) error {
	light, err := s.GetDetailByLight(tenantId, publicId, handType)
	if err != nil {
		panic(err)
	}
	list := light.LightControlList
	var sn []string
	for _, control := range list {
		sn = append(sn, control.Sn)
	}
	fmt.Printf("操作的sn = %v", sn)
	// 这里要调用云端 操作灯控
	var forLightControlReq edge_service.ForLightControlReq
	forLightControlReq.Codes = sn
	forLightControlReq.Tenant = tenantId
	forLightControlReq.Recovery = handTime
	forLightControlReq.Brightness = luminance
	str := "灯控"
	if handType == 2 {
		str = "灯杆分组"
	}
	if handSwitch == 1 {
		str += "[开启]"
		forLightControlReq.Switchon = 1
	} else {
		str += "[关闭]"
		forLightControlReq.Switchon = 0
	}
	edge_service.ForLightControl{}.SwitchLightCtr(forLightControlReq)
	service.OperationHisService.Save(userId, tenantId, common.OperationControl, common.ModuleTypeLightStrategy,
		common.DeviceTypeLightControl, common.GetDeviceObject(publicId, "照明开关控制"), common.OperationSuccess)
	return nil
}
