package services

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"io/ioutil"
	"net/http"
	"time"
)

func GetStocksFromVmp(cont context.Context) (err error) {
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go utils.SendAlarmMsg("更新上市公司表失败"+err.Error(), 2)
		}
	}()
	err = models.DelYanxuanSpecialCompany()
	if err != nil {
		fmt.Println("获取上市公司信息失败 Err:%s", err.Error())
		return
	}
	getUrl := "https://vmp.hzinsights.com/v2api/articles/stock"
	result, err := http.Get(getUrl)
	if err != nil {
		return
	}
	defer result.Body.Close()
	body, err := ioutil.ReadAll(result.Body)
	if err != nil {
		fmt.Println("err:" + err.Error())
		return
	}
	fmt.Println(body)
	var resp models.VmpStocks
	err = json.Unmarshal(body, &resp)
	if err != nil {
		fmt.Println("获取上市公司信息失败 Err:%s", err.Error())
		return
	}

	items := make([]*models.CygxYanxuanSpecialCompany, 0)

	for i, _ := range resp.Data {
		items = append(items, &resp.Data[i])
		if len(items) > 5000 {
			err = models.AddCygxYanxuanSpecialCompanyMulti(items)
			if err != nil {
				fmt.Println("AddCygxYanxuanSpecialCompanyMulti Err:%s", err.Error())
				return
			}
			items = []*models.CygxYanxuanSpecialCompany{}
		}
	}

	err = models.AddCygxYanxuanSpecialCompanyMulti(items)
	if err != nil {
		fmt.Println("AddCygxYanxuanSpecialCompanyMulti Err:%s", err.Error())
		return
	}
	return
}

