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/lib"
	model2 "cold-delivery/common/model"
	"database/sql"
	"errors"
	"fmt"
	"math"
	"sort"
	"strings"
	"time"

	"gogs.baozhida.cn/zoie/OAuth-core/service"
	"gorm.io/gorm"
)

type IceRaft struct {
	service.Service
}

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

	if c.PageSize == 9999 {
		err = e.Orm.Model(&data).
			Scopes(
				actions.Permission(data.TableName(), p),
			).Order("ice_raft.sort asc").
			Find(list).Limit(-1).Offset(-1).
			Count(count).Error
	} else {
		err = e.Orm.Model(&data).
			Scopes(
				cDto.MakeCondition(c.GetNeedSearch()),
				cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
				actions.Permission(data.TableName(), p),
			).Order("ice_raft.sort asc").
			Find(list).Limit(-1).Offset(-1).
			Count(count).Error
	}
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.GetFailedErr
	}
	return nil
}
func IceRaftNameRecordStatusScopes(status string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if len(status) == 0 {
			return db
		}
		if status == "0" {
			return db.Where("ice_raft_record.status is null")

		}
		return db.Where("ice_raft_record.status = ?", status)
	}
}
func IceRaftNameRecordIceLockerScopes(status string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if len(status) == 0 {
			return db.Where("ice_raft_record.status = 1 or ice_raft_record.status =2 or ice_raft_record.status =5 or ice_raft_record.status =6")
		}
		if status == "0" {
			return db.Where("ice_raft_record.status is null")

		}
		return db.Where("ice_raft_record.status = ?", status)
	}
}
func IceRaftNameRecordIceLockerIdScopes(iceLockerId int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if iceLockerId == 0 {
			return db
		}
		return db.Where("ice_raft_record.ice_locker_id = ? and ice_raft_record.cooler_box_id = 0", iceLockerId)
	}
}

func IceRaftNameRecordCoolerBoxIdScopes(coolerBoxId int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if coolerBoxId == 0 {
			return db
		}
		return db.Where("ice_raft_record.cooler_box_id = ?", coolerBoxId)
	}
}
func IceRaftStartTimeAndEndTimeScopes(startTime, endtime string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if len(startTime) == 0 {
			return db
		}
		return db.Where("ice_raft_record.ice_use_time >= ?", startTime).Where("ice_raft_record.ice_use_time <= ?", endtime)
	}
}
func CollerStartTimeAndEndTimeScopes(startTime, endtime string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if len(startTime) == 0 {
			return db
		}
		return db.Where("cooler_box_record.cooler_box_star_time >= ?", startTime).Where("cooler_box_record.cooler_box_star_time <= ?", endtime)
	}
}

func (e *IceRaft) GetRecordPage(c *dto.IceRaftGetNewestRecordPageReq, list *[]model.IceRaft, count *int64, p *actions.DataPermission) error {
	var err error
	var data model.IceRaft

	if c.PageSize == 9999 {
		err = e.Orm.Model(&data).
			Scopes(
				actions.Permission(data.TableName(), p),
			).
			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
	} else {
		err = e.Orm.Model(&data).
			Scopes(
				cDto.MakeCondition(c.GetNeedSearch()),
				cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
				actions.Permission(data.TableName(), p),
				IceRaftNameRecordStatusScopes(c.Status),
				IceRaftNameRecordIceLockerIdScopes(c.IceLockerId),
				IceRaftNameRecordCoolerBoxIdScopes(c.CoolerBoxId),
			).
			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
	}
	//for i, _ := range *list {
	//	if (*list)[i].IceRaftRecord.IsSuitableForCold == 1 && len((*list)[i].IceRaftRecord.StartIceColdTime.String()) != 0 {
	//		start, _ := time.Parse("2006-01-02 15:04:05", (*list)[i].IceRaftRecord.StartIceColdTime.String())
	//		end, _ := time.Parse("2006-01-02 15:04:05", (*list)[i].IceRaftRecord.EndForColdTime.String())
	//		sub := end.Sub(start)
	//		hours := sub.Hours()
	//		minutes := int(sub.Minutes()) % 60
	//		sprintf := fmt.Sprintf("%vh%dm\n", hours, minutes)
	//		(*list)[i].IceRaftRecord.CoolingTime = sprintf
	//	}
	//}
	for i := range *list {
		(*list)[i].IceRaftRecord.ForColdTimeActual = math.Floor((*list)[i].IceRaftRecord.ForColdTimeActual)
	}
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.GetFailedErr
	}
	return nil
}

// Get 获取IceRaft对象
func (e *IceRaft) Get(d *dto.IceRaftGetReq, iceRaftModel *model.IceRaft, p *actions.DataPermission) error {
	err := e.Orm.
		Scopes(actions.Permission(iceRaftModel.TableName(), p)).
		First(iceRaftModel, 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
}
func (e *IceRaft) GetByCode(d *dto.IceRaftGetByCodeReq, iceRaftModel *model.IceRaft, p *actions.DataPermission) error {
	err := e.Orm.
		Scopes(actions.Permission(iceRaftModel.TableName(), p)).
		Where("code = ?", d.Code).
		First(iceRaftModel).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New(fmt.Sprintf("冰排编号【%s】不存在！", d.Code))
		}
		return global.GetFailedErr
	}

	return nil
}

