package service

import (
	"cold-delivery/app/admin/model"
	"cold-delivery/app/admin/service/dto"
	cDto "cold-delivery/common/dto"
	"cold-delivery/common/global"
	model2 "cold-delivery/common/model"
	"cold-delivery/common/nats/nats_server"
	"errors"
	"fmt"
	"gogs.baozhida.cn/zoie/OAuth-core/service"
	"gorm.io/gorm"
	"sort"
	"time"
)

type WaybillTask struct {
	service.Service
}

func WaybillTaskTimeScopes(startTime, endTime string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if len(startTime) == 0 && len(endTime) == 0 {
			return db
		}
		return db.Where("(start_time between ? and ?) or (end_time between ? and ?)",
			startTime, endTime, startTime, endTime)
	}
}

// GetPage 获取WaybillTask列表
func (e *WaybillTask) GetPage(c *dto.WaybillTaskGetPageReq, list *[]model.WaybillTask, count *int64) error {
	var err error
	var data model.WaybillTask
	var waybill model.Waybill
	err = e.Orm.Model(&waybill).Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return errors.New("获取运单信息失败")
	}

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
		).
		Preload("CoolerBox").
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.GetFailedErr
	}
	// 获取公司秘钥
	var company model.SysDept
	company, err = model.GetCompanyById(waybill.DeptId)
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return model.GetCompanyKeyErr
	}
	for i := 0; i < len(*list); i++ {
		// 获取传感器信息
		deviceSensorList, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey((*list)[i].Sn, company.ColdKey)
		(*list)[i].DeviceSensorList = deviceSensorList
	}
	return nil
}
func (e *WaybillTask) Get(c *dto.WeianGetWaybillDataReq, task *model.WaybillTask) error {
	var err error
	var data model.WaybillTask
	var waybill model.Waybill
	err = e.Orm.Model(&waybill).Where("waybill_no = ? or order_no = ?", c.WaybillNo, c.WaybillNo).First(&waybill).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return errors.New("获取运单信息失败")
	}

	err = e.Orm.Model(&data).
		Where("waybill_no = ?", waybill.WaybillNo).
		Preload("CoolerBox").
		First(task).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return errors.New("获取运单任务信息失败")
	}
	// 获取公司秘钥
	var company model.SysDept
	company, err = model.GetCompanyById(waybill.DeptId)
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return model.GetCompanyKeyErr
	}

	// 获取传感器信息
	deviceSensorList, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey(task.Sn, company.ColdKey)
	task.DeviceSensorList = deviceSensorList

	return nil
}

