package models

import (
	"bytes"
	"strconv"
	"strings"
)

type Pages struct {
	PageNo     int    //当前页
	PageSize   int    //每页多少数据
	TotalPage  int    //总共多少页
	TotalCount int    //总共多少条数据
	FirstPage  int    //第一页
	LastPage   int    //最后一页
	Url        string //链接
}

func NewPage(PageNo int, PageSize int, TotalCount int, Url string) Pages {
	return Pages{PageNo: PageNo, PageSize: PageSize, TotalCount: TotalCount, Url: Url}
}

//计算总页数
func (c *Pages) getPageCount() {
	var tp float32 = float32(c.TotalCount) / float32(c.PageSize)
	if tp < 1 {
		c.TotalPage = 1
	}
	var tpint float32 = float32(int(tp))

	if tp > tpint {
		tpint += 1
	}
	c.TotalPage = int(tpint)
	c.LastPage = int(tpint)
	c.FirstPage = 1
	c.execUrl()
}

//格式化URL地址
func (c *Pages) execUrl() {
	if strings.Contains(c.Url, "?") {
		c.Url = strings.Join([]string{c.Url, "&page="}, "")
	} else {
		c.Url = strings.Join([]string{c.Url, "?page="}, "")
	}
}

//获取URL组织
func (c *Pages) getUrl(page int) string {
	return strings.Join([]string{c.Url, strconv.Itoa(page)}, "")
}

func (c *Pages) getNum(page int, num int) (int, int) {
	var k = 1
	//分布显示数量
	var v = 5
	if page > 3 {
		k = page - 2
		v = page + 2
		if v > num {
			k = num - 4
			v = num
		}
	} else {
		if v > num {
			v = num
		}
	}
	return k, v
}
func (c *Pages) LimitStart() int {
	return (c.PageNo - 1) * c.PageSize
}
func (c *Pages) Show() string {
	c.getPageCount()
	var style bytes.Buffer
	style.WriteString("<style> .pageing{ width:360px; list-style-type:none; margin: 0px;padding: 0px; } .pageing>li {  float: left; width: 30px; line-height:23px; text-align: center; border: 1px solid #7B7B7B; margin:3px; }  </style>")
	var buf bytes.Buffer
	str := "<div style=\"clear:both;\"></div><ul class=\"pageing\"><li><a href=\"" + c.getUrl(1) + "\">1</a></li>"
	buf.WriteString(str)
	if c.PageNo > 1 {
		buf.WriteString("<li><a href=\"" + c.getUrl(c.PageNo-1) + "\"><<</a></li>")
	}

	k, v := c.getNum(c.PageNo, c.TotalPage)

	for i := k; i <= v; i++ {
		if i == c.PageNo {
			buf.WriteString("<li style=\"background-color: green;\">")
			buf.WriteString(strconv.Itoa(i))
		} else {
			buf.WriteString("<li><a href=\"" + c.getUrl(i) + "\">")
			buf.WriteString(strconv.Itoa(i))
		}
		buf.WriteString("</a></li>")
	}

	if c.PageNo < c.TotalPage {
		var nextPage int = c.PageNo + 1
		buf.WriteString("<li><a href=\"" + c.getUrl(nextPage) + "\">>></a></li>")
	}

	buf.WriteString("<li><a href=\"" + c.getUrl(c.TotalPage) + "\">" + strconv.Itoa(c.TotalPage) + "</a></li></ul>")
	return style.String() + buf.String()
}
