package model

import (
	"trading-go/common"
	"trading-go/response"
)

type Order struct {
	Id      uint   `db:"id"`
	GoodsId uint   `db:"goods_id"`
	BuyerId uint   `db:"buyer_id" json:"buyerId,string"`
	Time    uint   `db:"time"`
	Place   string `db:"place"`
	Phone   string `db:"phone"`
	State   int    `db:"state"`
}

type OrderJson struct {
	GoodsId uint   `json:"goodsId"`
	BuyerId uint   `json:"buyerId,string"`
	Time    uint   `json:"time"`
	Place   string `json:"place"`
	Phone   string `json:"phone"`
	State   int    `json:"state"`
}

type OrderSurface struct {
	OrderId  uint   `json:"orderId" db:"order_id"`
	GoodsId  uint   `json:"goodsId" db:"goods_id"`
	GoodsImg string `json:"goodsImg" db:"pic"`
	Price    uint   `json:"price" db:"price"`
	State    int    `json:"state" db:"state"`
	Title    string `json:"title" db:"title"`
	BName    string `json:"bName" db:"name"`
	Bid      uint   `json:"bid,string" db:"uid"`
}

func (o OrderJson) Change() Order {
	return Order{
		GoodsId: o.GoodsId,
		BuyerId: o.BuyerId,
		Time:    o.Time,
		Place:   o.Place,
		Phone:   o.Phone,
		State:   o.State,
	}
}

func (o Order) GetAll() (orders []Order, err error) {
	db := common.DB
	sqlStr := "SELECT * FROM orders"
	err = db.Select(&orders, sqlStr)
	return
}

func (o Order) GetOwner(ownerId uint) (orderSurface []OrderSurface, err error) {
	db := common.DB
	sqlStr := `SELECT o.id as order_id, g.id as goods_id, g.pic as pic, g.price as price, o.state as state, g.title as title, u.name as name, u.uid as uid
	FROM orders as o, goods_surfaces as g, users as u
	WHERE o.buyer_id = ? AND o.goods_id = g.id AND g.owner_id = u.uid;`
	err = db.Select(&orderSurface, sqlStr, ownerId)
	return
}

func (o Order) Revise() error {
	db := common.DB
	sqlStr := "UPDATE orders SET state = ? WHERE id = ?"
	_, err := db.Exec(sqlStr, o.State, o.Id)
	return err
}

func (o Order) Create() error {
	db := common.DB
	sqlStr := "INSERT INTO orders(goods_id, buyer_id, time, place, phone, state) VALUES(:goods_id, :buyer_id, :time, :place, :phone , :state)"
	_, err := db.NamedExec(sqlStr, o)
	return err
}

func (o Order) Delete() error {
	db := common.DB
	sqlStr := "DELETE FROM orders WHERE id = ?"
	_, err := db.Exec(sqlStr, o.Id)
	return err
}

func (o Order) GetPaged(page, pageSize int) (rsp response.PageResponse, err error) {
	var orders []Order
	db := common.DB
	sqlStr := "SELECT * FROM orders LIMIT ?,?"
	rsp.Page = page
	rsp.PageSize = pageSize
	err = db.Select(&orders, sqlStr, (page-1)*pageSize, pageSize)
	rsp.Data = orders
	return
}

func (o Order) GetCnt() (cnt int, err error) {
	db := common.DB
	sqlStr := "SELECT COUNT(1) FROM orders"
	err = db.Get(&cnt, sqlStr)
	return
}