package acquirer_student

import (
	"context"
	"fmt"
	"git.i2edu.net/i2/i2-bill-api/internal/svc"
	"git.i2edu.net/i2/i2-bill-api/internal/types"
	"git.i2edu.net/i2/i2-bill-api/internal/utils"
	"git.i2edu.net/i2/i2-bill-erp/transform"
	"net/http"
	"strconv"
	"time"

	"git.i2edu.net/i2/go-zero/core/logx"
)

type AcquirerStudentPageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAcquirerStudentPageLogic(ctx context.Context, svcCtx *svc.ServiceContext) AcquirerStudentPageLogic {
	return AcquirerStudentPageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AcquirerStudentPageLogic) AcquirerStudentPage(r *http.Request) (*types.Response, error) {
	// todo: add your logic here and delete this line
	r.ParseForm()
	create_time_sta := r.Form.Get("create_time_sta")
	create_time_end := r.Form.Get("create_time_end")
	page, _ := strconv.Atoi(r.Form.Get("page"))
	rows, _ := strconv.Atoi(r.Form.Get("rows"))
	check_state := r.Form.Get("check_state")
	sort := r.Form.Get("__sort__")
	userId := fmt.Sprintf("%d", l.svcCtx.GetUserIdByJwt(l.ctx))
	if create_time_end != "" {
		end, err := time.Parse("2006-01-02", create_time_end)
		if err != nil {
			return &types.Response{500, err.Error(), nil}, nil
		}
		create_time_end = end.Add(time.Second*24*60*60 - 1*time.Second).Format("2006-01-02 15:04:05")

	}
	if sort == "" {
		sort = "id desc"
	}
	paramMap_i_t := map[string]interface{}{
		"page":            page,
		"rows":            rows,
		"create_time_sta": create_time_sta,
		"create_time_end": create_time_end,
		"user_id":         userId,
		"check_state":     check_state,
		"__sort__":        sort,
	}
	res, err := utils.PageSearch(l.svcCtx.DB, "i2bill_acquirer_student", "page", "i2bill_acquirer_student", paramMap_i_t)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	erpRes, err := l.svcCtx.Transformer.GetErpSchool(l.ctx, &transform.Empty{})
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), res}, nil
	}
	if res.Content != nil {
		for index, r := range res.Content {
			for _, sch := range erpRes.School {
				if sch.Id == r["sch_id"].(int64) {
					r["sch_name"] = sch.Name
					res.Content[index] = r
					break
				}
			}
			phone := r["stu_phone"].(string)
			if len(phone) >= 11 {
				r["stu_phone"] = utils.ReplaceSub(phone, "*", 3, 4)
			} else if len(phone) > 5 {
				r["stu_phone"] = utils.ReplaceSub(phone, "*", 2, 2)
			}
		}
	}
	return &types.Response{200, "", res}, nil

}
