package usermanage

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"go-admin/app/admin/apis/pay"
	"go-admin/app/admin/models"
	orm "go-admin/common/global"
	"go-admin/logger"
	"go-admin/pkg/jwtauth"
	"go-admin/tools"
	"go-admin/tools/app"
	"go-admin/tools/config"
	"net/http"
	"strings"
	"time"
)

func UserList(c *gin.Context) {
	req := struct {
		Page                  int    `json:"pageIndex"`
		PageSize              int    `json:"pageSize"`
		Tel                   string `json:"tel"`                     // 电话
		Uid                   int    `json:"uid"`                     // 用户id
		CooperativeBusinessId int    `json:"cooperative_business_id"` // 合作商id
		MemberLevel           int    `json:"memberLevel"`             // 当前会员等级:10-普通用户 1-普通会员 2-黄金会员 4-白金会员 5-黑金会员
		StoreId               int    `json:"store_id"`                // 门店id
		UserType              int    `json:"user_type"`               // 用户类型 用户类型 1-普通用户 2-店员
		StartTime             string `json:"startTime"`               // 开始时间
		EndTime               string `json:"endTime"`                 // 结束时间
		NameKey               string `json:"nameKey"`                 // 昵称搜索
		SortField             string `json:"sort_field"`              // 排序字段
		SortType              string `json:"sort_type"`               // 排序类型
		Filter                bool   `json:"filter"`                  // 是否过滤无滞纳金已标记用户
	}{
		Page:     1,
		PageSize: 10,
	}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	fmt.Printf("req: %+v \n", req)
	if req.CooperativeBusinessId == 0 {
		data, _ := c.Get(jwtauth.JwtPayloadKey)
		mapClaims := data.(jwtauth.MapClaims)
		sysUid := float64(0)
		if v, ok := mapClaims["identity"]; ok {
			sysUid = v.(float64)
		}
		var sUser models.SysUser
		sql := fmt.Sprintf("SELECT * FROM sys_user WHERE user_id=%.0f;", sysUid)
		err := orm.Eloquent.Raw(sql).Scan(&sUser).Error
		if err != nil {
			logger.Error("sys user err:", logger.Field("err", err))
			app.Error(c, http.StatusInternalServerError, err, "查询失败")
			return
		}
		req.CooperativeBusinessId = int(sUser.CooperativeBusinessId)
	}

	//req.SysUid = fmt.Sprintf("%.0f", sysUid)

	userList, _, count, err := models.GetUserList(req.Page, req.PageSize, req.Uid, req.MemberLevel, req.StoreId,
		req.UserType, req.CooperativeBusinessId, req.Tel, req.StartTime, req.EndTime, req.NameKey, req.SortField, req.SortType, req.Filter)
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	var uids []uint32
	for _, u := range userList {
		if u.MemberExpireDays > 0 {
			uids = append(uids, u.Uid)
		}
	}
	//未归还卡带
	cards, err := models.GetUserExpiredCards(uids)
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	for i, u := range userList {
		c, ok := cards[u.Uid]
		if ok {
			userList[i].OrderCards = c
			//滞纳金 一个卡带一天2块钱
			userList[i].ForfeitPenalty = len(c) * 200 * int(userList[i].MemberExpireDays)
		}
	}

	ret := map[string]interface{}{
		"count":      count,
		"list":       userList,
		"pageIndex":  req.Page,
		"total_page": req.PageSize,
	}
	app.OK(c, ret, "")
}

// NewUserList 所有用户
// @Summary 所有用户
// @Tags 会员管理, V1.2.0
// @Produce json
// @Accept json
// @Param request body models.NewUserListReq true "所有用户模型"
// @Success 200 {object} models.NewUserListResp
// @Router /api/v1/user_info/list [post]
func NewUserList(c *gin.Context) {
	var req = new(models.NewUserListReq)
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	fmt.Printf("req: %+v \n", req)
	ret, err := models.GetNewUserList(req, c)
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	app.OK(c, ret, "")
}

func CommonProblemList(c *gin.Context) {
	commonProblem := &models.CommonProblem{}
	list, err := commonProblem.List()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	app.OK(c, list, "")
}

func CommonProblemAdd(c *gin.Context) {
	commonProblem := &models.CommonProblem{}
	if c.ShouldBindJSON(commonProblem) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	err := commonProblem.Add()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	app.OK(c, commonProblem, "")
}

func CommonProblemModify(c *gin.Context) {
	commonProblem := &models.CommonProblem{}
	if c.ShouldBindJSON(commonProblem) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	err := commonProblem.Modify()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	app.OK(c, commonProblem, "")
}

