package service

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

type IceLocker struct {
	service.Service
}

// GetPage 获取IceLocker列表
func (e *IceLocker) GetPage(c *dto.IceLockerGetPageReq, list *[]model.IceLocker, count *int64, p *actions.DataPermission) error {
	var err error
	var data model.IceLocker

	if c.PageSize == 9999 {
		err = e.Orm.Model(&data).
			Scopes(
				actions.Permission(data.TableName(), p),
			).
			Find(list).Limit(-1).Offset(-1).
			Count(count).Error
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			return global.GetFailedErr
		}
	} else {
		err = e.Orm.Model(&data).
			Scopes(
				cDto.MakeCondition(c.GetNeedSearch()),
				cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
				actions.Permission(data.TableName(), p),
			).
			Find(list).Limit(-1).Offset(-1).
			Count(count).Error

	}

	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.GetFailedErr
	}
	if c.ShowTemp {
		// 获取公司秘钥
		var company model.SysDept
		company, err = model.GetCompanyById(p.DeptId)
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			return model.GetCompanyKeyErr
		}
		for i := 0; i < len(*list); i++ {
			deviceData, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey((*list)[i].Sn, company.ColdKey)
			if len(deviceData) > 0 {
				(*list)[i].DeviceData = deviceData[0].T_DeviceSensorData
			}
		}
	}

	return nil
}

// Get 获取IceLocker对象
func (e *IceLocker) Get(d *dto.IceLockerGetReq, iceLockerModel *model.IceLocker, p *actions.DataPermission) error {
	err := e.Orm.
		Scopes(actions.Permission(iceLockerModel.TableName(), p)).
		First(iceLockerModel, d.GetId()).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return global.GetNotFoundOrNoPermissionErr
		}
		return global.GetFailedErr
	}

	return nil
}

// Insert 创建IceLocker对象
func (e *IceLocker) Insert(c *dto.IceLockerInsertReq, p *actions.DataPermission) error {
	var err error
	var data model.IceLocker

	tx := e.Orm.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()

	var k int64
	err = tx.Model(&data).Where("name = ? and dept_id = ?", c.Name, c.DeptId).Count(&k).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.CreateFailedErr
	}
	if k > 0 {
		err = errors.New("冷冻柜名称已存在！")
		e.Log.Errorf("db error: %s", err)
		return err
	}

	//var device nats_server.Device
	//var company model.SysDept
	//device, err = nats_server.Cold_ReadDeviceByT_sn(c.Sn)
	//if err != nil {
	//	err = errors.New("获取SN信息失败，请检查SN是否正确！")
	//	e.Log.Errorf("db error: %s", err)
	//	return err
	//}
	//company, err = model.GetCompanyById(p.DeptId)
	//if err != nil {
	//	e.Log.Errorf("db error: %s", err)
	//	return err
	//}
	//if device.T_pid != company.Id {
	//	err = errors.New("获取SN信息失败，请检查SN是否正确！")
	//	e.Log.Errorf("获取SN信息失败，device.T_pid != company.Id")
	//	return err
	//}

	// 添加冷冻柜
	c.Generate(&data)
	err = tx.Create(&data).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.CreateFailedErr
	}
	c.Id = data.Id

	return nil

}

// Update 修改IceLocker对象
func (e *IceLocker) Update(c *dto.IceLockerUpdateReq, p *actions.DataPermission) error {
	var err error

	tx := e.Orm.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()

	var iceLockerModel = model.IceLocker{}
	// 查询冷冻柜是否存在
	err = e.Orm.Scopes(actions.Permission(iceLockerModel.TableName(), p)).
		First(&iceLockerModel, c.GetId()).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return global.UpdateNotFoundOrNoPermissionErr
		}
		return global.UpdateFailedErr
	}

	if iceLockerModel.Name != c.Name {
		var k int64
		var data = model.IceLocker{}
		err = tx.Model(&data).Where("name = ? and dept_id = ?", c.Name, iceLockerModel.DeptId).Count(&k).Error
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			return global.CreateFailedErr
		}
		if k > 0 {
			err = errors.New("冷冻柜名称已存在！")
			e.Log.Errorf("db error: %s", err)
			return err
		}
	}

	if iceLockerModel.Sn != c.Sn && len(c.Sn) > 0 {
		var k int64
		var data = model.IceLocker{}
		err = tx.Model(&data).Where("sn = ?", c.Sn).Count(&k).Error
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			return global.CreateFailedErr
		}
		if k > 0 {
			err = errors.New("该Sn已绑定！")
			e.Log.Errorf("db error: %s", err)
			return err
		}

		//var device nats_server.Device
		//var company model.SysDept
		//device, err = nats_server.Cold_ReadDeviceByT_sn(c.Sn)
		//if err != nil {
		//	err = errors.New("获取SN信息失败，请检查SN是否正确！")
		//	e.Log.Errorf("db error: %s", err)
		//	return err
		//}
		//company, err = model.GetCompanyById(p.DeptId)
		//if err != nil {
		//	e.Log.Errorf("db error: %s", err)
		//	return err
		//}
		//if device.T_pid != company.Id {
		//	err = errors.New("获取SN信息失败，请检查SN是否正确！")
		//	e.Log.Errorf("获取SN信息失败，device.T_pid != company.Id")
		//	return err
		//}

		iceLockerModel.HistorySn = append(iceLockerModel.HistorySn, c.Sn)
	}

	c.Generate(&iceLockerModel)
	err = tx.Save(&iceLockerModel).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.UpdateFailedErr
	}

	c.Id = iceLockerModel.Id
	return nil
}

