package controller

import (
	"bytes"
	"encoding/json"
	"github.com/robfig/cron"
	"io/ioutil"
	"iot_manager_service/app/data/model"
	"iot_manager_service/app/data/service"
	deviceCtl "iot_manager_service/app/device/controller"
	deviceSer "iot_manager_service/app/device/service"
	recordCtl "iot_manager_service/app/record/controller"
	warnSer "iot_manager_service/app/warn/service"
	"iot_manager_service/util/cache"
	"iot_manager_service/util/logger"
	"net/http"
	"time"
)

func CalcTask() {
	hourSpec := "0 0 */1 * * ?"
	//minuteSpec := "0 */1 * * * ?"
	daySpec := "0 1 0 * * ?"
	c := cron.New()
	_ = c.AddFunc(hourSpec, func() {
		devices := deviceSer.GarbageService.GetAll()
		var deviceIds []string
		for _, d := range devices {
			deviceIds = append(deviceIds, d.DeviceIMei)
		}
		GarbageDataSync(deviceIds)
	})

	//【环境传感】日数据 统计
	_ = c.AddFunc(hourSpec, func() {
		service.EnvironmentDataService.DataSync()
	})
	//【环境传感】天数据 统计
	_ = c.AddFunc(daySpec, func() {
		service.EnvironmentDataService.DayDataSync()
	})
	//【告警管理】处理告警消息 同步告警
	c.AddFunc("* */30 * * * ?", func() {
		warnSer.PlatformAlarmService.SyncAlarm()
	})
	//【告警管理】发送告警
	_ = c.AddFunc(hourSpec, func() {
		//发送告警
		warnSer.TaskWarnService.HandlingAlarms()
	})
	//【一键告警】每59秒 同步记录
	c.AddFunc("*/59 * * * * ?", func() {
		recordCtl.AKeyAlarmRecord.SosRecordSync()
	})
	//【led信息屏】每5分钟 同步亮度与音量
	c.AddFunc("* */5 * * * ?", func() {
		deviceCtl.InfoBoard.CronSyncBrightnessAndMusicvolume()
	})
	//【led信息屏】每59秒 播放节目同步
	c.AddFunc("*/59 * * * * ?", func() {
		deviceCtl.InfoBoard.CronSyncLedPaying(0)
	})
	//【IP音柱】每59秒 播放节目同步
	c.AddFunc("*/10 * * * * ?", func() {
		deviceCtl.IpBroadcast.CronSyncIpCastPaying(0)
	})
	c.Start()
}

func GarbageDataSync(deviceIds []string) {
	if len(deviceIds) == 0 {
		return
	}
	url := "http://124.239.149.63:5000/admin/garbage/can/getGarbageCanByDeviceIdsList"
	req := model.GarbageDataReq{
		DeviceIds: deviceIds,
	}
	data, err := json.Marshal(&req)
	if err != nil {
		logger.Logger.Warningf("GarbageDataSync Marshal err = %s", err.Error())
		return
	}
	body := bytes.NewBuffer(data)
	request, err := http.NewRequest("POST", url, body)
	if err != nil {
		logger.Logger.Warningf("GarbageDataSync NewRequest err = %s", err.Error())
		return
	}
	request.Header.Set("Authorization", "Bearer "+GarbageLogin())
	request.Header.Set("Content-Type", "application/json")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		logger.Logger.Warningf("GarbageDataSync Do err = %s", err.Error())
		return
	}
	rspData, err := ioutil.ReadAll(response.Body)
	if err != nil {
		logger.Logger.Warningf("GarbageDataSync ReadAll err = %s", err.Error())
		return
	}
	var rsp model.GarbageDataRsp
	err = json.Unmarshal(rspData, &rsp)
	if err != nil {
		logger.Logger.Warningf("GarbageDataSync Unmarshal err = %s", err.Error())
		return
	}
	if rsp.Code != 0 {
		logger.Logger.Warningf("GarbageDataSync rsp.Code != 0 msg = %s", rsp.Msg)
		return
	}

	service.GarbageDataService.BatchSave(rsp.Data)
}

func GarbageLogin() string {
	value, err := cache.Redis.Get(model.GarbageLoginKey).Result()
	if err == nil {
		return value
	}

	url := "http://124.239.149.63:5000/admin/user/login"
	req := model.GarbageLoginReq{
		Username: "湖南溢满1",
		Password: "T2rMLUCMaaBXfjBjZ7myOA==",
	}
	data, err := json.Marshal(&req)
	if err != nil {
		logger.Logger.Warningf("GarbageLogin Marshal err = %s", err.Error())
		return ""
	}
	body := bytes.NewBuffer(data)
	request, err := http.NewRequest("POST", url, body)
	if err != nil {
		logger.Logger.Warningf("GarbageLogin NewRequest err = %s", err.Error())
		return ""
	}
	request.Header.Set("Content-Type", "application/json")

	response, err := http.DefaultClient.Do(request)
	if err != nil {
		logger.Logger.Warningf("GarbageLogin Do err = %s", err.Error())
		return ""
	}
	rspData, err := ioutil.ReadAll(response.Body)
	if err != nil {
		logger.Logger.Warningf("GarbageLogin ReadAll err = %s", err.Error())
		return ""
	}
	var rsp model.GarbageLoginRsp
	err = json.Unmarshal(rspData, &rsp)
	if err != nil {
		logger.Logger.Warningf("GarbageLogin Unmarshal err = %s", err.Error())
		return ""
	}
	if rsp.Code != 0 {
		logger.Logger.Warningf("GarbageLogin rsp.Code != 0 msg = %s", rsp.Msg)
		return ""
	}
	cache.Redis.Set(model.GarbageLoginKey, rsp.Data.AccessToken, 2*time.Hour)
	return rsp.Data.AccessToken
}