func CommonProblemDel(c *gin.Context) {
	req := &struct {
		CommonProblemId uint32 `json:"common_problem_id"`
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	commonProblem := &models.CommonProblem{}
	commonProblem.ID = req.CommonProblemId
	err := commonProblem.Del()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	app.OK(c, commonProblem, "")
	return
}

func UserAddAssistant(c *gin.Context) {
	req := &struct {
		Uid                   uint32 `json:"uid"`                 // 用户id
		ShopAssistantName     string `json:"shop_assistant_name"` // 店员名称
		StoreId               uint32 `json:"store_id"`            // 门店id
		CooperativeBusinessId uint32 `json:"cooperative_business_id"`
		XcxRoleId             uint32 `json:"xcx_role_id"` // 角色id
		//Name    string `json:"name"`     //
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	//models.UserInfo{}
	// TODO 注册会员更新时间
	// TODO 会员价格
	// TODO 支付地址
	userInfo, err := models.GetUserInfoByUid(req.Uid)
	if err != nil {
		logger.Error("get user info err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "绑定店员失败")
		return
	}
	if userInfo.Uid != req.Uid {
		logger.Error("user info err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "绑定店员失败")
		return
	}
	var cooperative models.CooperativeBusiness
	err = orm.Eloquent.Table("cooperative_business").Where("id=?", req.CooperativeBusinessId).Find(&cooperative).Error
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "绑定店员失败")
		return
	}
	store, err := models.GetStore(req.StoreId)
	if err != nil {
		logger.Error("get store err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "绑定店员失败")
		return
	}
	if store.CooperativeBusinessId != req.CooperativeBusinessId {
		logger.Error("cooperative business store err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "绑定门店错误")
		return
	}

	sql := fmt.Sprintf(
		"UPDATE `user` SET user_type = 2, store_id = %d,shop_assistant_name='%s',cooperative_business_id=%d,cooperative_name='%s',xcx_role_id=%d WHERE uid = %d;",
		req.StoreId, req.ShopAssistantName, req.CooperativeBusinessId, cooperative.Name, req.XcxRoleId, req.Uid)
	err = orm.Eloquent.Exec(sql).Error
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "绑定店员失败")
		return
	}

	app.OK(c, nil, "绑定店员成功")
}

func UserAssistantDel(c *gin.Context) {
	req := &struct {
		Uid uint32 `json:"uid"` // 用户id
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	//models.UserInfo{}

	// TODO 注册会员更新时间
	// TODO 会员价格
	// TODO 支付地址
	sql := fmt.Sprintf("UPDATE `user` SET user_type = 1, store_id = 0 WHERE uid = %d;", req.Uid)
	err := orm.Eloquent.Exec(sql).Error
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "绑定失败")
		return
	}

	app.OK(c, nil, "绑定店员成功")
}

func UserInviteList(c *gin.Context) {
	req := new(models.UserInviteListReq)
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	// TODO 注册会员更新时间
	// TODO 会员价格
	// TODO 支付地址
	list, count, err := req.InviteList()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := map[string]interface{}{
		"count":     count,
		"list":      list,
		"pageIndex": req.Page,
	}
	app.OK(c, ret, "")
}

func CancelMembers(c *gin.Context) {
	req := &struct {
		Uid uint32 `json:"uid"` // 用户id
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	//list, count, err := req.InviteList()
	//if err != nil {
	//	logger.Errorf("err:",logger.Field("err",err))
	//	app.Error(c, http.StatusInternalServerError, err, "查询失败")
	//	return
	//}
	var userInfo models.UserInfo
	err := orm.Eloquent.Table("user").Where("uid", req.Uid).Find(&userInfo).Error
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询用户失败")
		return
	}
	oldMember := userInfo.MemberLevel
	userInfo.MemberLevel = 1
	//memberExpire := userInfo.MemberExpire.AddDate(-1, 0, 0)
	//userInfo.MemberExpire = memberExpire
	nowTime := time.Now()
	sql := fmt.Sprintf("UPDATE `user` SET member_level = 1,member_expire=?,updated_at=?,deposit=0 WHERE uid = ?;")
	err = orm.Eloquent.Debug().Exec(sql, nowTime, nowTime, req.Uid).Error
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "取消会员失败")
		return
	}
	var userInvite models.UserInvite
	orm.Eloquent.Table("user_invite").Where("to_uid=?", req.Uid).Where("spend_type=2").
		Order("id DESC").Limit(1).Find(&userInvite)
	sqlInvite := fmt.Sprintf("UPDATE user_invite SET member_status=3,action=1,spend_type=1 WHERE id= ? ;")
	err = orm.Eloquent.Exec(sqlInvite, userInvite.ID).Error
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "取消会员失败")
		return
	}

	var vmCount int
	switch oldMember {
	case models.MemberLevelGold, models.MemberLevelPeriod: // 黄金会员
		if userInfo.MemberGenre == 200 { // 年费
			vmCount = -399
		} else if userInfo.MemberGenre == 201 { // 季度
			vmCount = -199
		} else if userInfo.MemberGenre == 202 { // 半年
			vmCount = -299
		}
	case models.MemberLevelPlatinum: // 白金会员
		vmCount = -699
	case models.MemberLevelBlackGold: // 黑金会员
		vmCount = -1499
	}

	// 更新用户积分
	err = models.UserVmUpdate(nil, "", uint32(req.Uid), vmCount, models.VmEventCancelMember,
		"取消租卡会员")
	if err != nil {
		logger.Errorf("err:", err)
	}

	app.OK(c, userInfo, "修改成功")
}