// Remove 删除IceLocker
func (e *IceLocker) Remove(c *dto.IceLockerDeleteReq, p *actions.DataPermission) error {
	var err error

	tx := e.Orm.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()

	var iceRaftModel model.IceRaft
	var count int64
	err = e.Orm.Model(&iceRaftModel).
		Scopes(
			actions.Permission(iceRaftModel.TableName(), p),
			IceRaftNameRecordStatusScopes(model.IceRaftRecordStatusWaitUse),
			IceRaftNameRecordIceLockerIdScopes(c.Id),
		).
		Where("ice_raft.status = '2'").
		Joins("left join ice_raft_record on ice_raft.ice_raft_record_id = ice_raft_record.id").
		Count(&count).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.DeleteFailedErr
	}
	if count > 0 {
		err = errors.New("该冷冻柜下有冰排待使用中，无法删除！")
		return err
	}

	var iceLockerModel model.IceLocker

	// 查询冷冻柜是否存在
	err = e.Orm.Scopes(actions.Permission(iceLockerModel.TableName(), p)).
		First(&iceLockerModel, c.GetId()).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return global.DeleteNotFoundOrNoPermissionErr
		}
		return global.DeleteFailedErr
	}

	db := tx.Delete(&iceLockerModel)

	if err = db.Error; err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.DeleteFailedErr
	}
	if db.RowsAffected == 0 {
		return global.DeleteNotFoundOrNoPermissionErr
	}

	return nil
}

func (e *IceLocker) BatchInsert(c *dto.IceLockerBatchInsertReq) error {
	var err error

	tx := e.Orm.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()

	for _, iceLocker := range c.List {
		var data model.IceLocker

		var k int64
		err = tx.Model(&data).Where("sn = ?", iceLocker.Sn).Count(&k).Error
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			return global.CreateFailedErr
		}
		if k > 0 {
			//err = errors.New("该Sn已绑定！")
			continue
		}

		// 添加冷冻柜
		iceLocker.CreateBy = c.CreateBy
		iceLocker.DeptId = c.DeptId
		iceLocker.Status = c.Status
		iceLocker.Generate(&data)
		data.HistorySn = []string{data.Sn}
		err = tx.Create(&data).Error
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			return global.CreateFailedErr
		}
	}

	return nil

}
func (e *IceLocker) GetIceLocker(c *dto.GetIceLockerReq, list *[]model.IceRaft, p *actions.DataPermission, count *int64) error {
	var err error
	tx := e.Orm.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	//查询冷冻柜是否存在
	var icerecord model.IceRaft

	err = e.Orm.Model(&icerecord).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(icerecord.TableName(), p),
			IceRaftNameRecordIceLockerScopes(c.Status),
			IceRaftNameRecordIceLockerIdScopes(c.Locker),
		).
		//Where("ice_raft.status = '2'").
		Joins("left join ice_raft_record on ice_raft.ice_raft_record_id = ice_raft_record.id").
		Preload("IceRaftRecord.IceLocker").
		Preload("IceRaftRecord.CoolerBox").
		Preload("IceRaftRecord").
		//Order("FIELD(ice_raft_record.status,'2','','1','3','4')").
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return global.GetFailedErr
		}
		return global.GetFailedErr
	}
	for i := range *list {
		(*list)[i].IceRaftRecord.ForColdTimeActual = math.Floor((*list)[i].IceRaftRecord.ForColdTimeActual)
	}

	return nil
}