// 记录用户阅读时长
func AddSpecialRecord(user *models.WxUserItem, specialId, stopTime int) (err error) {
	if user.UserId == 0 {
		return
	}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("记录用户阅读时长 失败 AddSpecialRecord Err:"+err.Error(), "userId:", user.UserId, "specialId:", specialId), 2)
		}
	}()
	//校验研选专栏权限，以及无权限的时候的对应状态码
	havePower, e := GetYanxuanSpecialDetailUserPower(user)
	if e != nil {
		err = errors.New("GetYanxuanSpecialDetailUserPower, Err: " + e.Error())
		return
	}

	var permissionCode int
	if havePower {
		permissionCode = 1
	}
	var sellerName string
	//获取销售信息
	sellerName, _, _ = GetSellerName(user)
	if stopTime >= 3 {

		//判断一个用户是否阅读过 某一篇研选专栏
		totalRecord, e := models.GetCygxYanxuanSpecialRecordCountByUser(user.UserId, specialId)
		if e != nil {
			err = errors.New("GetCygxYanxuanSpecialRecordCountByUser, Err: " + e.Error())
			return
		}

		detail, e := models.GetYanxuanSpecialBySpecialId(specialId)
		if e != nil {
			err = errors.New("GetYanxuanSpecialBySpecialId, Err: " + e.Error())
			return
		}

		item := new(models.CygxYanxuanSpecialRecord)
		item.UserId = user.UserId
		item.Mobile = user.Mobile
		item.Email = user.Email
		item.CompanyId = user.CompanyId
		item.CompanyName = user.CompanyName
		item.RealName = user.RealName
		item.SellerName = sellerName
		item.CreateTime = time.Now().Add(-time.Duration(stopTime) * time.Second) // 往前推迟的时间就是他的阅读时间
		item.ModifyTime = time.Now()
		item.RegisterPlatform = utils.REGISTER_PLATFORM
		item.YanxuanSpecialId = specialId
		item.StopTime = stopTime
		item.PermissionCode = permissionCode
		//go CygxRaiServeBillRedisAdd(detail.Title, utils.CYGX_OBJ_YANXUANSPECIAL, user.UserId, user.CompanyId, specialId, utils.REGISTER_PLATFORM, item.CreateTime) // 权益服务统计添加到Redis队列中

		_, e = models.AddCygxYanxuanSpecialRecord(item) // 添加历史记录
		if e != nil {
			err = errors.New("AddCygxYanxuanSpecialRecord, Err: " + e.Error())
			return
		}
		//如果不是弘则研究的人员阅读的，就修改Pv、Uv数量
		if user.CompanyId != utils.HZ_COMPANY_ID {

			//专栏Pv数量进行加一
			e = models.UpdateYanxuanSpecialPv(specialId)
			if e != nil {
				err = errors.New("UpdateYanxuanSpecialPv, Err: " + e.Error())
				return
			}

			//专栏作者Pv数量进行加一
			e = models.UpdateCygxYanxuanSpecialAuthorPv(detail.UserId)
			if e != nil {
				err = errors.New("UpdateCygxYanxuanSpecialAuthorPv, Err: " + e.Error())
				return
			}

			//如果没有阅读过，那么就给专栏文章的UV、作者的UV进行加一
			if totalRecord == 0 {
				e = models.UpdateYanxuanSpecialUv(specialId)
				if e != nil {
					err = errors.New("UpdateYanxuanSpecialUv, Err: " + e.Error())
					return
				}

				//专栏作者Uv数量进行加一
				e = models.UpdateCygxYanxuanSpecialAuthorUv(detail.UserId)
				if e != nil {
					err = errors.New("UpdateCygxYanxuanSpecialAuthorUv, Err: " + e.Error())
					return
				}
			}
		} else {
			//专栏Pv数量进行加一
			e = models.UpdateYanxuanSpecialHzPv(specialId)
			if e != nil {
				err = errors.New("UpdateYanxuanSpecialHzPv, Err: " + e.Error())
				return
			}

			//如果没有阅读过，那么就给专栏文章的UV、作者的UV进行加一
			if totalRecord == 0 {
				e = models.UpdateYanxuanSpecialHzUv(specialId)
				if e != nil {
					err = errors.New("UpdateYanxuanSpecialHzUv, Err: " + e.Error())
					return
				}
			}
		}
	}

	itemLog := new(models.CygxYanxuanSpecialRecordLog)
	itemLog.UserId = user.UserId
	itemLog.Mobile = user.Mobile
	itemLog.Email = user.Email
	itemLog.CompanyId = user.CompanyId
	itemLog.CompanyName = user.CompanyName
	itemLog.RealName = user.RealName
	itemLog.SellerName = sellerName
	itemLog.CreateTime = time.Now().Add(-time.Duration(stopTime) * time.Second) // 往前推迟的时间就是他的阅读时间
	itemLog.ModifyTime = time.Now()
	itemLog.RegisterPlatform = utils.REGISTER_PLATFORM
	itemLog.YanxuanSpecialId = specialId
	itemLog.StopTime = stopTime
	itemLog.PermissionCode = permissionCode
	_, e = models.AddCygxYanxuanSpecialRecordLog(itemLog) // 添加历史记录
	if e != nil {
		err = errors.New("AddCygxYanxuanSpecialRecordLog, Err: " + e.Error())
		return
	}
	return
}

// GetYanxuanSpecialRecordByYanxuanSpecialId 获取研选专栏阅读 pv map
func GetYanxuanSpecialRecordByYanxuanSpecialId(articleIds []int) (mapResp map[int]int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("获取研选专栏阅读，信息失败，GetYanxuanSpecialRecordByYanxuanSpecialId Err："+err.Error(), 3)
		}
	}()
	lenIds := len(articleIds)
	if lenIds == 0 {
		return
	}
	var condition string
	var pars []interface{}
	//condition = ` AND yanxuan_special_id IN (` + utils.GetOrmInReplace(lenIds) + `) `
	//pars = append(pars, articleIds)
	//listPv, e := models.GetCygxYanxuanSpecialRecordListPv(condition, pars)
	//if e != nil {
	//	err = errors.New("GetCygxArticleHistoryRecordNewpvListPvCy, Err: " + e.Error())
	//	return
	//}

	condition += ` AND id  IN (` + utils.GetOrmInReplace(lenIds) + `) `
	pars = append(pars, articleIds)
	listPv, e := models.GetYanxuanSpecialListBycondition(condition, pars, 0, lenIds)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetYanxuanSpecialListBycondition, Err: " + e.Error())
		return
	}

	mapResp = make(map[int]int, 0)
	for _, v := range listPv {
		mapResp[v.Id] = v.Pv + v.HzPv
	}

	return
}