// GetPage 获取WaybillTask列表
func (e *WaybillTask) GetDataPage(c *dto.WaybillTaskGetDataPageReq) (list []nats_server.DeviceData_R, count int64, err error) {

	var waybill model.Waybill
	err = e.Orm.Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		err = errors.New("获取运单信息错误！")
		return
	}

	var task model.WaybillTask
	err = e.Orm.Where("id = ? and waybill_no = ?", c.TaskId, c.WaybillNo).First(&task).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		err = errors.New("获取运单信息错误！")
		return
	}

	if len(c.StartTime) > 0 {
		var st time.Time
		st, err = time.ParseInLocation("2006-01-02 15:04:05", c.StartTime, time.Local)
		if err != nil {
			err = errors.New("解析时间字符串出错！")
			return
		}
		if st.Before(time.Time(task.StartTime)) {
			c.StartTime = task.StartTime.String()
		}
	} else {
		c.StartTime = task.StartTime.String()
	}
	if len(c.EndTime) > 0 {
		var et time.Time
		et, err = time.ParseInLocation("2006-01-02 15:04:05", c.EndTime, time.Local)
		if err != nil {
			err = errors.New("解析时间字符串出错！")
			return
		}
		if et.After(time.Time(task.EndTime)) {
			c.EndTime = task.EndTime.String()
		}
	} else {
		c.EndTime = task.EndTime.String()
	}

	T_snid := ""
	for _, id := range c.T_ids {
		T_snid += fmt.Sprintf("%s,%d|", task.Sn, id)
	}
	list, count, err = nats_server.Cold_ReadDeviceDataListBy_T_snid(T_snid, c.StartTime, c.EndTime, c.Page, c.PageSize)
	return list, count, err
}
func (e *WaybillTask) GetNewestDataPage(c *dto.WaybillTaskGetNewestDataPageReq) (data nats_server.DeviceData_R, err error) {
	var waybill model.Waybill
	err = e.Orm.Model(&waybill).Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		err = errors.New("获取运单信息错误！")
		return
	}
	// 获取公司秘钥
	var company model.SysDept
	company, err = model.GetCompanyById(waybill.DeptId)
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		err = model.GetCompanyKeyErr
		return
	}

	var taskList []model.WaybillTask
	err = e.Orm.Where("waybill_no = ?", c.WaybillNo).Order("id desc").Find(&taskList).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		err = errors.New("获取运单信息任务失败！")
		return
	}
	if len(taskList) == 0 {
		err = errors.New("暂无温湿度记录信息！")
		return
	}
	var listAll []nats_server.DeviceData_R
	for _, task := range taskList {
		deviceSensorList, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey(task.Sn, company.ColdKey)
		if len(deviceSensorList) == 0 {
			continue
		}
		T_snid := fmt.Sprintf("%s,%d|", deviceSensorList[0].T_sn, deviceSensorList[0].T_id)
		if len(task.EndTime.String()) == 0 {
			task.EndTime = model2.Time(time.Now())
		}
		// 获取传感器信息
		list, _, _ := nats_server.Cold_ReadDeviceDataListBy_T_snid(T_snid, task.StartTime.String(), task.EndTime.String(), 0, 9999)
		if len(list) > 0 {
			listAll = append(listAll, list...)
			break
		}
	}

	if len(listAll) > 0 {
		data = listAll[0]
		return
	}
	err = errors.New("暂无温湿度记录信息！")
	return
}
func (e *WaybillTask) GetLocus(c *dto.WaybillGetLocusReq) ([]nats_server.DeviceData_R2, error) {
	var err error
	var data model.WaybillTask
	var waybill model.Waybill
	var taskList []model.WaybillTask
	locusList := make([]nats_server.DeviceData_R2, 0)

	err = e.Orm.Model(&waybill).Where("waybill_no = ? or order_no = ?", c.WaybillNo, c.WaybillNo).First(&waybill).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return locusList, errors.New("获取运单信息失败")
	}
	// 获取公司秘钥
	var company model.SysDept
	company, err = model.GetCompanyById(waybill.DeptId)
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return locusList, model.GetCompanyKeyErr
	}

	err = e.Orm.Model(&data).
		Where("waybill_no = ?", waybill.WaybillNo).
		Find(&taskList).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return locusList, errors.New("获取运单任务信息失败")
	}

	for i := 0; i < len(taskList); i++ {
		// 获取传感器信息
		deviceSensorList, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey(taskList[i].Sn, company.ColdKey)
		if len(deviceSensorList) > 0 {
			T_snid := fmt.Sprintf("%s,%d|", taskList[i].Sn, deviceSensorList[0].T_id)
			dataList, _, err := nats_server.Cold_ReadDeviceDataListBy_T_snidForLocus(T_snid, taskList[i].StartTime.String(), taskList[i].EndTime.String(), 0, 9999)
			if err != nil {
				e.Log.Errorf("nats 获取轨迹信息失败: %s", err)
				return locusList, errors.New("获取运单轨迹信息失败")
			}

			// 倒序
			sort.Slice(dataList, func(i, j int) bool {
				if dataList[i].T_time < dataList[j].T_time {
					return true
				}
				return false
			})
			locusList = append(locusList, dataList...)

		}

	}
	return locusList, nil
}
