package mobile

import (
	"fmt"
	"gin-vue-admin/global"
	"gin-vue-admin/model/request"
	"gin-vue-admin/model/response"
	"gin-vue-admin/service"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"go.uber.org/zap"
	"strconv"
	"time"
)

func GetCustomerUserList(c *gin.Context) {
	var req request.GetCustomerUserListReq
	_ = c.ShouldBindQuery(&req)
	err, list, total := service.GetCustomerUserList(req)
	reply := request.GetCustomerUserListReply{}
	reply.List = list
	reply.Total = total

	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Any("err", err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithDetailed(reply, "获取成功", c)
	}
	return
}

func ExportMsgExcel(c *gin.Context) {
	var req request.GetCustomerUserListReq
	_ = c.ShouldBindQuery(&req)

	req.PageSize = 99999

	_, list, _ := service.GetCustomerUserList(req)

	codeList := service.GetVcodeList(req.MocId)

	fileName := "用户短链列表" + time.Now().Format("20060102")
	f := excelize.NewFile()
	// Create a new sheet.
	index := f.NewSheet(fileName)

	f.SetCellValue(fileName, "A1", "用户ID")
	f.SetCellValue(fileName, "B1", "用户名称")
	f.SetCellValue(fileName, "C1", "省")
	f.SetCellValue(fileName, "D1", "市")
	f.SetCellValue(fileName, "E1", "区")
	f.SetCellValue(fileName, "F1", "工作人员")
	f.SetCellValue(fileName, "G1", "工作人员电话")
	f.SetCellValue(fileName, "H1", "短链")

	for k, v := range list {
		url := ""
		code, ok := codeList[v.Id]
		if ok == true {
			url = global.GVA_CONFIG.Common.Url + "/" + code
		} else {
			url = global.GVA_CONFIG.Common.Url + "/" + service.GetVcode(v.Id, req.MocId)
		}

		a := strconv.Itoa(k + 2)
		f.SetCellValue(fileName, "A"+a, v.Id)
		f.SetCellValue(fileName, "B"+a, v.UserName)
		f.SetCellValue(fileName, "C"+a, v.Region)
		f.SetCellValue(fileName, "D"+a, v.City)
		f.SetCellValue(fileName, "E"+a, v.Zone)
		f.SetCellValue(fileName, "F"+a, v.WorkerName)
		f.SetCellValue(fileName, "G"+a, v.WorkerMobile)
		f.SetCellValue(fileName, "H"+a, url)
	}

	// Set active sheet of the workbook.
	f.SetActiveSheet(index)
	// Save xlsx file by the given path.
	if err := f.SaveAs("./" + fileName + ".csv"); err != nil {
		fmt.Println(err)
		return
	}

	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", "./"+fileName+".csv")) //fmt.Sprintf("attachment; filename=%s", filename)对下载的文件重命名
	c.Writer.Header().Add("Content-Type", "application/octet-stream")
	c.File("./" + fileName + ".csv")
	return
}