// Insert 创建IceRaft对象
func (e *IceRaft) Insert(c *dto.IceRaftInsertReq) error {
	var err error
	var data model.IceRaft

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

	for _, code := range c.CodeList {
		var k int64
		err = tx.Model(&data).Where("code = ? and dept_id = ?", code, c.DeptId).Count(&k).Error
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			return global.CreateFailedErr
		}
		// 冰排编号已存在
		if k > 0 {
			err = errors.New("该编号已存在！")
			return err
		}

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

	return nil

}

// Update 修改IceRaft对象
func (e *IceRaft) Update(c *dto.IceRaftUpdateReq, 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{}
	// 查询冰排是否存在
	err = e.Orm.Scopes(actions.Permission(iceRaftModel.TableName(), p)).
		First(&iceRaftModel, 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 iceRaftModel.Code != c.Code {
		var k int64
		var data = model.IceRaft{}
		err = tx.Model(&data).Where("code = ? and dept_id = ?", c.Code, iceRaftModel.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
		}
	}

	c.Generate(&iceRaftModel)
	err = tx.Save(&iceRaftModel).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.UpdateFailedErr
	}
	// 查询冰排记录是否存在
	var iceRaftRecordModel model.IceRaftRecord
	var count int64
	e.Orm.Table(iceRaftRecordModel.TableName()).Where("ice_raft_id = ?", c.Id).Count(&count)
	if count > 0 {
		iceRaftRecordModel.Id = iceRaftModel.IceRaftRecordId
		iceRaftRecordModel.FreezeClaim = iceRaftModel.FreezeClaim
		iceRaftRecordModel.Label = iceRaftModel.Label
		err = tx.Updates(&iceRaftRecordModel).Error
		if err != nil {
			e.Log.Errorf("db error: %s  该冰排未使用", err)
			return errors.New("修改冰排记录失败")
		}
	}
	c.Id = iceRaftModel.Id
	return nil
}

