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 Car struct {
	service.Service
}

func CarIsBindUserScopes(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 获取Car列表
func (e *Car) GetPage(c *dto.CarGetPageReq, list *[]model.Car, count *int64, p *actions.DataPermission) error {
	var err error
	var data model.Car

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
			CarIsBindUserScopes(c.IsBind),
		).
		Joins("User").
		Where("car_no 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 获取Car对象
func (e *Car) Get(d *dto.CarGetReq, carModel *model.Car, p *actions.DataPermission) error {
	err := e.Orm.
		Scopes(actions.Permission(carModel.TableName(), p)).
		Preload("User").
		First(carModel, 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 创建Car对象
func (e *Car) Insert(c *dto.CarInsertReq) error {
	var err error
	var data model.Car

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

	var i int64
	err = tx.Model(&data).Where("car_no = ?", c.CarNo).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{data.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 修改Car对象
func (e *Car) Update(c *dto.CarUpdateReq, p *actions.DataPermission) error {
	var err error

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

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

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

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

	c.Id = carModel.Id
	return nil
}

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

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

	var carModel model.Car

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

	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 *Car) GetUserList(c *dto.SysUserGetPageReq, p *actions.DataPermission, list *[]model.SysUserForBind, count *int64) error {
	var err error
	var userList []model.SysUserForBind

	var carModel model.Car
	var userModel model.SysUserForBind
	var userIds []int
	// 查询仓库是否存在
	err = e.Orm.Model(&carModel).Select("user_id").Scopes(actions.Permission(carModel.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
}
