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"
	"errors"
	"gogs.baozhida.cn/zoie/OAuth-core/service"
	"gorm.io/gorm"
)

type Warehouse struct {
	service.Service
}

func WarehouseIsBindUserScopes(isBind bool) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		// 未发货
		if isBind {
			return db.Where("user_id > 0")
		}
		return db
	}
}

// GetPage 获取Warehouse列表
func (e *Warehouse) GetPage(c *dto.WarehouseGetPageReq, list *[]model.Warehouse, count *int64, p *actions.DataPermission) error {
	var err error
	var data model.Warehouse
	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
			WarehouseIsBindUserScopes(c.IsBind),
		).
		Joins("User").
		Where("name like ? or User.nick_name like ?", "%"+c.Name+"%", "%"+c.Name+"%").
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.GetFailedErr
	}
	return nil
}

// Get 获取Warehouse对象
func (e *Warehouse) Get(d *dto.WarehouseGetReq, warehouseModel *model.Warehouse, p *actions.DataPermission) error {
	err := e.Orm.
		Scopes(actions.Permission(warehouseModel.TableName(), p)).
		Preload("User").
		First(warehouseModel, 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 创建Warehouse对象
func (e *Warehouse) Insert(c *dto.WarehouseInsertReq) error {
	var err error
	var data model.Warehouse

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

	var i int64
	err = tx.Model(&data).Where("name = ? and dept_id = ?", c.Name, c.DeptId).Count(&i).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.CreateFailedErr
	}
	if i > 0 {
		err = errors.New("仓库名已存在！")
		e.Log.Errorf("db error: %s", err)
		return err
	}
	var j int64
	err = tx.Model(&data).Where("user_id = ?", c.UserId).Count(&j).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.CreateFailedErr
	}
	if j > 0 {
		err = errors.New("该用户已绑定其他仓库！")
		e.Log.Errorf("db error: %s", err)
		return err
	}

	var k int64
	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
	}

	// 添加仓库
	c.Generate(&data)
	data.HistorySn = []string{c.Sn}
	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 修改Warehouse对象
func (e *Warehouse) Update(c *dto.WarehouseUpdateReq, p *actions.DataPermission) error {
	var err error

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

	var warehouseModel = model.Warehouse{}
	// 查询仓库是否存在
	err = e.Orm.Scopes(actions.Permission(warehouseModel.TableName(), p)).
		First(&warehouseModel, 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 warehouseModel.Sn != c.Sn {
		var k int64
		var data = model.Warehouse{}
		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
		}
		warehouseModel.HistorySn = append(warehouseModel.HistorySn, c.Sn)
	}

	if warehouseModel.UserId != c.UserId {
		var k int64
		var data = model.Warehouse{}
		err = tx.Model(&data).Where("user_id = ?", c.UserId).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(&warehouseModel)
	err = tx.Save(&warehouseModel).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.UpdateFailedErr
	}

	c.Id = warehouseModel.Id
	return nil
}

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

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

	var warehouseModel model.Warehouse

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

	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
}

// GetUserList 获取绑定车辆的用户
func (e *Warehouse) GetUserList(c *dto.SysUserGetPageReq, p *actions.DataPermission, list *[]model.SysUserForBind, count *int64) error {
	var err error
	var userList []model.SysUserForBind

	var warehouseModel model.Warehouse
	var userModel model.SysUserForBind
	var userIds []int
	// 查询仓库是否存在
	err = e.Orm.Model(&warehouseModel).Select("user_id").Scopes(actions.Permission(warehouseModel.TableName(), p)).
		Find(&userIds).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.GetFailedErr
	}

	err = e.Orm.
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.UserPermission(userModel.TableName(), p),
		).
		Where("user_type = ? ", model.UserTypeSys).
		Find(&userList).Limit(-1).Offset(-1).
		Count(count).Error

	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return global.GetFailedErr
	}
	userIdMap := make(map[int]bool)
	for _, id := range userIds {
		userIdMap[id] = true
	}

	for i := 0; i < len(userList); i++ {
		if _, ok := userIdMap[userList[i].Id]; ok {
			userList[i].IsBind = true
		}
	}

	*list = userList
	return nil
}