// Remove 删除IceRaft
func (e *IceRaft) Remove(c *dto.IceRaftDeleteReq, 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

	// 查询冰排是否存在
	err = e.Orm.Scopes(actions.Permission(iceRaftModel.TableName(), p)).
		First(&iceRaftModel, 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(&iceRaftModel)

	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 *IceRaft) InStorage(c *dto.IceRaftInStorageReq, 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.IceLockerId).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return errors.New("获取冷冻柜信息失败")
	}
	if iceLockerModel.Status != model.IceLockerStatusNormal {
		err = errors.New("冷冻柜状态异常")
		return err
	}

	for _, code := range c.Code {
		// 查询冰排是否存在
		var iceRaftModel model.IceRaft
		err = e.Orm.Scopes(actions.Permission(iceRaftModel.TableName(), p)).
			Where("code = ?", code).
			Preload("IceRaftRecord").
			First(&iceRaftModel).Error
		if err != nil {
			e.Log.Errorf("获取冰排信息失败 %s", err)
			return errors.New(fmt.Sprintf("获取冰排【%s】信息失败", code))
		}

		if iceRaftModel.Status != model.IceRaftStatusNormal {
			err = errors.New(fmt.Sprintf("冰排【%s】状态异常", code))
			return err
		}

		if iceRaftModel.IceRaftRecord.Status == model.IceRaftRecordStatusFreezing || iceRaftModel.IceRaftRecord.Status == model.IceRaftRecordStatusWaitUse {
			err = errors.New(fmt.Sprintf("冰排【%s】状态为%s，入库失败！", code, model.GetIceRaftRecordStatus(iceRaftModel.IceRaftRecord.Status)))
			return err
		}
		if iceRaftModel.IceRaftRecord.Status == model.IceRaftRecordReleasedInTheCold || iceRaftModel.IceRaftRecord.Status == model.IceRaftRecordReleasedInTheColdEnd {
			err = tx.Model(&model.IceRaftRecord{}).Where("ice_raft_id = ?", iceRaftModel.Id).
				Where("status = ?", model.IceRaftRecordReleasedInTheCold).
				Or("status = ?", model.IceRaftRecordReleasedInTheColdEnd).Updates(map[string]interface{}{
				"status":           model.IceRaftRecordStatusFreezing,
				"out_storage_time": sql.NullTime{Valid: false},
				"in_storage_time":  model2.Time(time.Now()),
				"freeze_duration":  0,
			}).Error
			if err != nil {
				e.Log.Errorf("db 添加冰排记录失败: %s", err)
				return errors.New("添加冰排记录失败")
			}
		} else {
			// 更新冰排记录状态 使用中 -> 已完成
			err = tx.Model(&model.IceRaftRecord{}).
				Where("ice_raft_id = ? and status = ?", iceRaftModel.Id, model.IceRaftRecordStatusUsing).
				Updates(map[string]interface{}{
					"status":      model.IceRaftRecordStatusFinish,
					"return_date": model2.Time(time.Now()),
				}).Error

			// 添加冰排记录
			var iceRaftRecordModel = model.IceRaftRecord{
				IceLockerId:   iceLockerModel.Id,
				IceRaftId:     iceRaftModel.Id,
				Status:        model.IceRaftRecordStatusFreezing,
				Label:         iceRaftModel.Label,
				Code:          code,
				InStorageTime: model2.Time(time.Now()),
				Sort:          iceRaftModel.Sort,
				ForColdTime:   iceRaftModel.ForColdTime,
				DeptBy: model2.DeptBy{
					DeptId: p.DeptId,
				},
			}
			iceRaftRecordModel.FreezeClaim = append(iceRaftRecordModel.FreezeClaim, iceRaftModel.FreezeClaim...)
			err = tx.Create(&iceRaftRecordModel).Error
			if err != nil {
				e.Log.Errorf("db error: %s", err)
				return errors.New("添加冰排记录失败")
			}
			// 更新冰排使用记录
			err = tx.Model(&iceRaftModel).
				Where("id = ?", iceRaftModel.Id).
				Updates(map[string]interface{}{
					"ice_raft_record_id": iceRaftRecordModel.Id,
				}).Error
			if err != nil {
				e.Log.Errorf("db error: %s", err)
				return errors.New("关联冰排记录失败")
			}
		}
	}
	return nil
}
func (e *IceRaft) OutStorage(c *dto.IceRaftOutStorageReq, p *actions.DataPermission) error {
	var err error

	tx := e.Orm.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	// 查询保温箱信息
	var coolerBoxModel model.CoolerBox
	err = e.Orm.Scopes(actions.Permission(coolerBoxModel.TableName(), p)).
		First(&coolerBoxModel, c.CoolerBoxId).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return errors.New("获取保温箱信息失败")
	}
	if coolerBoxModel.Status != model.CoolerBoxStatusNormal {
		err = errors.New("保温箱状态异常")
		return err
	}
	if len(coolerBoxModel.BindIceRaftId) != 0 {
		is := lib.StrListEqual(coolerBoxModel.BindIceRaftId, c.Code)
		if !is {
			err = errors.New("保温箱已绑定冰排，禁止出库")
			return err
		}
	}
	falseIce := make([]string, 0)
	err, sysUser := GetUserProfile(e.Orm, p.UserId)
	if err != nil {
		err = errors.New("获取用户信息失败")
		return err
	}
	for _, code := range c.Code {
		// 查询冰排是否存在
		var iceRaftModel model.IceRaft
		err = e.Orm.Scopes(actions.Permission(iceRaftModel.TableName(), p)).
			Where("code = ?", code).
			Preload("IceRaftRecord").
			First(&iceRaftModel).Error
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			return errors.New("获取冰排信息失败，请检查该冰排是否存在")
		}

		if iceRaftModel.Status != model.IceRaftStatusNormal {
			err = errors.New(fmt.Sprintf("冰排【%s】状态异常", code))
			return err
		}

		var iceRaftSuccess []string
		var iceRaftErr []string
		if len(iceRaftModel.BindCoolerBox) != 0 {
			for _, v := range iceRaftModel.BindCoolerBox {
				if v == coolerBoxModel.Id {
					iceRaftSuccess = append(iceRaftSuccess, code)
				} else {
					iceRaftErr = append(iceRaftErr, fmt.Sprintf("冰排【%s】已绑定保温箱【%v】，禁止出库！", code, iceRaftModel.CoolerBoxName))
				}
			}
		}
		if len(iceRaftErr) != 0 && len(iceRaftSuccess) == 0 {
			err = errors.New(strings.Join(iceRaftErr, " "))
			return err
		}
		// 获取冰排记录
		var iceRaftRecordModel model.IceRaftRecord
		err = e.Orm.Scopes(actions.Permission(iceRaftRecordModel.TableName(), p)).
			Where("ice_raft_id = ?", iceRaftModel.Id).
			First(&iceRaftRecordModel, iceRaftModel.IceRaftRecordId).Error
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			return errors.New("获取冰排记录失败，请确认冰排是否入库！")
		}
		if len(iceRaftRecordModel.OutStorageTime.String()) > 0 && iceRaftRecordModel.Status == model.IceRaftRecordStatusUsing {
			err = errors.New(fmt.Sprintf("冰排【%s】已出库，禁止出库！", code))
			return err
		}

		inTime := iceRaftRecordModel.InStorageTime.Local()
		sort.Slice(iceRaftRecordModel.FreezeClaim, func(i, j int) bool {
			return iceRaftRecordModel.FreezeClaim[i] < iceRaftRecordModel.FreezeClaim[j]
		})

		if inTime.Add(time.Duration(iceRaftRecordModel.FreezeClaim[0] * float64(time.Hour))).After(time.Now()) {
			str := fmt.Sprintf("冰排【%s】未达到冷冻时长【%v】,禁止出库", code, iceRaftRecordModel.FreezeClaim[0])
			err = errors.New(str)
			return err
		}
		//判断冰排释冷要求是否为0,如果不为零，则判断是否达到释冷时长，否则不允许出库
		if sysUser.Dept.IsIceReleaseCold && iceRaftModel.ForColdTime != 0 {
			if len(iceRaftRecordModel.StartIceColdTime.String()) != 0 {
				start := iceRaftRecordModel.StartIceColdTime.Local()
				if start.Add(time.Duration(iceRaftModel.ForColdTime * float64(time.Hour))).After(time.Now()) {
					err = errors.New(fmt.Sprintf("冰排【%s】未达到释冷时长【%v】小时,禁止出库", code, iceRaftModel.ForColdTime))
					return err
				}
			} else {
				err = errors.New(fmt.Sprintf("冰排【%s】还未开始释冷,请先释冷再出库！！！", code))
				return err
			}
		}

		iceRaftRecordModel.Status = model.IceRaftRecordStatusUsing
		iceRaftRecordModel.CoolerBoxId = coolerBoxModel.Id
		iceRaftRecordModel.OutStorageTime = model2.Time(time.Now())
		iceRaftRecordModel.IceUseUsers = sysUser.NickName
		iceRaftRecordModel.IceUseTime = model2.Time(time.Now())
		iceRaftRecordModel.IceRaftId = iceRaftModel.Id
		if sysUser.Dept.IsIceReleaseCold {
			iceRaftRecordModel.IsSuitableForCold = 1
			iceRaftRecordModel.SuitableForCold = iceRaftModel.SuitableForCold
			iceRaftRecordModel.EndForColdTime = model2.Time(time.Now())
		}
		err = tx.Save(&iceRaftRecordModel).Error
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			return errors.New("保存冰排记录失败")
		}
	}
	m := make(map[string]bool)
	if len(coolerBoxModel.BindIceRaftId) != 0 {
		for _, v := range coolerBoxModel.BindIceRaftId {
			m[v] = true
		}
		for _, v := range c.Code {
			if !m[v] {
				falseIce = append(falseIce, v)
			}
		}
	}
	if len(falseIce) > 0 {
		err = errors.New(fmt.Sprintf("冰排%s未绑定该保温箱，禁止出库！", falseIce))
		return err
	}
	//添加保温箱记录
	var cooler model.CoolerBoxRecord
	cooler.CoolerBoxId = coolerBoxModel.Id
	cooler.CoolerUserTime = model2.Time(time.Now())
	cooler.Sn = coolerBoxModel.Sn
	cooler.Status = "1" //保温箱使用状态变为使用中
	cooler.DeptId = p.DeptId
	cooler.Name = coolerBoxModel.Name
	cooler.HistoryCode = append(cooler.HistoryCode, c.Code...)
	cooler.CoolerUseUsers = sysUser.NickName
	cooler.ForColdCoolerTime = coolerBoxModel.ForColdCoolerTime
	//查询是否有正在使用中的保温箱记录
	var count int64
	var coolerBoxRecordModel model.CoolerBoxRecord
	err = tx.Model(&model.CoolerBoxRecord{}).Where("cooler_box_id = ?", coolerBoxModel.Id).Where("status = ?", "1").First(&coolerBoxRecordModel).Count(&count).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			err = e.Orm.Create(&cooler).Error
			if err != nil {
				e.Log.Errorf("db 创建保温箱记录失败: %s", err)
				return errors.New("创建保温箱记录失败")
			}
		} else {
			e.Log.Errorf("获取保温箱信息失败: %s", err)
			return errors.New("获取保温箱信息失败")
		}
	}
	if sysUser.Dept.IsCoolerReleaseCold && coolerBoxModel.ForColdCoolerTime != 0 {
		start := coolerBoxRecordModel.CoolerBoxStarTime.Local()
		if start.Add(time.Duration(coolerBoxModel.ForColdCoolerTime * float64(time.Hour))).After(time.Now()) {
			err = errors.New(fmt.Sprintf("保温箱未达到预冷时长【%v】小时,禁止装箱", coolerBoxModel.ForColdCoolerTime))
			return err
		}
	}
	//更新保温箱状态为使用中  2
	err = e.Orm.Table(model.CoolerBox{}.TableName()).Where("id =?", coolerBoxModel.Id).Update("use_status", "2").Error
	if err != nil {
		e.Log.Errorf("更新保温箱状态失败: %s", err)
		return errors.New("更新保温箱状态失败")
	}
	//如果有正在使用中的保温箱记录，就更新
	if count > 0 {
		err = tx.Where("id = ?", coolerBoxRecordModel.Id).Updates(&cooler).Error
		if err != nil {
			e.Log.Errorf("db 更新保温箱记录失败: %s", err)
			return errors.New("更新保温箱记录失败")
		}
	}
	return nil
}