func ExportDataUser(c *gin.Context) {
	req := struct {
		StoreId          uint32 `json:"store_id"`
		StartTime        string `json:"startTime"` // 开始时间
		EndTime          string `json:"endTime"`   // 结束时间
		RenewalStartTime string `json:"renewal_start_time"`
		RenewalEndTime   string `json:"renewal_end_time"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	//goodsStock := models.ExportUserMember(req.StoreId, req.StartTime, req.EndTime)
	sysUser, err := models.GetSysUserByCtx(c)
	if err != nil {
		logger.Error("sys user err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	//sysUser := &models.SysUser{}
	//data, _ := c.Get(jwtauth.JwtPayloadKey)
	//sysUid, ok := data.(jwtauth.MapClaims)["identity"]
	//if !ok {
	//	logger.Error("sys uid err")
	//	app.Error(c, http.StatusInternalServerError, errors.New("sys uid err"), "查询失败")
	//	return
	//}
	//sysUser, err := models.GetSysUser(sysUid)
	//if err != nil {
	//	logger.Error("sys user err:",logger.Field("err",err))
	//	app.Error(c, http.StatusInternalServerError, err, "查询失败")
	//	return
	//}

	goodsStock := models.ExportUserMemberList(req.StoreId, 2, sysUser.CooperativeBusinessId, req.StartTime, req.EndTime, req.RenewalStartTime, req.RenewalEndTime)

	//StoreId uint32 `json:"store_id"` // 门店id
	//cardGoods := &models.GameCardGoods{}
	//err := cardGoods.Adds(req.Cards)
	//if err != nil {
	//	logger.Errorf("err:",logger.Field("err",err))
	//	app.Error(c, http.StatusInternalServerError, err, "入库失败")
	//	return
	//}
	ret := &map[string]interface{}{
		"goods_stock_url": goodsStock,
	}
	app.OK(c, ret, "数据导出成功")
}

func ExportDataUserMember(c *gin.Context) {
	req := struct {
		MemberType uint32 `json:"member_type"` // 1-普通用户 2-会员 3-短期会员
		StoreId    uint32 `json:"store_id"`
		StartTime  string `json:"startTime"` // 开始时间
		EndTime    string `json:"endTime"`   // 结束时间
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	// pms 导出会员数据
	goodsStock := models.ExportUserMemberList(req.StoreId, req.MemberType, 0, req.StartTime, req.EndTime, "", "")
	//StoreId uint32 `json:"store_id"` // 门店id
	//cardGoods := &models.GameCardGoods{}
	//err := cardGoods.Adds(req.Cards)
	//if err != nil {
	//	logger.Errorf("err:",logger.Field("err",err))
	//	app.Error(c, http.StatusInternalServerError, err, "入库失败")
	//	return
	//}
	ret := &map[string]interface{}{
		"goods_stock_url": goodsStock,
	}
	app.OK(c, ret, "数据导出成功")
}

func ArticleAdd(c *gin.Context) {
	req := &models.Article{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	err := orm.Eloquent.Create(req).Error
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "添加文章错误")
		return
	}

	app.OK(c, nil, "绑定店员成功")
}

func ArticleUpdate(c *gin.Context) {
	req := &models.Article{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	err := orm.Eloquent.Save(req).Error
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "添加文章错误")
		return
	}

	app.OK(c, nil, "绑定店员成功")
}

func ArticleList(c *gin.Context) {
	req := &models.ArticleListReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	list, total, err := req.GetArticleList()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "获取列表错误")
		return
	}

	ret := &map[string]interface{}{
		"list":     list,
		"count":    total,
		"page_idx": req.PageIdx,
	}
	app.OK(c, ret, "绑定店员成功")
}

func ArticleDel(c *gin.Context) {
	req := &struct {
		Ids []int `json:"ids"`
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	err := orm.Eloquent.Table("article").Where("id in (?)", req.Ids).Delete(&models.Article{}).Error
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "文章删除错误")
		return
	}

	app.OK(c, nil, "绑定店员成功")
}

// AutoDepositRefund 每天早上9点30分退前一天的保证金
func AutoDepositRefund() {
	if config.ApplicationConfig.Mode == "dev" {
		logger.Info("****开发环境不支持自动退保证金****")
		fmt.Println("****开发环境不支持自动退保证金****")
	}

	logger.Info("**** start AutoDepositRefund ****")
	fmt.Println("**** start AutoDepositRefund ****")
	// 查询待审核的订单
	var depositRefunds []models.DepositRefundRecord
	err := orm.Eloquent.Table("deposit_refund_record").
		Where("status = ?", models.DepositRefundStatusUnconfirmed).Order("id ASC").Limit(10).Find(&depositRefunds).Error
	if err != nil {
		logger.Error("AutoDepositRefund query deposit_refund_record err:", logger.Field("err", err))
		return
	}

	if len(depositRefunds) == 0 { // 没有找到待审核的
		logger.Info("****未查询到待审核订单****")
		fmt.Println("****未查询到待审核订单****")
	}

	for _, depositInfo := range depositRefunds {
		err = NotarizeUserDepositRefundByID(depositInfo.ID)
		if err != nil && err.Error() == "押金退款失败，请检查余额" { // 余额不足，停止退款并发短信
			logger.Errorf("押金退款失败，请检查余额")
			fmt.Println("押金退款失败，请检查余额")
			models.GtSendMessage([]string{"15019230751", "13510508605"}, "【明慧科技】用户押金退款失败，请检查微信商户余额。")
			return
		}
	}
	fmt.Println("**** end AutoDepositRefund ****")
	logger.Info("**** end AutoDepositRefund ****")
}

func NotarizeUserDepositRefundByID(depositRefundRecordId uint32) error {
	if depositRefundRecordId == 0 {
		return errors.New("invalid deposit refund record ID")
	}

	fmt.Println("DepositRefundRecordId:", depositRefundRecordId)
	var depositRefund models.DepositRefundRecord
	err := orm.Eloquent.Table("deposit_refund_record").Where("id = ?", depositRefundRecordId).Find(&depositRefund).Error
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		return err
	}
	if depositRefund.Status != models.DepositRefundStatusUnconfirmed {
		logger.Error("status not DepositRefundStatusUnconfirmed")
		return err
	}

	unreturnedOrders, err := models.IsUserHaveUnreturnedOrders(depositRefund.Uid)
	if err != nil {
		logger.Error("IsUserHaveUnreturnedOrders err:", logger.Field("err", err))
		return err
	}
	if unreturnedOrders {
		logger.Error("unreturnedOrders")
		return errors.New("用户有未完成订单")
	}

	userInfo, err := models.GetUserInfoByUid(depositRefund.Uid)
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		return err
	}
	var transfer *pay.WxTransferResp
	//if userInfo.Deposit == 80 {
	nTempDeposit := userInfo.Deposit // 用户押金
	fmt.Println("******userInfo.Deposit is:******", nTempDeposit)
	var results []*pay.WxTransferResp
	if userInfo.Deposit == 60000 {
		for i := 0; i < 2; i++ {
			transfer, err = pay.Transfer(userInfo.Deposit/2, userInfo.WxOpenID, fmt.Sprintf("押金退款(共2次到账)%d/2", i+1))
			if err != nil {
				logger.Errorf("pay.Transfer 600 err, i is:", i)
				logger.Error("pay.Transfer 600 err:", logger.Field("err", err))

				if i != 0 { // 非首次退款报错
					updateUser := map[string]interface{}{
						"deposit":      nTempDeposit,
						"member_level": 1,
					}
					if userInfo.MemberExpire.After(time.Now()) {
						updateUser["member_expire"] = time.Now()
					}
					err = orm.Eloquent.Table("user").Where("uid = ?", userInfo.Uid).Updates(updateUser).Error
					if err != nil {
						logger.Error("pay.Transfer 600 update deposit err:", logger.Field("err", err))
					}

					if len(results) != 0 {
						lastTransfer := results[len(results)-1]
						fundRecord := &models.FundRecord{
							Uid:        depositRefund.Uid,
							FundType:   models.FundTypeDepositRefund,
							Amount:     int64(userInfo.Deposit-nTempDeposit) * (-1),
							OutTradeNo: lastTransfer.PartnerTradeNo,
							PaymentNo:  lastTransfer.PaymentNo,
							Status:     2,
							Remark:     "退还押金",
						}
						err = orm.Eloquent.Create(fundRecord).Error
						if err != nil {
							logger.Error("create fund record err:", logger.Field("err", err))
						}
					}
				}

				return errors.New("押金退款失败，请检查余额")
			}
			nTempDeposit -= 30000
			results = append(results, transfer)
		}
	} else if userInfo.Deposit == 150000 {
		for i := 0; i < 5; i++ {
			transfer, err = pay.Transfer(userInfo.Deposit/5, userInfo.WxOpenID, fmt.Sprintf("押金退款(共5次到账)%d/5", i+1))
			if err != nil {
				logger.Errorf("pay.Transfer 1500 err, i is:", i)
				logger.Error("pay.Transfer 1500 err:", logger.Field("err", err))

				if i != 0 { // 非首次退款报错
					updateUser := map[string]interface{}{
						"deposit":      nTempDeposit,
						"member_level": 1,
					}
					if userInfo.MemberExpire.After(time.Now()) {
						updateUser["member_expire"] = time.Now()
					}
					err = orm.Eloquent.Table("user").Where("uid = ?", userInfo.Uid).Updates(updateUser).Error
					if err != nil {
						logger.Error("pay.Transfer 1500 update deposit err:", logger.Field("err", err))
					}

					if len(results) != 0 {
						lastTransfer := results[len(results)-1]
						fundRecord := &models.FundRecord{
							Uid:        depositRefund.Uid,
							FundType:   models.FundTypeDepositRefund,
							Amount:     int64(userInfo.Deposit-nTempDeposit) * (-1),
							OutTradeNo: lastTransfer.PartnerTradeNo,
							PaymentNo:  lastTransfer.PaymentNo,
							Status:     2,
							Remark:     "退还押金",
						}
						err = orm.Eloquent.Create(fundRecord).Error
						if err != nil {
							logger.Error("create fund record err:", logger.Field("err", err))
						}
					}
				}

				return errors.New("押金退款失败，请检查余额")
			}
			nTempDeposit -= 30000
			results = append(results, transfer)
		}
	} else if userInfo.Deposit == 120000 {
		for i := 0; i < 4; i++ {
			transfer, err = pay.Transfer(userInfo.Deposit/4, userInfo.WxOpenID, fmt.Sprintf("押金退款(共4次到账)%d/4", i+1))
			if err != nil {
				logger.Errorf("pay.Transfer 1200 err, i is:", i)
				logger.Error("pay.Transfer 1200 err:", logger.Field("err", err))

				if i != 0 { // 非首次退款报错
					updateUser := map[string]interface{}{
						"deposit":      nTempDeposit,
						"member_level": 1,
					}
					if userInfo.MemberExpire.After(time.Now()) {
						updateUser["member_expire"] = time.Now()
					}
					err = orm.Eloquent.Table("user").Where("uid = ?", userInfo.Uid).Updates(updateUser).Error
					if err != nil {
						logger.Error("pay.Transfer 1200 update deposit err:", logger.Field("err", err))
					}

					if len(results) != 0 {
						lastTransfer := results[len(results)-1]
						fundRecord := &models.FundRecord{
							Uid:        depositRefund.Uid,
							FundType:   models.FundTypeDepositRefund,
							Amount:     int64(userInfo.Deposit-nTempDeposit) * (-1),
							OutTradeNo: lastTransfer.PartnerTradeNo,
							PaymentNo:  lastTransfer.PaymentNo,
							Status:     2,
							Remark:     "退还押金",
						}
						err = orm.Eloquent.Create(fundRecord).Error
						if err != nil {
							logger.Error("create fund record err:", logger.Field("err", err))
						}
					}
				}

				return errors.New("押金退款失败，请检查余额")
			}
			nTempDeposit -= 30000
			results = append(results, transfer)
		}
	} else if userInfo.Deposit == 90000 {
		for i := 0; i < 3; i++ {
			transfer, err = pay.Transfer(userInfo.Deposit/3, userInfo.WxOpenID, fmt.Sprintf("押金退款(共3次到账)%d/3", i+1))
			if err != nil {
				logger.Errorf("pay.Transfer 900 err, i is:", i)
				logger.Error("pay.Transfer 900 err:", logger.Field("err", err))

				if i != 0 { // 非首次退款报错
					updateUser := map[string]interface{}{
						"deposit":      nTempDeposit,
						"member_level": 1,
					}
					if userInfo.MemberExpire.After(time.Now()) {
						updateUser["member_expire"] = time.Now()
					}
					err = orm.Eloquent.Table("user").Where("uid = ?", userInfo.Uid).Updates(updateUser).Error
					if err != nil {
						logger.Error("pay.Transfer 900 update deposit err:", logger.Field("err", err))
					}

					if len(results) != 0 {
						lastTransfer := results[len(results)-1]
						fundRecord := &models.FundRecord{
							Uid:        depositRefund.Uid,
							FundType:   models.FundTypeDepositRefund,
							Amount:     int64(userInfo.Deposit-nTempDeposit) * (-1),
							OutTradeNo: lastTransfer.PartnerTradeNo,
							PaymentNo:  lastTransfer.PaymentNo,
							Status:     2,
							Remark:     "退还押金",
						}
						err = orm.Eloquent.Create(fundRecord).Error
						if err != nil {
							logger.Error("create fund record err:", logger.Field("err", err))
						}
					}
				}

				return errors.New("押金退款失败，请检查余额")
			}
			nTempDeposit -= 30000
			results = append(results, transfer)
		}
	} else if userInfo.Deposit == 30000 {
		transfer, err = pay.Transfer(userInfo.Deposit, userInfo.WxOpenID, "押金退款")
		if err != nil {
			logger.Error("pay.Transfer 300 err:", logger.Field("err", err))
			return errors.New("押金退款失败，请检查余额")
		}
	} else {
		logger.Errorf("押金退款失败， 押金额有误，userInfo.Deposit is:", userInfo.Deposit)
		return errors.New("押金退款失败，金额有误")
	}

	fmt.Println("transfer:", transfer)
	updateUser := map[string]interface{}{
		"deposit":      0,
		"member_level": 1,
	}
	if userInfo.MemberExpire.After(time.Now()) {
		updateUser["member_expire"] = time.Now()
	}
	err = orm.Eloquent.Table("user").Where("uid = ?", userInfo.Uid).Updates(updateUser).Error
	if err != nil {
		logger.Error("update deposit err:", logger.Field("err", err))
		return err
	}

	err = orm.Eloquent.Table("deposit_refund_record").Where("id = ?", depositRefund.ID).Updates(map[string]interface{}{
		"status":       models.DepositRefundStatusRefunded,
		"confirm_time": time.Now(),
	}).Error
	if err != nil {
		logger.Error("update deposit refund record err:", logger.Field("err", err))
		return err
	}
	fundRecord := &models.FundRecord{
		Uid:        depositRefund.Uid,
		FundType:   models.FundTypeDepositRefund,
		Amount:     int64(userInfo.Deposit) * (-1),
		OutTradeNo: transfer.PartnerTradeNo,
		PaymentNo:  transfer.PaymentNo,
		Status:     2,
		Remark:     "退还押金",

		//TransactionId: ,
	}
	err = orm.Eloquent.Create(fundRecord).Error
	if err != nil {
		logger.Error("create fund record err:", logger.Field("err", err))
	}

	return nil
}

func UserDepositRefundRecordList(c *gin.Context) {
	req := &models.UserDepositRefundRecordListReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	resp, err := req.DepositRefundRecordList()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "获取列表错误")
		return
	}

	app.OK(c, resp, "绑定店员成功")
}

func NotarizeUserDepositRefund(c *gin.Context) {
	req := &struct {
		DepositRefundRecordId uint32 `json:"deposit_refund_record_id"`
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	if config.ApplicationConfig.Mode == "dev" {
		logger.Info("****开发环境不支持退保证金****")
		fmt.Println("****开发环境不支持退保证金****")
	}

	fmt.Println("DepositRefundRecordId:", req.DepositRefundRecordId)
	var depositRefund models.DepositRefundRecord
	err := orm.Eloquent.Table("deposit_refund_record").Where("id = ?", req.DepositRefundRecordId).Find(&depositRefund).Error
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "错误")
		return
	}
	if depositRefund.Status != models.DepositRefundStatusUnconfirmed {
		logger.Error("status not DepositRefundStatusUnconfirmed")
		app.Error(c, http.StatusInternalServerError, err, "错误")
		return
	}

	unreturnedOrders, err := models.IsUserHaveUnreturnedOrders(depositRefund.Uid)
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		//RespJson(c, status.InternalServerError, nil)
		app.Error(c, http.StatusInternalServerError, err, "用户有未完成订单")
		return
	}
	if unreturnedOrders {
		logger.Error("unreturnedOrders")
		app.Error(c, http.StatusInternalServerError, err, "用户有未完成订单")
		return
	}

	userInfo, err := models.GetUserInfoByUid(depositRefund.Uid)
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "错误")
		return
	}
	var transfer *pay.WxTransferResp
	//if userInfo.Deposit == 80 {
	if userInfo.Deposit == 60000 {
		for i := 0; i < 2; i++ {
			transfer, err = pay.Transfer(userInfo.Deposit/2, userInfo.WxOpenID, fmt.Sprintf("押金退款(共2次到账)%d/2", i+1))
			if err != nil {
				logger.Error("err:", logger.Field("err", err))
				app.Error(c, http.StatusInternalServerError, err, "错误")
				return
			}
		}
	} else if userInfo.Deposit == 150000 {
		for i := 0; i < 5; i++ {
			transfer, err = pay.Transfer(userInfo.Deposit/5, userInfo.WxOpenID, fmt.Sprintf("押金退款(共5次到账)%d/5", i+1))
			if err != nil {
				logger.Error("err:", logger.Field("err", err))
				app.Error(c, http.StatusInternalServerError, err, "错误")
				return
			}
		}
	} else {
		transfer, err = pay.Transfer(userInfo.Deposit, userInfo.WxOpenID, "押金退款")
		if err != nil {
			logger.Error("err:", logger.Field("err", err))
			app.Error(c, http.StatusInternalServerError, err, "错误")
			return
		}
	}

	fmt.Println("transfer:", transfer)
	updateUser := map[string]interface{}{
		"deposit":      0,
		"member_level": 1,
	}
	if userInfo.MemberExpire.After(time.Now()) {
		updateUser["member_expire"] = time.Now()
	}
	err = orm.Eloquent.Table("user").Where("uid = ?", userInfo.Uid).Updates(updateUser).Error
	if err != nil {
		logger.Error("update deposit err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "错误")
		return
	}

	err = orm.Eloquent.Table("deposit_refund_record").Where("id = ?", depositRefund.ID).Updates(map[string]interface{}{
		"status":       models.DepositRefundStatusRefunded,
		"confirm_time": time.Now(),
	}).Error
	if err != nil {
		logger.Error("update deposit refund record err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "错误")
		return
	}
	fundRecord := &models.FundRecord{
		Uid:        depositRefund.Uid,
		FundType:   models.FundTypeDepositRefund,
		Amount:     int64(userInfo.Deposit) * (-1),
		OutTradeNo: transfer.PartnerTradeNo,
		PaymentNo:  transfer.PaymentNo,
		Status:     2,
		Remark:     "退还押金",

		//TransactionId: ,
	}
	err = orm.Eloquent.Create(fundRecord).Error
	if err != nil {
		logger.Error("create fund record err:", logger.Field("err", err))
	}
	app.OK(c, nil, "操作成功")
}

func NotarizeUserDepositRefused(c *gin.Context) {
	req := &struct {
		DepositRefundRecordId uint32 `json:"deposit_refund_record_id"`
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	var depositRefund models.DepositRefundRecord
	err := orm.Eloquent.Table("deposit_refund_record").Where("id = ?", req.DepositRefundRecordId).Find(&depositRefund).Error
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "错误")
		return
	}
	if depositRefund.Status != models.DepositRefundStatusUnconfirmed {
		logger.Error("status not DepositRefundStatusUnconfirmed")
		app.Error(c, http.StatusInternalServerError, err, "错误")
		return
	}

	err = orm.Eloquent.Table("deposit_refund_record").Where("id = ?", req.DepositRefundRecordId).Updates(map[string]interface{}{
		"status":       models.DepositRefundStatusRefused,
		"confirm_time": time.Now(),
	}).Error
	if err != nil {
		logger.Error("update deposit refund record err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "错误")
		return
	}

	app.OK(c, nil, "操作成功")
}

// GroupSendMessageCreateTemplateList 查询短信模版列表
// @Summary 短信群发
// @Tags 短信群发, V1.2.0
// @Produce json
// @Accept json
// @Param request body models.GroupSendMessageCreateTemplateListReq true "查询短信模版列表模型"
// @Success 200 {object} models.GroupSendMessageCreateTemplateListResp
// @Router /api/v1/group_send_message/template/list [post]
func GroupSendMessageCreateTemplateList(c *gin.Context) {
	req := &models.GroupSendMessageCreateTemplateListReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	list, err := req.List()
	if err != nil {
		app.Error(c, http.StatusInternalServerError, err, "获取列表错误")
		return
	}

	app.OK(c, list, "操作成功")
}

func GroupSendMessageCreateTemplate(c *gin.Context) {
	req := &models.GroupSendMessageTemplate{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	if req.UserType == 4 && req.Tels == "" {
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "指定用户手机号")
		return
	}

	if req.Message == "" {
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "短信内容不能为空")
		return
	}
	req.Status = 1
	err := orm.Eloquent.Create(req).Error
	if err != nil {
		logger.Errorf("Create GroupSendMessageTemplate err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "模板创建错误")
		return
	}

	app.OK(c, nil, "操作成功")
}

func GroupSendMessageEditTemplate(c *gin.Context) {
	req := &models.GroupSendMessageTemplate{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	if req.Status == 2 { // 已发送的模版不能编辑
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "已发送的短信不能编辑，请重新创建！")
		return
	}

	if req.UserType == 4 && req.Tels == "" {
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "指定用户手机号")
		return
	}

	if req.Message == "" {
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "短信内容不能为空")
		return
	}
	err := orm.Eloquent.Save(req).Error
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "添加文章错误")
		return
	}

	app.OK(c, nil, "操作成功")
}

func GroupSendMessage(c *gin.Context) {
	req := &struct {
		GroupSendMessageTemplateId uint32 `json:"group_send_message_template_id"`
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	var groupMessageTemplate models.GroupSendMessageTemplate
	err := orm.Eloquent.Table("group_send_message_template").Where("id = ?", req.GroupSendMessageTemplateId).Find(&groupMessageTemplate).Error
	if err != nil && err != models.RecordNotFound {
		logger.Errorf("GroupSendMessageTemplate err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "获取模板错误")
		return
	}
	tels := ""
	qs := orm.Eloquent.Table("user")
	switch groupMessageTemplate.UserType {
	case 1:

	case 2:
		qs = qs.Where("member_level IN (2, 3)")
	case 3:
		qs = qs.Where("member_level = 1")
	case 4:
		tels = groupMessageTemplate.Tels
	}
	// 1-所有用户 2-会员 3-非会员
	if tels == "" {
		var users []models.UserInfo
		err := qs.Find(&users).Error
		if err != nil {
			logger.Errorf("users err:", logger.Field("err", err))
			app.Error(c, http.StatusInternalServerError, err, "获取用户错误")
			return
		}
		telList := make([]string, 0)
		for i, _ := range users {
			if users[i].Tel != "" {
				telList = append(telList, users[i].Tel)
			}
		}
		tels = strings.Join(telList, ",")
	}
	if tels == "" {
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "没有要发送的手机号")
		return
	}

	fmt.Println("tels:", tels)
	fmt.Println("Message:", groupMessageTemplate.Message)
	//groupMessageTemplate.Message = "【明慧科技】温馨提示:您的会员即将过期,请在过期之前将卡归还到门店,如有问题联系客服"
	err = models.GtSendMessage(strings.Split(tels, ","), groupMessageTemplate.Message)
	if err != nil {
		logger.Errorf("SmsSend err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "群发消息错误")
		return
	}

	err = orm.Eloquent.Table("group_send_message_template").Where("id = ?", req.GroupSendMessageTemplateId).Updates(map[string]interface{}{
		"status":    2,
		"send_time": time.Now(),
	}).Error
	if err != nil {
		logger.Error("message template send update err:", logger.Field("err", err))
	}

	app.OK(c, nil, "操作成功")
}

func GroupSendMessageCreateTemplateDel(c *gin.Context) {
	req := &struct {
		GroupSendMessageTemplateId uint32 `json:"group_send_message_template_id"`
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	err := orm.Eloquent.Table("group_send_message_template").Where("id = ?", req.GroupSendMessageTemplateId).Delete(&models.GroupSendMessageTemplate{}).Error
	if err != nil {
		logger.Errorf("GroupMessageTemplate del err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "删除错误")
		return
	}

	app.OK(c, nil, "操作成功")
}

func XcxRoleList(c *gin.Context) {
	var xcxRoles []models.XcxRole
	err := orm.Eloquent.Table("xcx_role").Find(&xcxRoles).Error
	if err != nil {
		app.Error(c, http.StatusInternalServerError, err, "获取列表错误")
		return
	}

	app.OK(c, xcxRoles, "")
}

// 升级 1-黄金会员 2-白金会员 3-黑金会员

func UserMemberRecordList(c *gin.Context) {
	req := new(models.UserMemberRecordReq)
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := map[string]interface{}{
		"count":     count,
		"list":      list,
		"pageIndex": req.PageIndex,
	}
	app.OK(c, ret, "")
}

func UserMemberRecordListExport(c *gin.Context) {
	req := new(models.UserMemberRecordReq)
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	url, err := req.Export()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	app.OK(c, url, "")
}

func UserMemberStatisticList(c *gin.Context) {
	req := new(models.MemberStatisticDailyListReq)
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	rsp, err := req.List()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	//ret := map[string]interface{}{
	//	"count":     count,
	//	"list":      list,
	//	"pageIndex": req.PageNum,
	//}
	app.OK(c, rsp, "")
}

func UserInviteRecordList(c *gin.Context) {
	req := new(models.UserInviteRecordReq)
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := map[string]interface{}{
		"count":     count,
		"list":      list,
		"pageIndex": req.PageNum,
	}
	app.OK(c, ret, "")
}

// NewUserInviteRecordList 会员邀请记录
// @Summary 会员邀请记录
// @Tags 会员管理, V1.2.0
// @Produce json
// @Accept json
// @Param request body models.NewUserInviteRecordReq true "会员邀请记录模型"
// @Success 200 {object} models.UserInviteRecordListResp
// @Router /api/v1/user_info/new_user_invite_record_list [post]
func NewUserInviteRecordList(c *gin.Context) {
	req := new(models.NewUserInviteRecordReq)
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	resp, err := req.NewList(c)
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		if err.Error() == "您没有该门店权限" {
			app.Error(c, http.StatusInternalServerError, err, err.Error())
		} else {
			app.Error(c, http.StatusInternalServerError, err, "查询失败")
		}
		return
	}

	app.OK(c, resp, "")
}

func ExpireMemberSmsSendRecordList(c *gin.Context) {
	req := &models.ExpireMemberSmsSendListReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	resp, err := req.List()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	app.OK(c, resp, "")
	return
}

type UserMarkRequest struct {
	Uid  []uint32 `json:"uid"`
	Mark int8     `json:"mark"`
}

func MarkUser(c *gin.Context) {
	var req = new(UserMarkRequest)

	err := c.ShouldBindJSON(req)
	if err != nil || (req.Mark != models.UNMARK && req.Mark != models.MARK) {
		app.Error(c, http.StatusBadRequest, err, "参数错误")
		return
	}

	err = models.MarkUser(req.Uid, req.Mark)
	if err != nil {
		app.Error(c, http.StatusInternalServerError, err, "更新失败")
		return
	}
	app.OK(c, nil, "更新成功")
}

// TelList 查询会员手机号
// @Summary 查询会员手机号
// @Tags 用户信息
// @Produce json
// @Accept json
// @Param request body models.TelListReq true "查询会员手机号模型"
// @Success 200 {object} app.Response
// @Router /api/v1/user_info/tel [post]
func TelList(c *gin.Context) {
	var req = new(models.TelListReq)
	if err := c.ShouldBindJSON(&req); err != nil {
		logger.Error("ShouldBindJSON err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	err := tools.Validate(req) //必填参数校验
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	telListInfo, err := req.GetTelList()
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	app.OK(c, telListInfo, "")
}

// PrivilegeMemberList 零售尊享会员列表
// @Summary 零售尊享会员列表
// @Tags 会员管理, V1.4.2
// @Produce json
// @Accept json
// @Param request body models.PrivilegeMemberListReq true "零售尊享会员列表模型"
// @Success 200 {object} models.PrivilegeMemberListResp
// @Router /api/v1/user_info/privilege_member/list [post]
func PrivilegeMemberList(c *gin.Context) {
	req := new(models.PrivilegeMemberListReq)
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	resp, err := req.PrivilegeMemberList(c)
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		if err.Error() == "您没有该门店权限" {
			app.Error(c, http.StatusInternalServerError, err, err.Error())
		} else {
			app.Error(c, http.StatusInternalServerError, err, "查询失败")
		}
		return
	}

	app.OK(c, resp, "")
}

// ActivateExtendedWarranty 零售尊享会员激活主机延保
// @Summary 零售尊享会员激活主机延保
// @Tags 会员管理, V1.4.2
// @Produce json
// @Accept json
// @Param request body models.ActivateExtendedWarrantyReq true "零售尊享会员激活主机延保模型"
// @Success 200 {object} app.Response
// @Router /api/v1/user_info/privilege_member/activate_extended_warranty [post]
func ActivateExtendedWarranty(c *gin.Context) {
	var req = new(models.ActivateExtendedWarrantyReq)
	if err := c.ShouldBindJSON(&req); err != nil {
		logger.Error("ShouldBindJSON err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	err := tools.Validate(req) //必填参数校验
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	err = req.ActivateExtendedWarranty(c)
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	app.OK(c, nil, "激活成功")
}

// CancelPrivilegeMembers 取消尊享会员
// @Summary 取消尊享会员
// @Tags 会员管理, V1.4.2
// @Produce json
// @Accept json
// @Param request body models.CancelPrivilegeMembersReq true "取消尊享会员模型"
// @Success 200 {object} app.Response
// @Router /api/v1/user_info/privilege_member/cancel_members [post]
func CancelPrivilegeMembers(c *gin.Context) {
	var req = new(models.CancelPrivilegeMembersReq)
	if err := c.ShouldBindJSON(&req); err != nil {
		logger.Error("ShouldBindJSON err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	err := tools.Validate(req) //必填参数校验
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	userInfo, err := req.CancelPrivilegeMembers()
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	app.OK(c, userInfo, "取消成功")
}
