package dyjx

import (
	"dysy/apis"
	"dysy/models"
	"dysy/models/mysql"
	"dysy/tools"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/asmcos/requests"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func DouYinUrlJieXi(c *gin.Context) {
	//前端给端视频连接
	var inData models.DyJieXiInput
	var outData models.DyJieXiOutput

	err := c.ShouldBindJSON(&inData)
	if err != nil {
		outData.Code = apis.Code400
		outData.Message = apis.InputFail
		c.JSON(http.StatusOK, outData)
		return
	}

	err, outData = DeWater(inData)
	if err != nil {
		outData.Code = apis.Code500
		outData.Message = err.Error()
		c.JSON(http.StatusOK, outData)
		return
	}
	outData.Code = apis.Code200
	outData.Message = apis.Success
	c.JSON(http.StatusOK, outData)

}

func DeWater(in models.DyJieXiInput) (error, models.DyJieXiOutput) {
	var out models.DyJieXiOutput
	var dysy mysql.DysyUrlInfo
	var p []byte

	str := ""
	baseHost := in.Url
	client := &http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}

	res, err := client.Get(baseHost)
	if err != nil {
		fmt.Print(err.Error())
		return errors.New(apis.ClientGetFail), out
	}

	n, err := res.Body.Read(p)
	fmt.Println("n=", n)
	str = res.Header.Get("Location")
	fmt.Println("res.Body = ", string(p))
	fmt.Print("str = ", str)

	comma := strings.Index(str, "/video/")
	pos := strings.Index(str, "/?")
	//fmt.Println(comma, pos, str[comma+7:pos])

	var inData models.DyJieXi
	baseHost = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=" + str[comma+7:pos]
	//fmt.Println("baseHost = ", baseHost)
	req := requests.Requests()
	resp, err := req.Get(baseHost)

	if err != nil {
		return errors.New(apis.RedirectUrlFail), out
	}

	err = json.Unmarshal([]byte(resp.Text()), &inData)
	if err != nil {
		return errors.New(apis.JsonUnmarshalFail), out
		//fmt.Println()
	}

	//视频url
	var videoUrl = inData.ItemList[0].Video.PlayAddr.URLList[0]

	out.Data.VideoUrl = strings.Replace(videoUrl, "playwm", "play", 1)
	//音频url

	out.Data.AudioUrl = inData.ItemList[0].Music.PlayURL.URI

	out.Data.VideoPic = inData.ItemList[0].Video.DynamicCover.URLList[0]

	out.Data.Desc = inData.ItemList[0].Desc

	//数据库创建记录
	dysy.Desc = out.Data.Desc
	dysy.VideoPic = out.Data.VideoPic
	dysy.AudioURL = out.Data.AudioUrl
	dysy.DouYinShortURL = in.Url
	dysy.DeWaterVideoURL = out.Data.VideoUrl
	dysy.DouYinBaseHost = baseHost
	dysy.Number = 1
	dysy.UpdateTime = tools.GetCurrntTimeStr()
	dysy.CreateTime = tools.GetCurrntTimeStr()
	dysy.Create(dysy.DeWaterVideoURL)

	fmt.Println("out.Data.VideoUrl = ", out.Data.VideoUrl)

	//client1 := &http.Client{
	//	CheckRedirect: func(req *http.Request, via []*http.Request) error {
	//		return http.ErrUseLastResponse
	//	},
	//}
	//request.Header.Set("User-Agent", "Mozilla/5.0 (Linux; Android 6.0.1; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Mobile Safari/537.36") //刚才找到的浏览器中User-agent

	//client.Head()

	//return nil, out

	//res1, err := client1.Get(out.Data.VideoUrl)
	//if err != nil {
	//	fmt.Print(err.Error())
	//	return errors.New(apis.ClientGetFail), out
	//}
	//
	//ss, err := ioutil.ReadAll(res1.Body)
	request1, err := http.NewRequest("GET", out.Data.VideoUrl, nil)
	if err != nil {
		fmt.Print(err.Error())
	}

	client1 := &http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}
	request1.Header.Set("User-Agent", "Mozilla/5.0 (Linux; Android 6.0.1; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Mobile Safari/537.36") //刚才找到的浏览器中User-agent
	response, err := client1.Do(request1)

	if err != nil {
		fmt.Print("err = ", err.Error())
	}
	loc := response.Header.Get("location")
	if loc != "" {
		out.Data.VideoUrl = loc
	} else {
		return errors.New("location error"), out
	}
	fmt.Print("body = ", response.StatusCode)
	fmt.Print("loc =", response.Header.Get("location"))
	//if response.StatusCode == 200 {
	//	body, _ := ioutil.ReadAll(response.Body)
	//	_ = string(body)
	//	//fmt.Print("body", bodystr)
	//}
	//
	//fmt.Print("body = ", response.StatusCode)

	//fmt.Println("ss = ", string(ss))
	//videoStr := string(ss)
	//截取字符串
	//comma = strings.Index(videoStr, "\"")
	//pos = strings.Index(videoStr[comma+1:], "\">")

	//fmt.Println(videoStr[comma+1 : pos+comma+1])
	out.Data.VideoUrl = strings.Replace(out.Data.VideoUrl, "http", "https", 1)
	//out.Data.VideoUrl = out.Data.VideoUrl + ".mp4"

	//截取
	comma = strings.Index(out.Data.VideoUrl, "https://")
	pos = strings.Index(out.Data.VideoUrl[comma+1:], ".com")
	//fmt.Println(out.Data.VideoUrl[comma : pos+comma+4+1])
	var twoUrl mysql.DysyTwoUrl
	twoUrl.CreateTime = tools.GetCurrntTimeStr()
	twoUrl.UpdateTime = tools.GetCurrntTimeStr()
	twoUrl.TwoURL = out.Data.VideoUrl[comma:pos+comma+4+1] + ";"
	twoUrl.Number = 1
	twoUrl.Create(twoUrl.TwoURL)

	return nil, out

}

func ubaRequestHeader(body string) (header requests.Header, err error) {

	// 正确返回
	return requests.Header{
		"Content-Type": "text/html; charset=utf-8",
		"User-Agent":   "Mozilla/5.0 (Linux; Android 9.0; Z832 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Mobile Safari/537.36",
	}, nil

}