// BindCookerBox 冰排绑定保温箱
func (e *IceRaft) BindCookerBox(c *dto.BindCoolerBox, p *actions.DataPermission) error {
	var err error

	tx := e.Orm.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	// 查询保温箱信息
	for _, v := range c.CoolerBoxId {
		var coolerBoxModel model.CoolerBox
		err = e.Orm.Scopes(actions.Permission(coolerBoxModel.TableName(), p)).Where("id =?", v).
			First(&coolerBoxModel).Error
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			return errors.New("获取保温箱信息失败")
		}
		if coolerBoxModel.Status != model.CoolerBoxStatusNormal {
			err = errors.New("保温箱状态不可用")
			return err
		}
		for _, code := range c.Code {
			// 查询冰排是否存在
			var iceRaftModel model.IceRaft
			err = e.Orm.Scopes(actions.Permission(iceRaftModel.TableName(), p)).
				Where("code = ?", code).
				Preload("IceRaftRecord").
				First(&iceRaftModel).Error
			if err != nil {
				e.Log.Errorf("获取冰排信息失败: %s", err)
				return errors.New("获取冰排信息失败")
			}

			if iceRaftModel.Status != model.IceRaftStatusNormal {
				err = errors.New(fmt.Sprintf("冰排【%s】状态异常", code))
				return err
			}
			iceRaftModel.CoolerBoxName = append(iceRaftModel.CoolerBoxName, coolerBoxModel.Name)
			iceRaftModel.BindCoolerBox = append(iceRaftModel.BindCoolerBox, coolerBoxModel.Id)
			iceRaftModel.CoolerBoxName = cDto.UniqueSlice(iceRaftModel.CoolerBoxName)
			iceRaftModel.BindCoolerBox = cDto.UniqueSliceInt(iceRaftModel.BindCoolerBox)

			err = e.Orm.Model(&iceRaftModel).Where("id =?", iceRaftModel.Id).Update("bind_cooler_box", iceRaftModel.BindCoolerBox).Update("cooler_box_name", iceRaftModel.CoolerBoxName).Error
			if err != nil {
				e.Log.Errorf("绑定保温箱失败: %s", err)
				return errors.New("绑定保温箱失败")
			}
			coolerBoxModel.BindIceRaftId = append(coolerBoxModel.BindIceRaftId, code)
			coolerBoxModel.BindIceRaftId = cDto.UniqueSlice(coolerBoxModel.BindIceRaftId)
			err = e.Orm.Model(&coolerBoxModel).Where("id =?", coolerBoxModel.Id).Update("bind_ice_raft_id", coolerBoxModel.BindIceRaftId).Error
			if err != nil {
				e.Log.Errorf("绑定保温箱失败: %s", err)
				return errors.New("绑定保温箱失败")
			}
		}
	}
	return nil
}

