package service

import (
	"fmt"
	"gin-vue-admin/global"
	"gin-vue-admin/model/request"
	"strconv"
)

func GetCustomerUserList(req request.GetCustomerUserListReq) (error, []request.GetCustomerUserList, int64) {
	pagesize := 10
	page := 1
	if req.PageSize != 0 {
		pagesize = req.PageSize
	}
	if req.Page != 0 {
		page = req.Page
	}
	currentpage := pagesize * (page - 1)

	list := make([]request.GetCustomerUserList, 0)

	table := " customer_user"

	field := " id, user_name, region, city, zone, address, contacts, contacts_mobile" +
		", worker_position, worker_name, worker_mobile, user_source, user_type, create_time "

	conditions := ""

	orderby := " id asc "

	if req.UserName != "" {
		conditions += " AND user_name like '%" + req.UserName + "%'"
	}

	if req.Region != "" {
		conditions += " AND region like '%" + req.Region + "%'"
	}

	if req.City != "" {
		conditions += " AND city like '%" + req.City + "%'"
	}

	if req.Zone != "" {
		conditions += " AND zone like '%" + req.Zone + "%'"
	}

	if req.WorkerName != "" {
		conditions += " AND worker_name like '%" + req.WorkerName + "%'"
	}

	if req.WorkerMobile != "" {
		conditions += " AND worker_mobile like '%" + req.WorkerMobile + "%'"
	}

	//@@总条数，总页数
	var totalItem int64 = 0

	sqlStr := "SELECT count(id) as totalItem FROM " + table + " where 1=1 " + conditions
	global.GVA_DB.Raw(sqlStr).Count(&totalItem) //获取总条数

	sqlStr2 := "SELECT " + field +
		" FROM " + table +
		" WHERE 1>0 " + conditions +
		" ORDER BY " + orderby +
		" LIMIT " + strconv.Itoa(currentpage) + "," + strconv.Itoa(pagesize)

	global.GVA_DB.Raw(sqlStr2).Scan(&list)
	if global.GVA_DB.Error != nil {
		fmt.Println(sqlStr2)
		return global.GVA_DB.Error, nil, 0
	}
	return nil, list, totalItem
}
