package services

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

//专门处理活动定时任务相关的业务逻辑

type VmpRobotMeeting struct {
	ModeID            int    `json:"mode_id"`
	PhoneNumber       string `json:"phone_number"`
	MeetingPassword   string `json:"meeting_password"`
	MeetingStartTime  string `json:"meeting_start_time"`
	MeetingTitle      string `json:"meeting_title"`
	MeetingTypeID     int    `json:"meeting_type_id"`
	ParsingMethodID   int    `json:"parsing_method_id"`
	IndustryID        int    `json:"industry_id"`
	FieldID           int    `json:"field_id"`
	Stock             string `json:"stock"`
	Remark            string `json:"remark"`
	ProjectID         int    `json:"project_id"`
	AuthorPhoneNumber int64  `json:"author_phone_number"`
	ExecutionStatusID int    `json:"execution_status_id"`
	ParsingID         int    `json:"parsing_id"`
	SerialNumber      string `json:"serial_number"`
	ChannelID         int    `json:"channel_id"`
	IsActive          int    `json:"is_active"`
}

type VmpRobotMeetingDataResult struct {
	Code int                   `json:"code"`
	Msg  string                `json:"msg"`
	Data VmpRobotMeetingResult `json:"data"`
}

type VmpRobotMeetingResult struct {
	ModeID            int    `json:"mode_id"`
	PhoneNumber       string `json:"phone_number"`
	MeetingPassword   string `json:"meeting_password"`
	MeetingStartTime  string `json:"meeting_start_time"`
	MeetingTitle      string `json:"meeting_title"`
	MeetingTypeID     int    `json:"meeting_type_id"`
	ParsingMethodID   int    `json:"parsing_method_id"`
	IndustryID        int    `json:"industry_id"`
	FieldID           int    `json:"field_id"`
	Stock             string `json:"stock"`
	Remark            string `json:"remark"`
	ProjectID         int    `json:"project_id"`
	AuthorPhoneNumber int64  `json:"author_phone_number"`
	ExecutionStatusID int    `json:"execution_status_id"`
	ParsingID         int    `json:"parsing_id"`
	SerialNumber      string `json:"serial_number"`
	ChannelID         int    `json:"channel_id"`
	IsActive          int    `json:"is_active"`
	VmpRobotMeetinId  int    `json:"id"`
}

//func init() {
//	PushVmpRobotMeeting()
//}

// 研选活动会前15分钟推送给上海那边的机器人
func PushVmpRobotMeeting(cont context.Context) (err error) {
	//func PushVmpRobotMeeting() (err error) {
	defer func() {
		if err != nil {
			//go utils.SendAlarmMsg("15分钟会议消息提醒失败err :"+err.Error(), 2)
			go utils.SendAlarmMsg(fmt.Sprint("研选活动会前15分钟推送给上海那边的机器人失败 PushVmpRobotMeeting Err:", err.Error()), 2)
			//fmt.Println("发送失败，Err:", err.Error())
		}
	}()

	postUrl := "https://vmp.hzinsights.com/v2api/meeting"
	authorization := "bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxNTAwMDEyMzA1NiIsInBob25lX251bWJlciI6IjE1MDAwMTIzMDU2IiwibmFtZSI6IumrmOS6puaWhyIsImVudHJhbmNlIjoicGFzc3d3b3JkIiwiaWF0IjoxNzAzODM1OTc4LCJleHAiOjE3MDM4Mzk1Nzh9.qX6EFkVPn2R0SqIQXJ4tyub--iiqKqrJnz9lbdcVetw"
	var condition string
	var pars []interface{}
	endDate := time.Now().Add(+time.Minute * 15).Format(utils.FormatDateTime)
	condition = ` AND activity_time <= ? AND activity_time >= NOW()  AND  publish_status = 1  AND   chart_permission_id  = ? AND  vmp_robot_meeting_id = 0 AND active_state = 1  AND  mainland_tell != ''  `
	pars = append(pars, endDate, utils.CHART_PERMISSION_ID_YANXUAN)
	listActivity, e := models.GetCygxActivityList(condition, pars, 0, 10)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivityList, Err: " + e.Error())
		return
	}
	//fmt.Println(len(listActivity))

	//return
	if len(listActivity) == 0 {
		return
	}
	for _, v := range listActivity {
		item := new(VmpRobotMeeting)
		item.ModeID = 2
		item.PhoneNumber = utils.GetArabicNumbers(v.MainlandTell)
		item.MeetingPassword = utils.GetArabicNumbers(v.ParticipationCode) + "#" // 业务需求，必须带有一个#
		item.MeetingStartTime = v.ActivityTime
		item.MeetingTitle = v.ActivityName
		item.MeetingTypeID = 1
		item.ParsingMethodID = 0
		item.IndustryID = 13
		item.FieldID = 0
		item.Stock = ""
		item.Remark = v.Remarks // 处理HTML格式样式
		item.ProjectID = 1
		item.AuthorPhoneNumber = 15000123056 // 高亦文 手机号
		item.ExecutionStatusID = 0
		item.ParsingID = 0
		item.SerialNumber = ""
		item.ChannelID = -1
		item.IsActive = 1
		jsonBody, e := json.Marshal(item)
		if e != nil {
			err = errors.New("json.Marshal, Err: " + e.Error())
			fmt.Println("json.Marshal Err:" + err.Error())
			return
		}
		//fmt.Println(item)
		//return
		tr := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
		client := &http.Client{Transport: tr}
		req, e := http.NewRequest("POST", postUrl, strings.NewReader(string(jsonBody)))
		if e != nil {
			err = e
			return
		}
		req.Header.Set("Content-Type", "application/json")
		req.Header.Set("Authorization", authorization)
		resp, e := client.Do(req)
		if e != nil {
			err = errors.New("client.Do Err: " + e.Error())
			fmt.Println("client.Do Err:" + err.Error())
			return
		}
		//fmt.Println(resp)
		defer resp.Body.Close()
		body, e := ioutil.ReadAll(resp.Body)
		if e != nil {
			fmt.Println("err:" + err.Error())
			err = e
			return
		}
		result := new(VmpRobotMeetingDataResult)
		e = json.Unmarshal(body, &result)
		if e != nil {
			fmt.Println(" json.Unmarshal Err:" + err.Error())
			err = errors.New("json.Unmarshal Err: " + e.Error())
			return
		}
		vmpRobotMeetinId := result.Data.VmpRobotMeetinId
		e = models.UpdateActivityVmpRobotMeetingId(vmpRobotMeetinId, v.ActivityId)
		if e != nil {
			fmt.Println("UpdateActivityVmpRobotMeetingId  Err:" + err.Error())
			err = errors.New("UpdateActivityVmpRobotMeetingId  Err: " + e.Error())
			return
		}
		itemlog := new(models.CygxShanghaiCompanyLog)
		itemlog.CreateTime = time.Now()
		itemlog.Url = postUrl
		itemlog.Body = string(jsonBody)
		itemlog.Result = string(body)
		go models.AddCygxShanghaiCompanyLog(itemlog)
	}

	return
}