// GetCoolerBoxBindCieRaft 获取保温箱可绑定冰排
func (e *IceRaft) GetCoolerBoxBindCieRaft(c *dto.GetCoolerBoxByIceRaft, p *actions.DataPermission, list *[]string) error {
	var err error

	tx := e.Orm.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	// 查询保温箱信息
	var coolerBoxModel model.CoolerBox
	err = e.Orm.Scopes(actions.Permission(coolerBoxModel.TableName(), p)).Where("id =?", c.Id).
		First(&coolerBoxModel).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return errors.New("获取保温箱信息失败")
	}
	if coolerBoxModel.Status != model.CoolerBoxStatusNormal {
		err = errors.New("保温箱状态不可用")
		return err
	}
	if len(coolerBoxModel.BindIceRaftId) > 0 {
		for _, code := range coolerBoxModel.BindIceRaftId {
			// 查询冰排是否存在
			var iceRaftModel model.IceRaftRecord
			err = e.Orm.Scopes(actions.Permission(iceRaftModel.TableName(), p)).
				Where("code = ?", code).Where("status = ?", model.IceRaftRecordStatusWaitUse).Or("status = ?", model.IceRaftRecordReleasedInTheColdEnd).
				First(&iceRaftModel).Error
			if err != nil {
				if errors.Is(gorm.ErrRecordNotFound, err) {
					return nil
				}
				e.Log.Errorf("获取冰排信息失败: %s", err)
				return errors.New("获取冰排信息失败")
			}
			*list = append(*list, iceRaftModel.Code)
		}
	} else {
		var iceRaftModel []model.IceRaftRecord
		err = e.Orm.Scopes(actions.Permission(model.IceRaftRecord{}.TableName(), p)).
			Where("status = ?", model.IceRaftRecordStatusWaitUse).Or("status = ?", model.IceRaftRecordReleasedInTheColdEnd).Find(&iceRaftModel).Error
		if err != nil {
			e.Log.Errorf("获取冰排信息失败: %s", err)
			return errors.New("获取冰排信息失败")
		}
		for _, v := range iceRaftModel {
			var iceRaft model.IceRaft
			err = e.Orm.Scopes(actions.Permission(model.IceRaft{}.TableName(), p)).
				Where("id = ?", v.Id).First(&iceRaft).Error
			if len(iceRaft.BindCoolerBox) == 0 {
				*list = append(*list, v.Code)
			}
		}
	}
	return nil
}
func (e *IceRaft) GetCoolerIceRaft(p *actions.DataPermission, list *[]model.IceRaft) error {
	var err error

	tx := e.Orm.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	// 查询保温箱信息
	var data model.IceRaft
	err = e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p)).
		Where("ice_raft.status = '2'").
		Joins("left join ice_raft_record on ice_raft.ice_raft_record_id = ice_raft_record.id").
		Where("ice_raft_record.`status` IS NULL").
		Preload("IceRaftRecord.IceLocker").
		Preload("IceRaftRecord.CoolerBox").
		Preload("IceRaftRecord").
		Find(list).Limit(-1).Offset(-1).Error
	return nil
}
func (e *IceRaft) UnBindCookerBox(c *dto.UnBindCoolerBox, 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
	err = e.Orm.Scopes(actions.Permission(iceRaftModel.TableName(), p)).
		Where("code = ?", c.Code).
		Preload("IceRaftRecord").
		First(&iceRaftModel).Error
	if err != nil {
		e.Log.Errorf("获取冰排信息失败: %s", err)
		return errors.New("获取冰排信息失败")
	}
	for _, v := range iceRaftModel.BindCoolerBox {
		var coolerBoxModel model.CoolerBox
		err = e.Orm.Scopes(actions.Permission(coolerBoxModel.TableName(), p)).Where("id =?", v).First(&coolerBoxModel).Error
		if err != nil {
			e.Log.Errorf("获取保温箱信息失败: %s", err)
			return errors.New("获取保温箱信息失败")
		}
		coolerBoxModel.BindIceRaftId = cDto.RemoveValue(coolerBoxModel.BindIceRaftId, c.Code)
		err = e.Orm.Model(&coolerBoxModel).Where("id =?", coolerBoxModel.Id).Update("bind_ice_raft_id", coolerBoxModel.BindIceRaftId).Error
		if err != nil {
			e.Log.Errorf("解绑保温箱失败: %s", err)
			return errors.New("解绑保温箱失败")
		}
	}
	iceRaftModel.CoolerBoxName = []string{}
	iceRaftModel.BindCoolerBox = []int{}
	for _, v := range c.CoolerBoxId {
		var coolerBoxModel model.CoolerBox
		err = e.Orm.Scopes(actions.Permission(coolerBoxModel.TableName(), p)).Where("id =?", v).First(&coolerBoxModel).Error
		if err != nil {
			e.Log.Errorf("获取保温箱信息失败: %s", err)
			return errors.New("获取保温箱信息失败")
		}
		iceRaftModel.CoolerBoxName = append(iceRaftModel.CoolerBoxName, coolerBoxModel.Name)
		iceRaftModel.BindCoolerBox = append(iceRaftModel.BindCoolerBox, coolerBoxModel.Id)

		coolerBoxModel.BindIceRaftId = append(coolerBoxModel.BindIceRaftId, c.Code)
		coolerBoxModel.BindIceRaftId = cDto.UniqueSlice(coolerBoxModel.BindIceRaftId)
		err = e.Orm.Model(&coolerBoxModel).Where("id =?", coolerBoxModel.Id).Update("bind_ice_raft_id", coolerBoxModel.BindIceRaftId).Error
		if err != nil {
			e.Log.Errorf("修改保温箱失败: %s", err)
			return errors.New("修改保温箱失败")
		}
	}
	err = e.Orm.Model(&iceRaftModel).Where("id =?", iceRaftModel.Id).Update("bind_cooler_box", iceRaftModel.BindCoolerBox).Update("cooler_box_name", iceRaftModel.CoolerBoxName).Error
	if err != nil {
		e.Log.Errorf("绑定保温箱失败: %s", err)
		return errors.New("绑定保温箱失败")
	}
	return nil
}

