package user

import (
	"time"

	"github.com/33cn/chain33/common/address"
	"github.com/tealeg/xlsx"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"courseSign/server/global"
	"courseSign/server/model/common/request"
	"courseSign/server/model/user"
	userReq "courseSign/server/model/user/request"
)

type UsersService struct {
}

// CreateUsers 创建Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService) CreateUsers(users user.Users) (err error) {
	err = global.GVA_DB.Create(&users).Error
	return err
}

// DeleteUsers 删除Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService)DeleteUsers(users user.Users) (err error) {
	err = global.GVA_DB.Delete(&users).Error
	return err
}

// DeleteUsersByIds 批量删除Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService)DeleteUsersByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]user.Users{},"id in ?",ids.Ids).Error
	return err
}

// UpdateUsers 更新Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService)UpdateUsers(users user.Users) (err error) {
	err = global.GVA_DB.Save(&users).Error
	return err
}

func (usersService *UsersService)ImportBlack(file string) (n int,err error) {
	xfile,err := xlsx.OpenFile(file)
	if err != nil {
		global.GVA_LOG.Error("ImportBlack",zap.Any("openfile",err),zap.String("file",file))
		return
	}
	list := make([]*user.Users,0)
	createTime := time.Now()
	black := true
	for _, rows := range xfile.Sheets[0].Rows {
		for kk,cell := range rows.Cells {
			if kk == 0 {
				u := &user.Users{}
				u.IsBlack = &black
				t := 0
				if cell.String() == "" {
					continue
				}
				if err = address.CheckAddress(cell.String(),-1);err == nil {
					u.CreateTime = &createTime
					u.Address = cell.String()
					if address.IsEthAddress(cell.String()) {
						t = user.ADDRESSTYPEETH
					} else {
						t = user.ADDRESSTYPEBTY
					}
					u.AddressType = &t
					list = append(list, u)
					break
				} else {
					global.GVA_LOG.Error("ImportBlack",zap.Any("address not right",cell.String()))
					return
				}
			}
		}
	}
	global.GVA_LOG.Info("ImportBlack start",zap.Any("黑名单条数",len(list)))
	tx := global.GVA_DB.Begin()
	for _,v := range list {
		u := &user.Users{}
		err = tx.Model(&user.Users{}).Where("address = ?",v.Address).First(u).Error

		if err != nil && err != gorm.ErrRecordNotFound {
			tx.Rollback()
			return
		} else if err != nil && err == gorm.ErrRecordNotFound {
			err = tx.Model(&user.Users{}).Create(v).Error
			if err != nil {
				tx.Rollback()
				return
			}
			n++
			continue
		}
		if err == nil && !*u.IsBlack {
			err = tx.Model(&user.Users{}).Where("id = ?",u.ID).UpdateColumns(map[string]interface{}{"is_black":true,"address_type":v.AddressType}).Error
			if err != nil {
				tx.Rollback()
				return
			}
			n++
		}
	}
	tx.Commit()
	global.GVA_LOG.Info("ImportBlack done",zap.Any("黑名单条数",len(list)))
	return
}

// GetUsers 根据id获取Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService)GetUsers(id uint) (users user.Users, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&users).Error
	return
}

// GetUsersByAddr 根据id获取Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService)GetUsersByAddr(id string) (users user.Users, err error) {
	err = global.GVA_DB.Where("address = ?", id).First(&users).Error
	return
}

// GetUsersInfoList 分页获取Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService)GetUsersInfoList(info userReq.UsersSearch,order string,desc bool) (list []user.Users, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Debug().Model(&user.Users{})
    var userss []user.Users
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
     db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
    }
    if info.Address != "" {
        db = db.Where("address = ?",info.Address)
    }
    if info.AddressType != nil {
        db = db.Where("address_type = ?",info.AddressType)
    }
    if info.IsBlack != nil {
        db = db.Where("is_black = ?",info.IsBlack)
    }
    if info.CreateTime != nil {
        db = db.Where("create_time <> ?",info.CreateTime)
    }
	err = db.Count(&total).Error
	if err!=nil {
		return
	}

    if order != "" {
		var OrderStr string
		// 设置有效排序key 防止sql注入
		// 感谢 Tom4t0 提交漏洞信息
		orderMap := make(map[string]bool, 1)
		orderMap["id"] = true
		if orderMap[order] {
			if desc {
				OrderStr = order + " desc"
			} else {
				OrderStr = order
			}
		} else { // didn't matched any order key in `orderMap`
			return list, total, err
		}
		err = db.Limit(limit).Offset(offset).Order(OrderStr).Find(&userss).Error
	} else {
		err = db.Limit(limit).Offset(offset).Find(&userss).Error
	}



	return  userss, total, err
}