// IsOutStorage 判断冰排是否达到冷冻时长
func (e *IceRaft) IsOutStorage(c *dto.IceOutStorageReq, p *actions.DataPermission) (error, string) {
	var err error
	var str string
	msg := make([]string, 0)
	sussce := make([]string, 0)
	FreezeDuration := make([]float64, 0)
	// 获取冰排记录
	for _, v := range c.Code {
		var iceRaftRecordModel model.IceRaftRecord
		err = e.Orm.Scopes(actions.Permission(iceRaftRecordModel.TableName(), p)).
			Where("code = ?", v).
			Where("status = ?", model.IceRaftRecordStatusFreezing).Where("status != ?", 0).
			First(&iceRaftRecordModel).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				err = e.Orm.Scopes(actions.Permission(iceRaftRecordModel.TableName(), p)).
					Where("code = ?", v).
					Where("status != ?", 0).
					Where("status = ?", model.IceRaftRecordStatusWaitUse).
					Or("status=?", model.IceRaftRecordStatusUsing).
					Or("status=?", model.IceRaftRecordReleasedInTheColdEnd).
					First(&iceRaftRecordModel).Error
				if err != nil {
					e.Log.Errorf("db error: %s", err)
					return errors.New("当前冰排不存在" + v), ""
				} else {
					//记录达到冷冻要求的冰排
					msg = append(msg, v)
					continue
					//return errors.New("冰排已达到冷冻要求"), "冰排已达到冷冻要求"
				}
			} else {
				e.Log.Errorf("db error: %s", err)
				return errors.New("当前冰排不存在" + v), ""
			}
		}

		if len(iceRaftRecordModel.OutStorageTime.String()) > 0 {
			err = errors.New(fmt.Sprintf("冰排【%s】已出库，禁止出库！", v))
			return err, ""
		}
		//(001,002,003)未到达 xxx要求  已达到冷冻时长【%v】小时【%v】分钟
		inTime := iceRaftRecordModel.InStorageTime.Local()
		sort.Slice(iceRaftRecordModel.FreezeClaim, func(i, j int) bool {
			return iceRaftRecordModel.FreezeClaim[i] < iceRaftRecordModel.FreezeClaim[j]
		})
		for _, vs := range iceRaftRecordModel.FreezeClaim {
			if inTime.Add(time.Duration(vs * float64(time.Hour))).After(time.Now()) {
				hour := iceRaftRecordModel.FreezeDuration / 60
				minutes := int(iceRaftRecordModel.FreezeDuration) % 60
				str = fmt.Sprintf("冰排编号【%s】未达到冷冻时长【%v】小时，已达到冷冻时长【%v】小时【%v】分钟，是否继续出库", v, vs, hour, minutes)
				sussce = append(sussce, v)
				FreezeDuration = append(FreezeDuration, iceRaftRecordModel.FreezeDuration)
				break
			}
		}
	}
	if len(sussce) == 0 && len(msg) > 0 {
		return errors.New("冰排已达到冷冻要求"), "冰排已达到冷冻要求"
	} else if len(sussce) > 0 {
		sort.Slice(FreezeDuration, func(i, j int) bool {
			return FreezeDuration[i] < FreezeDuration[j]
		})
		str = fmt.Sprintf("冰排%v未达到冷冻要求，已达到冷冻时长【%v】小时【%v】分钟", sussce, FreezeDuration[0]/60, int(FreezeDuration[0])%60)
	}
	return nil, str
}

// GetPageByCoolerBoxId 查询保温箱关联的冰排
func (e *IceRaft) GetPageByCoolerBoxId(coolerBoxId int, list *[]string, p *actions.DataPermission) error {
	var data model.IceRaft
	err := e.Orm.Model(&data).
		Select("ice_raft.code").
		Scopes(
			actions.Permission(data.TableName(), p),
			IceRaftNameRecordStatusScopes(model.IceRaftRecordStatusUsing),
			IceRaftNameRecordCoolerBoxIdScopes(coolerBoxId),
		).
		Joins("left join ice_raft_record on ice_raft.ice_raft_record_id = ice_raft_record.id").
		Find(list).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.GetFailedErr
	}
	return nil
}

type IceRaftRecord struct {
	service.Service
}

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

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

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

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

	var iceRaftRecordModel = model.IceRaftRecord{}
	// 查询冰排是否存在
	err = e.Orm.Scopes(actions.Permission(iceRaftRecordModel.TableName(), p)).
		First(&iceRaftRecordModel, 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
	}

	iceRaftRecordModel.IceLockerId = c.IceLockerId
	iceRaftRecordModel.FreezeClaim = c.FreezeClaim
	if len(iceRaftRecordModel.OutStorageTime.String()) > 0 {
		iceRaftRecordModel.CoolerBoxId = c.CoolerBoxId
	}
	err = tx.Save(&iceRaftRecordModel).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.UpdateFailedErr
	}

	c.Id = iceRaftRecordModel.Id
	return nil
}

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

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

	var iceRaftRecordModel model.IceRaftRecord

	// 查询冰排是否存在
	err = e.Orm.Scopes(actions.Permission(iceRaftRecordModel.TableName(), p)).
		First(&iceRaftRecordModel, 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.Unscoped().Delete(&iceRaftRecordModel)

	if err = db.Error; err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.DeleteFailedErr
	}
	if db.RowsAffected == 0 {
		return global.DeleteNotFoundOrNoPermissionErr
	}
	// 更改冰排关联状态

	var iceRaftModel model.IceRaft
	var secondIceRaftRecordModel model.IceRaftRecord
	err = e.Orm.Scopes(actions.Permission(iceRaftModel.TableName(), p)).
		First(&iceRaftModel, iceRaftRecordModel.IceRaftId).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.DeleteFailedErr
	}
	err = e.Orm.Scopes(actions.Permission(secondIceRaftRecordModel.TableName(), p)).
		Where("ice_raft_id = ? and id != ?", iceRaftRecordModel.IceRaftId, iceRaftRecordModel.Id).
		First(&secondIceRaftRecordModel).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			iceRaftModel.IceRaftRecordId = 0
		}
	}
	iceRaftModel.IceRaftRecordId = secondIceRaftRecordModel.Id
	err = tx.Save(&iceRaftModel).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.UpdateFailedErr
	}
	return nil
}
func (e *IceRaftRecord) EndForCold(c *dto.IceRaftRecordEedReq, p *actions.DataPermission) error {
	var err error

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

	// 查询冰排是否存在
	for _, v := range c.Id {
		var iceRaftRecordModel model.IceRaftRecord
		err = e.Orm.Scopes(actions.Permission(iceRaftRecordModel.TableName(), p)).
			First(&iceRaftRecordModel, v).Error
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			if errors.Is(err, gorm.ErrRecordNotFound) {
				return global.UpdateNotFoundOrNoPermissionErr
			}
			return global.UpdateFailedErr
		}
		iceRaftRecordModel.IsSuitableForCold = 1 // 是否适冷
		iceRaftRecordModel.EndForColdTime = model2.Time(time.Now())
		iceRaftRecordModel.Id = v
		updates := tx.Where("id = ?", iceRaftRecordModel.Id).Updates(&iceRaftRecordModel)
		if err = updates.Error; err != nil {
			e.Log.Errorf("db error: %s", err)
			return global.UpdateFailedErr
		}
	}
	return nil
}

// StartForCold 冰排开始释冷
func (e *IceRaftRecord) StartForCold(c *dto.IceStartbleForColfTimReq, p *actions.DataPermission) error {
	var err error

	tx := e.Orm.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	var user model.SysUser
	first := e.Orm.Model(&model.SysUser{}).Where("id = ?", p.UserId).First(&user)
	if first.Error != nil {
		return global.GetFailedErr
	}
	//查询冰排是否存在
	for _, v := range c.Id {
		var iceRaftRecordModel model.IceRaftRecord
		var iceRaft model.IceRaft
		err = e.Orm.Scopes(actions.Permission(iceRaftRecordModel.TableName(), p)).
			First(&iceRaftRecordModel, v).Error
		if err != nil {
			e.Log.Errorf("db error: %s", err)
			if errors.Is(err, gorm.ErrRecordNotFound) {
				return errors.New("获取数据失败")
			}
			return errors.New("获取冰排失败")
		}
		err = e.Orm.Model(&iceRaft).Where("id = ?", iceRaftRecordModel.IceRaftId).First(&iceRaft).Error
		if err != nil {
			return global.GetFailedErr
		}
		// 获取冰排记录
		if iceRaftRecordModel.Status == model.IceRaftRecordReleasedInTheCold || iceRaftRecordModel.Status == model.IceRaftRecordReleasedInTheColdEnd {
			err = errors.New(fmt.Sprintf("冰排【%s】已释冷！", iceRaftRecordModel.Code))
			return err
		}
		if iceRaftRecordModel.Status != model.IceRaftRecordStatusWaitUse {
			err = errors.New(fmt.Sprintf("冰排【%s】状态为【%v】不可释冷！", iceRaftRecordModel.Code, model.GetIceRaftRecordStatus(iceRaftRecordModel.Status)))
			return err
		}

		inTime := iceRaftRecordModel.InStorageTime.Local()
		sort.Slice(iceRaftRecordModel.FreezeClaim, func(i, j int) bool {
			return iceRaftRecordModel.FreezeClaim[i] < iceRaftRecordModel.FreezeClaim[j]
		})
		if user.Dept.IsOutStorage {
			for _, vs := range iceRaftRecordModel.FreezeClaim {
				if inTime.Add(time.Hour * time.Duration(vs)).After(time.Now()) {
					str := fmt.Sprintf("冰排【%s】未达到冷冻时长【%v】,禁止出库", iceRaftRecordModel.Code, vs)
					err = errors.New(str)
					return err
				}
			}
		}
		iceRaftRecordModel.StartIceColdTime = model2.Time(time.Now())
		iceRaftRecordModel.Status = model.IceRaftRecordReleasedInTheCold //释冷中
		iceRaftRecordModel.IceColdUsers = user.NickName
		iceRaftRecordModel.IceColdAddress = iceRaft.IceColdAddress
		iceRaftRecordModel.SuitableForCold = iceRaft.SuitableForCold
		iceRaftRecordModel.OutStorageTime = model2.Time(time.Now()) //出库时间
		updates := tx.Where("id = ?", iceRaftRecordModel.Id).Updates(&iceRaftRecordModel)
		if err = updates.Error; err != nil {
			e.Log.Errorf("db error: %s", err)
			return global.UpdateFailedErr
		}
	}
	return nil
}

// IceRaftRecordRecording 获取冰排的历史记录
func (e *IceRaft) IceRaftRecordRecording(c *dto.IceRaftRecordRecording, list *[]model.IceRaftRecord, count *int64, p *actions.DataPermission) error {
	var err error
	var data model.IceRaftRecord
	if c.PageSize == 9999 {
		err = e.Orm.Model(&data).
			Scopes(
				cDto.MakeCondition(c.GetNeedSearch()),
				actions.Permission(data.TableName(), p),
				IceRaftStartTimeAndEndTimeScopes(c.StartTime, c.EndTime),
			).
			Where("status =?", model.IceRaftRecordStatusFinish).
			Preload("IceLocker").
			Preload("CoolerBox").
			Find(list).Limit(-1).Offset(-1).
			Count(count).Error
	} else {
		err = e.Orm.Model(&data).
			Scopes(
				cDto.MakeCondition(c.GetNeedSearch()),
				cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
				actions.Permission(data.TableName(), p),
				IceRaftStartTimeAndEndTimeScopes(c.StartTime, c.EndTime),
			).
			Where("status =?", model.IceRaftRecordStatusFinish).
			Preload("IceLocker").
			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 Ice model.IceRaftOmit
	for i := range *list {
		err = e.Orm.Model(&Ice).Where("id = ?", (*list)[i].IceRaftId).Find(&(*list)[i].IceRafts).Error
		if err != nil {
			return global.GetFailedErr
		}
	}
	return nil
}
