package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"github.com/go-sql-driver/mysql"
	"io/ioutil"
	"log"
	"net/http"
	"reflect"
	"strconv"
	"strings"
	"time"
)

var db *sql.DB

func getDate(time string) string {
	date, _, _ := strings.Cut(time, " ")
	return date
}
func getDB() *sql.DB {

	if db != nil {
		return db
	}
	cfg := mysql.Config{
		User:                 "application",
		Passwd:               "DzORXVx5sr6f&W",
		Net:                  "tcp",
		Addr:                 "52.8.176.243:4000",
		DBName:               "jirainterval",
		AllowNativePasswords: true,
	}
	db, err := sql.Open("mysql", cfg.FormatDSN())
	if err != nil {
		panic(err)
	}
	// See "Important settings" section.
	db.SetConnMaxLifetime(time.Minute)
	db.SetMaxOpenConns(10)
	db.SetMaxIdleConns(100)

	return db
}

type StatusCategory struct {
	Id   int
	Name string
}

type Status struct {
	StatusCategory *StatusCategory
}

type Creator struct {
	Name string
}

type Priority struct {
	Name string
}

type Reporter struct {
	Name string
}

type Assignee struct {
	Name string
}

type Issuetype struct {
	Name string
}

type Components struct {
	Name string
}

type Token2 struct {
	Created           string
	Updated           string
	Resolutiondate    string
	Status            *Status
	Creator           *Creator
	Priority          *Priority //嵌套json
	Summary           string
	Reporter          *Reporter
	Assignee          *Assignee
	Description       string
	Issuetype         *Issuetype
	Components        []*Components
	Customfield_12816 string //1
	Customfield_12819 string //1
	Customfield_10615 string //2
	Customfield_10321 string //1
	Customfield_10635 string //2
}

type Token struct {
	Id     string
	Key    string
	Fields *Token2
}

type Actress struct {
	Total  int
	Issues []*Token
}

type Author struct {
	Name string
}

//action结构体
type Tokenact struct {
	Id      string
	Author  *Author
	Body    string
	Created string
	Updated string
}

type ActressAction struct {
	Total    int
	Comments []*Tokenact
}
type Items struct {
	Field string //只需要找=status
	From  string //变化前的状态
	To    string
}

type Histories struct {
	Created string
	Items   []*Items
}

//type Changelog struct {
//	Histories []*Histories
//}

type Token3 struct {
	Total     int
	Histories []*Histories
}

type ActressIssue struct {
	Changelog *Token3
}

//issue结构体
type Tokenissue struct {
	Created        string
	Updated        string
	Resolutiondate string
	Status         *Status
	Creator        *Creator
	Priority       *Priority //嵌套json
	Summary        string
	Reporter       *Reporter
	Assignee       *Assignee
	Description    string
	Issuetype      *Issuetype
	Components     []*Components
	//Customfield_12816 string//1
	//Customfield_12819 string//1
	//Customfield_10615 string//2
}

type Tokeni struct {
	Id     string
	Key    string
	Fields *Tokenissue
}
type Tokenob struct {
	Title string
}

type Tokentitle struct {
	Id     int
	Object *Tokenob
}

func jira(flag int, start string, end string, fullflag int) {

	//var issue_id string = "80737"
	//url := "https://internal.pingcap.net/jira/rest/api/2/issue/" + issue_id

	//url := "https://internal.pingcap.net/jira/rest/api/2/search/" //1
	//url := "https://jira.tidbcloud.com/rest/api/2/search/" //2
	var url string
	var projectid string
	if flag == 1 {
		url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
		projectid = "11101"                                          //1

	} else if flag == 2 {
		url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		projectid = "10417"                                   //2
	} else {
		url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		projectid = "10415"                                   //2
	}
	//var val = engineer_name
	//var projectid string = "11101" //1
	//var projectid string = "10417" //2
	var payload *strings.Reader
	if fullflag == 1 {
		payload = strings.NewReader("{\n  \"jql\": \"created >= '2022/04/01'and created <'2022/07/19' and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")

	} else {
		payload = strings.NewReader("{\n  \"jql\": \"created >=" + "'" + start + "'" + " and created <" + "'" + end + "'" + " and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")

	}
	//payload := strings.NewReader("{\n  \"user\": {\n    \"type\": \"user\",\n    \"name\": \"Earline Greenholt\",\n    \"email\": \"125.greenholt.earline@graham.name\",\n    \"time_zone\": \"America/Lima\",\n    \"color\": \"green\",\n    \"role\": \"admin\",\n    \"job_title\": \"Director of Engineering\",\n    \"avatar_url\": \"https://secure.gravatar.com/avatar/1d1a39d4635208d5664082a6c654a73f.png?d=mm&r=PG\",\n    \"description\": \"I'm the boss\"\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Content-Type", "application/json")
	//req.Header.Add("Accept", "application/vnd.pagerduty+json;version=2")
	//req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1
	//req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2
	if flag == 1 {
		req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1
	} else {
		req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2
	}
	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close() //修改信息
	body, _ := ioutil.ReadAll(res.Body)
	var actress Actress
	//fmt.Println(res)
	//fmt.Println(string(body))
	err := json.Unmarshal(body, &actress)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("长度：%s\n", actress.Total)
	//token := actress.Issues[2]
	var tmpcreator string
	var tmpUpdated string
	var tmpResolutiondate string
	var tmpStatusId int
	var tmpCreatorName string
	var tmpCPriorityName string
	var tmpid string
	var tmpKey string
	var tmpReporter string
	var tmpAssignee string
	var tmpSummary string
	var tmpDescription string
	var tmpType string
	var tmpStatusName string

	//Updated        string
	//Resolutiondate string
	//Status         *Status
	//Creator        *Creator
	//Priority       *Priority //嵌套json
	dbb1 := getDB()
	for i := 0; i < actress.Total; i++ {
		tmpcreator = actress.Issues[i].Fields.Created
		tmpUpdated = actress.Issues[i].Fields.Updated
		tmpResolutiondate = actress.Issues[i].Fields.Resolutiondate
		tmpStatusId = actress.Issues[i].Fields.Status.StatusCategory.Id
		tmpCreatorName = actress.Issues[i].Fields.Creator.Name
		tmpCPriorityName = actress.Issues[i].Fields.Priority.Name
		tmpid = actress.Issues[i].Id

		tmpKey = actress.Issues[i].Key
		tmpReporter = actress.Issues[i].Fields.Reporter.Name
		if actress.Issues[i].Fields.Assignee == nil {
			tmpAssignee = ""
		} else {
			tmpAssignee = actress.Issues[i].Fields.Assignee.Name
		}
		tmpSummary = actress.Issues[i].Fields.Summary
		tmpDescription = actress.Issues[i].Fields.Description
		tmpType = actress.Issues[i].Fields.Issuetype.Name
		tmpStatusName = actress.Issues[i].Fields.Status.StatusCategory.Name

		rs := []rune(tmpDescription)

		var lenn int
		if len(rs) > 1000 {
			lenn = 1000
		} else {
			lenn = len(rs)
		}
		//if tmpid == "81838" || tmpid == "81615" {
		if tmpResolutiondate != "" {
			//getDB().Query("insert into jira_issueview values (?,?,null ,?,?,?,?,?,1,?,?,?,?,?,?); ", tmpid, tmpCreatorName, tmpCPriorityName, tmpStatusId, tmpcreator, tmpUpdated, tmpResolutiondate,projectid,tmpReporter,tmpAssignee,tmpSummary,tmpDescription,tmpKey)

			sqlStr := "insert into jira_issueview values (?,?,? ,?,?,?,?,?,1,?,?,?,?,?,?,?,null,null,null,null,null,null,null,null,null,null,null);"
			res, err := dbb1.Exec(sqlStr, tmpid, tmpCreatorName, tmpType, tmpCPriorityName, tmpStatusId, tmpcreator, tmpUpdated, tmpResolutiondate, projectid, tmpReporter, tmpAssignee, tmpSummary, string(rs[:lenn]), tmpKey, tmpStatusName)
			if err != nil {
				fmt.Println("res fail: ", err)
				return
			}
			id, err := res.LastInsertId()
			if err != nil {
				fmt.Printf("lastInsertId fail: %s", err)
			}
			fmt.Printf("id: %d insert success!", id)
			//if err != nil {
			//	panic(err)
			//} //清除修改
			//defer rows0.Close()
		} else {
			//getDB().Query("insert into jira_issueview values (?,?,null ,?,?,?,?,null,1,?,?,?,?,?,? ); ", tmpid, tmpCreatorName, tmpCPriorityName, tmpStatusId, tmpcreator, tmpUpdated,projectid,tmpReporter,tmpAssignee,tmpSummary,tmpDescription,tmpKey)

			sqlStr := "insert into jira_issueview values (?,?,?,?,?,?,?,null,1,?,?,?,?,?,?,?,null,null,null,null,null,null,null,null,null,null,null ); "
			res, err := dbb1.Exec(sqlStr, tmpid, tmpCreatorName, tmpType, tmpCPriorityName, tmpStatusId, tmpcreator, tmpUpdated, projectid, tmpReporter, tmpAssignee, tmpSummary, string(rs[:lenn]), tmpKey, tmpStatusName)
			if err != nil {
				fmt.Println("res fail: ", err)
				return
			}
			id, err := res.LastInsertId()
			if err != nil {
				fmt.Printf("lastInsertId fail: %s", err)
			}
			fmt.Printf("id: %d insert success!", id)
			//if err != nil {
			//	panic(err)
			//} //清除修改
			//defer rows0.Close()
		}
	}

	//}tmpid

	//var lenn = actress.Issues.en

	//getDB()
	//rows0, err := getDB().Query("UPDATE page_oncall set is_change=0")
	//if err != nil {
	//	panic(err)
	//} //清除修改
	//defer rows0.Close()
}

func jiraaction(flag int) {
	dbb := getDB()
	var url string
	var projectid string
	//if flag == 1 {
	//	//url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
	//	projectid = "11101" //1
	//
	//} else {
	//	//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
	//	projectid = "10417" //2
	//}

	if flag == 1 {
		//url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
		projectid = "11101" //1

	} else if flag == 2 {
		//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		projectid = "10417" //2
	} else {
		//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		projectid = "10415" //2
	}
	rows01, err := dbb.Query("SELECT id FROM jira_issueview where flag=1 and project_id=?", projectid)
	if err != nil {
		panic(err)
	}
	defer rows01.Close()
	for rows01.Next() {
		var issueid string

		err := rows01.Scan(&issueid)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(issueid + ",")
		//var issue_id string = "80737"
		if flag == 1 {
			url = "https://internal.pingcap.net/jira/rest/api/2/issue/" + issueid + "/comment" //1
		} else {
			url = "https://jira.tidbcloud.com/rest/api/2/issue/" + issueid + "/comment" //2
		}
		//url := "https://internal.pingcap.net/jira/rest/api/2/issue/" + issueid + "/comment" //1
		//url := "https://jira.tidbcloud.com/rest/api/2/issue/" + issueid + "/comment" //2
		//var val = engineer_name
		//payload := strings.NewReader("{\n   \"maxResults\": \"500\"\n }")
		//payload := strings.NewReader("{\n  \"user\": {\n    \"type\": \"user\",\n    \"name\": \"Earline Greenholt\",\n    \"email\": \"125.greenholt.earline@graham.name\",\n    \"time_zone\": \"America/Lima\",\n    \"color\": \"green\",\n    \"role\": \"admin\",\n    \"job_title\": \"Director of Engineering\",\n    \"avatar_url\": \"https://secure.gravatar.com/avatar/1d1a39d4635208d5664082a6c654a73f.png?d=mm&r=PG\",\n    \"description\": \"I'm the boss\"\n  }\n}")

		req, _ := http.NewRequest("GET", url, nil)

		req.Header.Add("Content-Type", "application/json")
		//req.Header.Add("Accept", "application/vnd.pagerduty+json;version=2")
		//req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1
		req.Header.Add("User-Agent", "PostmanRuntime/7.26.8") //1
		//req.Header.Add("Cookie", "JSESSIONID=C0EDF4B0189B1AA1F543B168CE7C205D; atlassian.xsrf.token=BB4Z-TISO-454F-I1QU_bdf4f5d06bd1419d9b905b54730e4ea1138bf90e_lin") //1
		//req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2
		if flag == 1 {
			req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1
		} else {
			req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2
		}
		res, _ := http.DefaultClient.Do(req)

		defer res.Body.Close() //修改信息
		body, _ := ioutil.ReadAll(res.Body)
		var actressAction ActressAction
		//fmt.Println(res)
		//fmt.Println(string(body))
		err2 := json.Unmarshal(body, &actressAction)
		if err2 != nil {
			fmt.Println("error:", err2)
			return
		}
		fmt.Printf("长度：%s\n", actressAction.Total)
		//token := actress.Issues[2]
		//var tmpcreator string
		//var tmpUpdated string
		//var tmpResolutiondate string
		//var tmpStatusId int
		//var tmpCreatorName string
		//var tmpCPriorityName string
		var tmpid string
		var tmpAuthor string
		var tmpBody string
		var tmpcreated string
		var tmpUpdated string
		dbb2 := getDB()
		for i := 0; i < actressAction.Total; i++ {
			//db.Close()
			//getDB().Close()
			tmpid = actressAction.Comments[i].Id
			tmpAuthor = actressAction.Comments[i].Author.Name
			tmpBody = actressAction.Comments[i].Body
			rs := []rune(tmpBody)

			var lenn int
			if len(rs) > 1000 {
				lenn = 1000
			} else {
				lenn = len(rs)
			}
			tmpcreated = actressAction.Comments[i].Created
			tmpUpdated = actressAction.Comments[i].Updated
			if tmpUpdated != "" {
				sqlStr := "insert into jira_actionview values (?,?,?,?,?,?,null,?);" //注意修改project_id
				res, err := dbb2.Exec(sqlStr, tmpid, issueid, tmpAuthor, string(rs[:lenn]), tmpcreated, tmpUpdated, projectid)
				if err != nil {
					fmt.Println("res fail: ", err)
					return
				}
				id, err := res.LastInsertId()
				if err != nil {
					fmt.Printf("lastInsertId fail: %s", err)
				}
				fmt.Printf("id: %d insert success!", id)

				//rows1a, err := dbb2.Query("insert into jira_actionview values (?,?,?,?,?,?,null); ", tmpid, issueid, tmpAuthor, tmpBody, tmpcreated, tmpUpdated)
				//if err != nil {
				//	panic(err)
				//} //清除修改
				//defer rows1a.Close()
			} else {
				rows1b, err := dbb2.Query("insert into jira_actionview values (?,?,?,?,?,null,null,? ); ", tmpid, issueid, tmpAuthor, tmpBody, tmpcreated, projectid)
				if err != nil {
					panic(err)
				} //清除修改
				defer rows1b.Close()
			}
			//time.Sleep(3 * time.Second)
		}

	}
}

func jiraday() {
	dbb := getDB()
	var project_id string
	//project_id = "11101"
	project_id = "10000"
	rows01, err := dbb.Query("SELECT  id,date_sub(date_format(date,'%Y-%m-%d'),interval 2 day) FROM jira_board_day where project_id=?", project_id)
	if err != nil {
		panic(err)
	}
	defer rows01.Close()
	for rows01.Next() {

		var board_id int
		var board_day string

		err := rows01.Scan(&board_id, &board_day)
		if err != nil {
			log.Fatal(err)
		}
		rows02, err2 := dbb.Query("SELECT COUNT(*) FROM jira_issueview WHERE project_id=? and date_format(created_time,'%Y-%m-%d') = ? ", project_id, board_day)
		if err2 != nil {
			panic(err2)
		}
		defer rows02.Close()
		var board_day2_all string
		for rows02.Next() {

			err3 := rows02.Scan(&board_day2_all)
			if err3 != nil {
				log.Fatal(err3)
			}

		}
		rows03, err4 := dbb.Query("SELECT COUNT(id) FROM (SELECT id,created_time,resolution_date,case when resolution_date is not null then timestampdiff(HOUR,created_time,resolution_date) end time_diff FROM jira_issueview WHERE project_id=? and date_format(created_time,'%Y-%m-%d') = ?  ) AS tmp_res_date WHERE time_diff<24", project_id, board_day)
		if err4 != nil {
			panic(err4)
		}
		defer rows03.Close()
		var board_day2_res string
		for rows03.Next() {

			err5 := rows03.Scan(&board_day2_res)
			if err5 != nil {
				log.Fatal(err5)
			}

		}
		sqlStr := "UPDATE jira_board_day SET all_issue=?,res_issue=? WHERE id=? "
		res, err := dbb.Exec(sqlStr, board_day2_all, board_day2_res, board_id)
		if err != nil {
			fmt.Println("res fail: ", err)
			return
		}
		id, err := res.LastInsertId()
		if err != nil {
			fmt.Printf("lastInsertId fail: %s", err)
		}
		fmt.Printf("id: %d insert success!", id)

	}
}

func test() {
	dbb1 := getDB()
	for i := 0; i < 92; i++ {
		sqlStr := "INSERT INTO jira_board_day (date,all_issue,res_issue,project_id,flag) SELECT DATE_ADD(date,INTERVAL 1 DAY) ,null,null,11101,1 FROM jira_board_day WHERE project_id=11101 and flag=1 ORDER BY date DESC LIMIT 1"
		res, err := dbb1.Exec(sqlStr)
		if err != nil {
			fmt.Println("res fail: ", err)
			return
		}
		id, err := res.LastInsertId()
		if err != nil {
			fmt.Printf("lastInsertId fail: %s", err)
		}
		fmt.Printf("id: %d insert success!", id)
	}
}

func jiraUpdateComponent(flag int, start string, end string, fullflag int) {

	//var issue_id string = "80737"
	//url := "https://internal.pingcap.net/jira/rest/api/2/issue/" + issue_id

	//url := "https://internal.pingcap.net/jira/rest/api/2/search/" //1
	//url := "https://jira.tidbcloud.com/rest/api/2/search/" //2

	//var val = engineer_name
	//var projectid string = "11101" //1
	//var projectid string = "10417" //2

	var url string
	var projectid string
	if flag == 1 {
		url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
		projectid = "11101"                                          //1

	} else if flag == 2 {
		url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		projectid = "10417"                                   //2
	} else {
		url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		projectid = "10415"                                   //2
	}

	var payload *strings.Reader
	if fullflag == 1 {
		payload = strings.NewReader("{\n  \"jql\": \"created >= '2022/04/01'and created <'2022/07/19' and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")

	} else {
		payload = strings.NewReader("{\n  \"jql\": \"created >=" + "'" + start + "'" + " and created <" + "'" + end + "'" + " and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")

	}
	//payload := strings.NewReader("{\n  \"jql\": \"created >=" + start + " and created <" + end + " and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")
	//payload := strings.NewReader("{\n  \"jql\": \"created >= '2022/07/04'and created <'2022/07/14' and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")

	//payload := strings.NewReader("{\n  \"user\": {\n    \"type\": \"user\",\n    \"name\": \"Earline Greenholt\",\n    \"email\": \"125.greenholt.earline@graham.name\",\n    \"time_zone\": \"America/Lima\",\n    \"color\": \"green\",\n    \"role\": \"admin\",\n    \"job_title\": \"Director of Engineering\",\n    \"avatar_url\": \"https://secure.gravatar.com/avatar/1d1a39d4635208d5664082a6c654a73f.png?d=mm&r=PG\",\n    \"description\": \"I'm the boss\"\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Content-Type", "application/json")
	//req.Header.Add("Accept", "application/vnd.pagerduty+json;version=2")
	//req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1
	//req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2
	if flag == 1 {
		req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1
	} else {
		req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2
	}
	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close() //修改信息
	body, _ := ioutil.ReadAll(res.Body)
	var actress Actress
	//fmt.Println(res)
	//fmt.Println(string(body))
	err := json.Unmarshal(body, &actress)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("长度：%s\n", actress.Total)
	//token := actress.Issues[2]
	//var tmpcreator string
	//var tmpUpdated string
	//var tmpResolutiondate string
	//var tmpStatusId int
	//var tmpCreatorName string
	//var tmpCPriorityName string
	var tmpid string
	//var tmpKey string
	//var tmpReporter string
	//var tmpAssignee string
	//var tmpSummary string
	//var tmpDescription string
	//var tmpType string
	//var tmpStatusName string
	var tmpComponents string

	//var tmpid string
	//Updated        string
	//Resolutiondate string
	//Status         *Status
	//Creator        *Creator
	//Priority       *Priority //嵌套json
	dbb1 := getDB()
	for i := 0; i < actress.Total; i++ {
		//tmpcreator = actress.Issues[i].Fields.Created
		//tmpUpdated = actress.Issues[i].Fields.Updated
		//tmpResolutiondate = actress.Issues[i].Fields.Resolutiondate
		//tmpStatusId = actress.Issues[i].Fields.Status.StatusCategory.Id
		//tmpCreatorName = actress.Issues[i].Fields.Creator.Name
		//tmpCPriorityName = actress.Issues[i].Fields.Priority.Name
		tmpid = actress.Issues[i].Id
		if len(actress.Issues[i].Fields.Components) == 0 {
			tmpComponents = ""
		} else {
			tmpComponents = actress.Issues[i].Fields.Components[0].Name
		}

		//tmpKey = actress.Issues[i].Key
		//tmpReporter = actress.Issues[i].Fields.Reporter.Name
		//if actress.Issues[i].Fields.Assignee == nil {
		//	tmpAssignee = ""
		//} else {
		//	tmpAssignee = actress.Issues[i].Fields.Assignee.Name
		//}
		//tmpSummary = actress.Issues[i].Fields.Summary
		//tmpDescription = actress.Issues[i].Fields.Description
		//tmpType = actress.Issues[i].Fields.Issuetype.Name
		//tmpStatusName = actress.Issues[i].Fields.Status.StatusCategory.Name
		sqlStr := "UPDATE jira_issueview set component=? WHERE id=? and flag=1"

		res, err := dbb1.Exec(sqlStr, tmpComponents, tmpid)
		if err != nil {
			fmt.Println("res fail: ", err)
			return
		}
		id, err := res.LastInsertId()
		if err != nil {
			fmt.Printf("lastInsertId fail: %s", err)
		}
		fmt.Printf("id: %d insert success!", id)

	}

}

func jiraUpdateCode(flag int, start string, end string, fullflag int) {
	//cloud的字段为Customfield_10615，interval的字段有两个，需要string相加处理，Customfield_12816+Customfield_12819
	//调用不同的地方，需要对struct结构体字段进行调整

	//var issue_id string = "80737"
	//url := "https://internal.pingcap.net/jira/rest/api/2/issue/" + issue_id

	//url := "https://internal.pingcap.net/jira/rest/api/2/search/" //1
	//url := "https://jira.tidbcloud.com/rest/api/2/search/" //2

	//var val = engineer_name
	//var projectid string = "11101" //1
	//var projectid string = "10417" //2
	var url string
	var projectid string
	if flag == 1 {
		url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
		projectid = "11101"                                          //1

	} else if flag == 2 {
		url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		projectid = "10417"                                   //2
	} else {
		url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		projectid = "10415"                                   //2
	}
	//if flag == 1 {
	//	url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
	//	projectid = "11101"                                          //1
	//
	//} else {
	//	url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
	//	projectid = "10417"                                   //2
	//}
	var payload *strings.Reader
	if fullflag == 1 {
		payload = strings.NewReader("{\n  \"jql\": \"created >= '2022/04/01'and created <'2022/07/19' and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")

	} else {
		payload = strings.NewReader("{\n  \"jql\": \"created >=" + "'" + start + "'" + " and created <" + "'" + end + "'" + " and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")

	}
	//payload := strings.NewReader("{\n  \"jql\": \"created >=" + start + " and created <" + end + " and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")
	//payload := strings.NewReader("{\n  \"jql\": \"created >= '2022/07/04'and created <'2022/07/14' and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")
	//payload := strings.NewReader("{\n  \"user\": {\n    \"type\": \"user\",\n    \"name\": \"Earline Greenholt\",\n    \"email\": \"125.greenholt.earline@graham.name\",\n    \"time_zone\": \"America/Lima\",\n    \"color\": \"green\",\n    \"role\": \"admin\",\n    \"job_title\": \"Director of Engineering\",\n    \"avatar_url\": \"https://secure.gravatar.com/avatar/1d1a39d4635208d5664082a6c654a73f.png?d=mm&r=PG\",\n    \"description\": \"I'm the boss\"\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Content-Type", "application/json")
	//req.Header.Add("Accept", "application/vnd.pagerduty+json;version=2")
	//req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1
	//req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2
	if flag == 1 {
		req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1
	} else {
		req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2
	}
	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close() //修改信息
	body, _ := ioutil.ReadAll(res.Body)
	var actress Actress
	//fmt.Println(res)
	//fmt.Println(string(body))
	err := json.Unmarshal(body, &actress)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("长度：%s\n", actress.Total)
	//token := actress.Issues[2]
	//var tmpcreator string
	//var tmpUpdated string
	//var tmpResolutiondate string
	//var tmpStatusId int
	//var tmpCreatorName string
	//var tmpCPriorityName string
	var tmpid string

	var tmpTenantid string //cloud
	//var tmpTenantid1 string //interval
	//var tmpTenantid2 string //interval

	dbb1 := getDB()
	for i := 0; i < actress.Total; i++ {
		//tmpcreator = actress.Issues[i].Fields.Created
		//tmpUpdated = actress.Issues[i].Fields.Updated
		//tmpResolutiondate = actress.Issues[i].Fields.Resolutiondate
		//tmpStatusId = actress.Issues[i].Fields.Status.StatusCategory.Id
		//tmpCreatorName = actress.Issues[i].Fields.Creator.Name
		//tmpCPriorityName = actress.Issues[i].Fields.Priority.Name
		tmpid = actress.Issues[i].Id
		//if len(actress.Issues[i].Fields.Components) == 0 {
		//	tmpComponents = ""
		//} else {
		//	tmpComponents = actress.Issues[i].Fields.Components[0].Name
		//}
		if flag == 1 {
			tmpTenantid = actress.Issues[i].Fields.Customfield_10615 //cloud
		} else {
			tmpTenantid = actress.Issues[i].Fields.Customfield_12816 + actress.Issues[i].Fields.Customfield_12819
		}

		//tmpTenantid1 = actress.Issues[i].Fields.Customfield_12816 //interval
		//tmpTenantid2 = actress.Issues[i].Fields.Customfield_12819 //interval
		//var resid string = tmpTenantid1 + tmpTenantid2            //interval
		//tmpKey = actress.Issues[i].Key
		//tmpReporter = actress.Issues[i].Fields.Reporter.Name
		//if actress.Issues[i].Fields.Assignee == nil {
		//	tmpAssignee = ""
		//} else {
		//	tmpAssignee = actress.Issues[i].Fields.Assignee.Name
		//}
		//tmpSummary = actress.Issues[i].Fields.Summary
		//tmpDescription = actress.Issues[i].Fields.Description
		//tmpType = actress.Issues[i].Fields.Issuetype.Name
		//tmpStatusName = actress.Issues[i].Fields.Status.StatusCategory.Name
		sqlStr := "UPDATE jira_issueview set account_code=? WHERE id=?"

		res, err := dbb1.Exec(sqlStr, tmpTenantid, tmpid)
		if err != nil {
			fmt.Println("res fail: ", err)
			return
		}
		id, err := res.LastInsertId()
		if err != nil {
			fmt.Printf("lastInsertId fail: %s", err)
		}
		fmt.Printf("id: %d insert success!", id)

	}

}
func jiraUpdaterootcause(flag int, start string, end string, fullflag int) {
	//cloud的字段为Customfield_10615，interval的字段有两个，需要string相加处理，Customfield_12816+Customfield_12819
	//调用不同的地方，需要对struct结构体字段进行调整

	//var issue_id string = "80737"
	//url := "https://internal.pingcap.net/jira/rest/api/2/issue/" + issue_id

	//url := "https://internal.pingcap.net/jira/rest/api/2/search/" //1
	//url := "https://jira.tidbcloud.com/rest/api/2/search/" //2

	//var val = engineer_name
	//var projectid string = "11101" //1
	//var projectid string = "10417" //2
	var url string
	var projectid string
	if flag == 1 {
		url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
		projectid = "11101"                                          //1

	} else if flag == 2 {
		url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		projectid = "10417"                                   //2
	} else {
		url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		projectid = "10415"                                   //2
	}
	//if flag == 1 {
	//	url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
	//	projectid = "11101"                                          //1
	//
	//} else {
	//	url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
	//	projectid = "10417"                                   //2
	//}
	var payload *strings.Reader
	if fullflag == 1 {
		payload = strings.NewReader("{\n  \"jql\": \"created >= '2022/04/01'and created <'2022/07/19' and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")

	} else {
		payload = strings.NewReader("{\n  \"jql\": \"created >=" + "'" + start + "'" + " and created <" + "'" + end + "'" + " and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")

	}
	//payload := strings.NewReader("{\n  \"jql\": \"created >=" + start + " and created <" + end + " and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")
	//payload := strings.NewReader("{\n  \"jql\": \"created >= '2022/07/04'and created <'2022/07/14' and project=" + projectid + "\",\n \"maxResults\": \"5000\"\n }")
	//payload := strings.NewReader("{\n  \"user\": {\n    \"type\": \"user\",\n    \"name\": \"Earline Greenholt\",\n    \"email\": \"125.greenholt.earline@graham.name\",\n    \"time_zone\": \"America/Lima\",\n    \"color\": \"green\",\n    \"role\": \"admin\",\n    \"job_title\": \"Director of Engineering\",\n    \"avatar_url\": \"https://secure.gravatar.com/avatar/1d1a39d4635208d5664082a6c654a73f.png?d=mm&r=PG\",\n    \"description\": \"I'm the boss\"\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Content-Type", "application/json")
	//req.Header.Add("Accept", "application/vnd.pagerduty+json;version=2")
	//req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1
	//req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2
	if flag == 1 {
		req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1
	} else {
		req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2
	}
	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close() //修改信息
	body, _ := ioutil.ReadAll(res.Body)
	var actress Actress
	//fmt.Println(res)
	//fmt.Println(string(body))
	err := json.Unmarshal(body, &actress)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("长度：%s\n", actress.Total)
	//token := actress.Issues[2]
	//var tmpcreator string
	//var tmpUpdated string
	//var tmpResolutiondate string
	//var tmpStatusId int
	//var tmpCreatorName string
	//var tmpCPriorityName string
	var tmpid string

	var tmpTenantid string //cloud
	//var tmpTenantid1 string //interval
	//var tmpTenantid2 string //interval

	dbb1 := getDB()
	for i := 0; i < actress.Total; i++ {
		//tmpcreator = actress.Issues[i].Fields.Created
		//tmpUpdated = actress.Issues[i].Fields.Updated
		//tmpResolutiondate = actress.Issues[i].Fields.Resolutiondate
		//tmpStatusId = actress.Issues[i].Fields.Status.StatusCategory.Id
		//tmpCreatorName = actress.Issues[i].Fields.Creator.Name
		//tmpCPriorityName = actress.Issues[i].Fields.Priority.Name
		tmpid = actress.Issues[i].Id
		//if len(actress.Issues[i].Fields.Components) == 0 {
		//	tmpComponents = ""
		//} else {
		//	tmpComponents = actress.Issues[i].Fields.Components[0].Name
		//}
		if flag == 1 {
			tmpTenantid = actress.Issues[i].Fields.Customfield_10321 //cloud
		} else {
			tmpTenantid = actress.Issues[i].Fields.Customfield_10635
		}

		//tmpTenantid1 = actress.Issues[i].Fields.Customfield_12816 //interval
		//tmpTenantid2 = actress.Issues[i].Fields.Customfield_12819 //interval
		//var resid string = tmpTenantid1 + tmpTenantid2            //interval
		//tmpKey = actress.Issues[i].Key
		//tmpReporter = actress.Issues[i].Fields.Reporter.Name
		//if actress.Issues[i].Fields.Assignee == nil {
		//	tmpAssignee = ""
		//} else {
		//	tmpAssignee = actress.Issues[i].Fields.Assignee.Name
		//}
		//tmpSummary = actress.Issues[i].Fields.Summary
		//tmpDescription = actress.Issues[i].Fields.Description
		//tmpType = actress.Issues[i].Fields.Issuetype.Name
		//tmpStatusName = actress.Issues[i].Fields.Status.StatusCategory.Name
		rs := []rune(tmpTenantid)

		var lenn int
		if len(rs) > 1000 {
			lenn = 1000
		} else {
			lenn = len(rs)
		}
		if lenn > 0 {
			sqlStr := "UPDATE jira_issueview set rootcause=? WHERE id=?"

			res, err := dbb1.Exec(sqlStr, string(rs[:lenn]), tmpid)
			if err != nil {
				fmt.Println("res fail: ", err)
				return
			}
			id, err := res.LastInsertId()
			if err != nil {
				fmt.Printf("lastInsertId fail: %s", err)
			}
			fmt.Printf("id: %d insert success!", id)
		}

	}

}
func jiraChangelog(flag int) { //先用SQL语句中的将issue的数值插入到change表，然后再执行这个函数
	dbb := getDB()
	//var url string
	var projectid string
	if flag == 1 {
		//url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
		projectid = "11101" //1

	} else if flag == 2 {
		//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		projectid = "10417" //2
	} else {
		//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		projectid = "10415" //2
	}
	//if flag == 1 {
	//	//url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
	//	projectid = "11101" //1
	//
	//} else {
	//	//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
	//	projectid = "10417" //2
	//}

	sqlStr := "INSERT into jira_issue_change (id ,project_id,change_time) SELECT id,project_id,null from jira_issueview WHERE project_id=? and flag=1 on duplicate key update project_id=?"
	res2, err2 := dbb.Exec(sqlStr, projectid, projectid)
	if err2 != nil {
		fmt.Println("res fail: ", err2)
		return
	}
	id, err2 := res2.LastInsertId()
	if err2 != nil {
		fmt.Printf("lastInsertId fail: %s", err2)
	}
	fmt.Printf("id: %d insert success!", id)
	//var project_id string
	//project_id = "11101"
	//project_id = "10000"

	rows01, err := dbb.Query("SELECT  id,project_id FROM jira_issue_change where project_id=? and flag=1 ", projectid)
	if err != nil {
		panic(err)
	}
	defer rows01.Close()
	for rows01.Next() {
		var log_id int
		var log_project_id string

		err := rows01.Scan(&log_id, &log_project_id)
		if err != nil {
			log.Fatal(err)
		}
		var log_idd string = strconv.Itoa(log_id)
		var url string

		if flag == 1 {
			url = "https://internal.pingcap.net/jira/rest/api/2/issue/" + string(log_idd) + "?expand=changelog" //1
		} else {
			url = "https://jira.tidbcloud.com/rest/api/2/issue/" + string(log_idd) + "?expand=changelog" //2
		}

		//url := "https://internal.pingcap.net/jira/rest/api/2/issue/" + string(log_idd) + "?expand=changelog" //1
		//url := "https://jira.tidbcloud.com/rest/api/2/issue/" + string(log_idd) + "?expand=changelog" //2

		//var val = engineer_name
		//var projectid string = "11101" //1
		//var projectid string = "10000" //2
		//payload := strings.NewReader("{\n  \"jql\": \"created >= '2022/01/01'and created <'2022/02/06' and project=" + projectid + "\",\n \"maxResults\": \"500\"\n }")
		//payload := strings.NewReader("{\n  \"user\": {\n    \"type\": \"user\",\n    \"name\": \"Earline Greenholt\",\n    \"email\": \"125.greenholt.earline@graham.name\",\n    \"time_zone\": \"America/Lima\",\n    \"color\": \"green\",\n    \"role\": \"admin\",\n    \"job_title\": \"Director of Engineering\",\n    \"avatar_url\": \"https://secure.gravatar.com/avatar/1d1a39d4635208d5664082a6c654a73f.png?d=mm&r=PG\",\n    \"description\": \"I'm the boss\"\n  }\n}")

		req, _ := http.NewRequest("GET", url, nil)

		req.Header.Add("Content-Type", "application/json")
		//req.Header.Add("Accept", "application/vnd.pagerduty+json;version=2")
		//req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1internal
		//req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2cloud
		if flag == 1 {
			req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1
		} else {
			req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2
		}
		res, _ := http.DefaultClient.Do(req)

		defer res.Body.Close() //修改信息
		body, _ := ioutil.ReadAll(res.Body)
		var actressissue ActressIssue
		//fmt.Println(res)
		//fmt.Println(string(body))
		err01 := json.Unmarshal(body, &actressissue)
		if err01 != nil {
			fmt.Println("error:", err01)
			return
		}
		fmt.Println("33:", log_id)
		//fmt.Printf("长度：%s\n", actressissue.Total)
		//token := actress.Issues[2]
		//var fromstatus string = "10000" //intercal
		//var tostatus string = "10114" //intercal
		//var fromstatus string = "10308" //cloud
		//var tostatus string = "10309" //cloud
		var tostatus string
		var needfield = "status"
		if flag == 1 {
			tostatus = "10114" //intercal
		} else {
			tostatus = "10309" //cloud
		}
		//var tmpfromstatus string
		var tmptostatus string
		var tmpfield string
		var tmpStatustime string

		//Updated        string
		//Resolutiondate string
		//Status         *Status
		//Creator        *Creator
		//Priority       *Priority //嵌套json
		//dbb1 := getDB()
		//fmt.Printf("长度：%s\n", actressissue.Changelog.Total)
		tmpStatustimeres := ""

		var lenHistories = len(actressissue.Changelog.Histories)
		for i := 0; i < lenHistories; i++ {
			var lenItems = len(actressissue.Changelog.Histories[i].Items)
			tmptostatus = ""

			for j := 0; j < lenItems; j++ {
				tmpfield = actressissue.Changelog.Histories[i].Items[j].Field
				//tmpfromstatus = actressissue.Changelog.Histories[i].Items[j].From
				tmptostatus = actressissue.Changelog.Histories[i].Items[j].To
				tmpStatustime = actressissue.Changelog.Histories[i].Created
				//tmpStatustime=actressissue.Fields.Changelog.Histories[0].Created
				rs := []rune(tmpStatustime)

				fmt.Printf("lastInsertId fail: %s", string(rs[0:10])+" "+string(rs[11:19]))
				tmpStatustimepar, _ := time.Parse("2006-01-02 15:04:05", string(rs[0:10])+" "+string(rs[11:19]))
				tmpStatustimerespar, _ := time.Parse("2006-01-02 15:04:05", tmpStatustimeres)

				beforeOrAfter := tmpStatustimerespar.After(tmpStatustimepar)
				if tmptostatus == tostatus && tmpfield == needfield {
					if tmpStatustimeres == "" || beforeOrAfter {
						tmpStatustimeres = tmpStatustime
					}

					//tmpStatustime=""
					//满足条件，写入数据库

				} else {
					continue
				}
			}

		}
		if tmpStatustimeres != "" {
			sqlStr := "update jira_issue_change set change_time=? where id=?"
			res2, err2 := dbb.Exec(sqlStr, tmpStatustimeres, log_idd)
			if err != nil {
				fmt.Println("res fail: ", err)
				return
			}
			id, err2 := res2.LastInsertId()
			if err2 != nil {
				fmt.Printf("lastInsertId fail: %s", err2)
			}
			fmt.Printf("id: %d insert success!", id)
		}

		//for i := 0; i < actress.Total; i++ {
		//	tmpcreator = actress.Issues[i].Fields.Created
		//
		//}
	}
}

func jiraupdaResolutiondate(flag int) {
	dbb := getDB()
	//var project_id string
	var url string
	var project_id string
	if flag == 1 {
		//url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
		project_id = "11101" //1

	} else if flag == 2 {
		//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		project_id = "10417" //2
	} else {
		//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		project_id = "10415" //2
	}
	//if flag == 1 {
	//	//url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
	//	project_id = "11101" //1
	//
	//} else {
	//	//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
	//	project_id = "10417" //2
	//}
	//project_id = "11101" //1
	//project_id = "10417" //2
	rows01, err := dbb.Query("  SELECT id FROM jira_issueview WHERE ttr is NULL and project_id=? ", project_id)
	if err != nil {
		panic(err)
	}
	defer rows01.Close()
	for rows01.Next() {
		var issue_id int

		err := rows01.Scan(&issue_id)
		if err != nil {
			log.Fatal(err)
		}
		var issue_idd string = strconv.Itoa(issue_id)

		//url := "https://internal.pingcap.net/jira/rest/api/2/issue/" + string(issue_idd) //1
		//url := "https://jira.tidbcloud.com/rest/api/2/issue/" + string(issue_idd) //2
		if flag == 1 {
			url = "https://internal.pingcap.net/jira/rest/api/2/issue/" + string(issue_idd) //1
		} else {
			url = "https://jira.tidbcloud.com/rest/api/2/issue/" + string(issue_idd) //2
		}
		//var val = engineer_name
		//var projectid string = "11101" //1
		//var projectid string = "10000" //2
		//payload := strings.NewReader("{\n  \"jql\": \"created >= '2022/01/01'and created <'2022/02/06' and project=" + projectid + "\",\n \"maxResults\": \"500\"\n }")
		//payload := strings.NewReader("{\n  \"user\": {\n    \"type\": \"user\",\n    \"name\": \"Earline Greenholt\",\n    \"email\": \"125.greenholt.earline@graham.name\",\n    \"time_zone\": \"America/Lima\",\n    \"color\": \"green\",\n    \"role\": \"admin\",\n    \"job_title\": \"Director of Engineering\",\n    \"avatar_url\": \"https://secure.gravatar.com/avatar/1d1a39d4635208d5664082a6c654a73f.png?d=mm&r=PG\",\n    \"description\": \"I'm the boss\"\n  }\n}")

		req, _ := http.NewRequest("GET", url, nil)

		req.Header.Add("Content-Type", "application/json")
		//req.Header.Add("Accept", "application/vnd.pagerduty+json;version=2")
		//req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1internal
		//req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2cloud
		if flag == 1 {
			req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1internal
		} else {
			req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2cloud
		}
		res, _ := http.DefaultClient.Do(req)

		defer res.Body.Close() //修改信息
		body, _ := ioutil.ReadAll(res.Body)
		var dtsissue Tokeni
		//fmt.Println(res)
		//fmt.Println(string(body))
		err01 := json.Unmarshal(body, &dtsissue)
		if err01 != nil {
			fmt.Println("error:", err01)
			return
		}
		fmt.Println("33:", issue_idd)
		//fmt.Printf("长度：%s\n", actressissue.Total)
		//token := actress.Issues[2]
		//var fromstatus string = "10000" //intercal
		//var tostatus string = "10114"   //intercal
		//var fromstatus string = "10308" //cloud

		//var tmpfromstatus string
		//var tmptostatus string
		//var tmpfield string
		//var tmpStatustime string

		//Updated        string
		var Resolutiondate string
		//Status         *Status
		//Creator        *Creator
		//Priority       *Priority //嵌套json
		//dbb1 := getDB()
		//fmt.Printf("长度：%s\n", actressissue.Changelog.Total)
		//tmpStatustimeres := ""
		//
		//var lenHistories = len(actressissue.Changelog.Histories)
		//for i := 0; i < lenHistories; i++ {
		//	var lenItems = len(actressissue.Changelog.Histories[i].Items)
		//	tmptostatus = ""
		//
		//	for j := 0; j < lenItems; j++ {
		//		tmpfield = actressissue.Changelog.Histories[i].Items[j].Field
		//		//tmpfromstatus = actressissue.Changelog.Histories[i].Items[j].From
		//		tmptostatus = actressissue.Changelog.Histories[i].Items[j].To
		//		tmpStatustime = actressissue.Changelog.Histories[i].Created
		//		//tmpStatustime=actressissue.Fields.Changelog.Histories[0].Created
		//		rs := []rune(tmpStatustime)
		//
		//		fmt.Printf("lastInsertId fail: %s", string(rs[0:10])+" "+string(rs[11:19]))
		//		tmpStatustimepar, _ := time.Parse("2006-01-02 15:04:05", string(rs[0:10])+" "+string(rs[11:19]))
		//		tmpStatustimerespar, _ := time.Parse("2006-01-02 15:04:05", tmpStatustimeres)
		//
		//		beforeOrAfter := tmpStatustimerespar.After(tmpStatustimepar)
		//		if tmptostatus == tostatus && tmpfield == needfield {
		//			if tmpStatustimeres == "" || beforeOrAfter {
		//				tmpStatustimeres = tmpStatustime
		//			}
		//
		//			//tmpStatustime=""
		//			//满足条件，写入数据库
		//
		//		} else {
		//			continue
		//		}
		//	}
		//
		//}
		if Resolutiondate != "" {
			sqlStr := "update jira_issueview set Resolutiondate=? where id=?"
			res2, err2 := dbb.Exec(sqlStr, Resolutiondate, issue_id)
			if err != nil {
				fmt.Println("res fail: ", err)
				return
			}
			id, err2 := res2.LastInsertId()
			if err2 != nil {
				fmt.Printf("lastInsertId fail: %s", err2)
			}
			fmt.Printf("id: %d insert success!", id)
		}

		//for i := 0; i < actress.Total; i++ {
		//	tmpcreator = actress.Issues[i].Fields.Created
		//
		//}
	}
}
func jiraupdaremotelink(flag int) {
	dbb := getDB()
	//var project_id string
	var url string
	var project_id string
	if flag == 1 {
		//url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
		project_id = "11101" //1

	} else if flag == 2 {
		//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		project_id = "10417" //2
	} else {
		//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		project_id = "10415" //2
	}
	//if flag == 1 {
	//	//url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
	//	project_id = "11101" //1
	//
	//} else {
	//	//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
	//	project_id = "10417" //2
	//}
	//project_id = "11101" //1
	//project_id = "10417" //2
	rows01, err := dbb.Query("  SELECT id FROM jira_issueview  where project_id=? ", project_id)
	if err != nil {
		panic(err)
	}
	defer rows01.Close()
	for rows01.Next() {
		var issue_id int

		err := rows01.Scan(&issue_id)
		if err != nil {
			log.Fatal(err)
		}
		var issue_idd string = strconv.Itoa(issue_id)

		//url := "https://internal.pingcap.net/jira/rest/api/2/issue/" + string(issue_idd) //1
		//url := "https://jira.tidbcloud.com/rest/api/2/issue/" + string(issue_idd) //2
		if flag == 1 {
			url = "https://internal.pingcap.net/jira/rest/api/2/issue/" + string(issue_idd) + "/remotelink" //1
		} else {
			url = "https://jira.tidbcloud.com/rest/api/2/issue/" + string(issue_idd) + "/remotelink" //2
		}
		//var val = engineer_name
		//var projectid string = "11101" //1
		//var projectid string = "10000" //2
		//payload := strings.NewReader("{\n  \"jql\": \"created >= '2022/01/01'and created <'2022/02/06' and project=" + projectid + "\",\n \"maxResults\": \"500\"\n }")
		//payload := strings.NewReader("{\n  \"user\": {\n    \"type\": \"user\",\n    \"name\": \"Earline Greenholt\",\n    \"email\": \"125.greenholt.earline@graham.name\",\n    \"time_zone\": \"America/Lima\",\n    \"color\": \"green\",\n    \"role\": \"admin\",\n    \"job_title\": \"Director of Engineering\",\n    \"avatar_url\": \"https://secure.gravatar.com/avatar/1d1a39d4635208d5664082a6c654a73f.png?d=mm&r=PG\",\n    \"description\": \"I'm the boss\"\n  }\n}")

		req, _ := http.NewRequest("GET", url, nil)

		req.Header.Add("Content-Type", "application/json")
		//req.Header.Add("Accept", "application/vnd.pagerduty+json;version=2")
		//req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1internal
		//req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2cloud
		if flag == 1 {
			req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1internal
		} else {
			req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2cloud
		}
		res, _ := http.DefaultClient.Do(req)

		defer res.Body.Close() //修改信息
		body, _ := ioutil.ReadAll(res.Body)
		if len(body) > 2 {
			var dtsissue []Tokentitle
			//fmt.Println(res)
			//fmt.Println(string(body))
			err01 := json.Unmarshal(body, &dtsissue)
			if err01 != nil {
				fmt.Println("error:", err01)
				return
			}
			fmt.Println("33:", issue_idd)
			//fmt.Printf("长度：%s\n", actressissue.Total)
			//token := actress.Issues[2]
			//var fromstatus string = "10000" //intercal
			//var tostatus string = "10114"   //intercal
			//var fromstatus string = "10308" //cloud

			//var tmpfromstatus string
			//var tmptostatus string
			//var tmpfield string
			//var tmpStatustime string

			//Updated        string
			var Title string
			//Status         *Status
			//Creator        *Creator
			//Priority       *Priority //嵌套json
			//dbb1 := getDB()
			//fmt.Printf("长度：%s\n", actressissue.Changelog.Total)
			//tmpStatustimeres := ""
			//
			//var lenHistories = len(actressissue.Changelog.Histories)
			//for i := 0; i < lenHistories; i++ {
			//	var lenItems = len(actressissue.Changelog.Histories[i].Items)
			//	tmptostatus = ""
			//
			//	for j := 0; j < lenItems; j++ {
			//		tmpfield = actressissue.Changelog.Histories[i].Items[j].Field
			//		//tmpfromstatus = actressissue.Changelog.Histories[i].Items[j].From
			//		tmptostatus = actressissue.Changelog.Histories[i].Items[j].To
			//		tmpStatustime = actressissue.Changelog.Histories[i].Created
			//		//tmpStatustime=actressissue.Fields.Changelog.Histories[0].Created
			//		rs := []rune(tmpStatustime)
			//
			//		fmt.Printf("lastInsertId fail: %s", string(rs[0:10])+" "+string(rs[11:19]))
			//		tmpStatustimepar, _ := time.Parse("2006-01-02 15:04:05", string(rs[0:10])+" "+string(rs[11:19]))
			//		tmpStatustimerespar, _ := time.Parse("2006-01-02 15:04:05", tmpStatustimeres)
			//
			//		beforeOrAfter := tmpStatustimerespar.After(tmpStatustimepar)
			//		if tmptostatus == tostatus && tmpfield == needfield {
			//			if tmpStatustimeres == "" || beforeOrAfter {
			//				tmpStatustimeres = tmpStatustime
			//			}
			//
			//			//tmpStatustime=""
			//			//满足条件，写入数据库
			//
			//		} else {
			//			continue
			//		}
			//	}
			//
			//}
			Title = dtsissue[0].Object.Title
			if Title != "" {
				sqlStr := "update jira_issueview set remotelink_title=? where id=?"
				res2, err2 := dbb.Exec(sqlStr, Title, issue_id)
				if err != nil {
					fmt.Println("res fail: ", err)
					return
				}
				id, err2 := res2.LastInsertId()
				if err2 != nil {
					fmt.Printf("lastInsertId fail: %s", err2)
				}
				fmt.Printf("id: %d insert success!", id)
			}

			//for i := 0; i < actress.Total; i++ {
			//	tmpcreator = actress.Issues[i].Fields.Created
			//
			//}
		}

	}
}
func jiraupdaassignee(flag int) {
	dbb := getDB()
	//var project_id string
	var url string
	var project_id string
	if flag == 1 {
		//url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
		project_id = "11101" //1

	} else if flag == 2 {
		//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		project_id = "10417" //2
	} else {
		//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
		project_id = "10415" //2
	}
	//if flag == 1 {
	//	//url = "https://internal.pingcap.net/jira/rest/api/2/search/" //1
	//	project_id = "11101" //1
	//
	//} else {
	//	//url = "https://jira.tidbcloud.com/rest/api/2/search/" //2
	//	project_id = "10417" //2
	//}
	//project_id = "11101" //1
	//project_id = "10417" //2
	rows01, err := dbb.Query("  SELECT id FROM jira_issueview  where project_id=? ", project_id)
	if err != nil {
		panic(err)
	}
	defer rows01.Close()
	for rows01.Next() {
		var issue_id int

		err := rows01.Scan(&issue_id)
		if err != nil {
			log.Fatal(err)
		}
		var issue_idd string = strconv.Itoa(issue_id)

		//url := "https://internal.pingcap.net/jira/rest/api/2/issue/" + string(issue_idd) //1
		//url := "https://jira.tidbcloud.com/rest/api/2/issue/" + string(issue_idd) //2
		if flag == 1 {
			url = "https://internal.pingcap.net/jira/rest/api/2/issue/" + string(issue_idd) //1
		} else {
			url = "https://jira.tidbcloud.com/rest/api/2/issue/" + string(issue_idd) //2
		}
		//var val = engineer_name
		//var projectid string = "11101" //1
		//var projectid string = "10000" //2
		//payload := strings.NewReader("{\n  \"jql\": \"created >= '2022/01/01'and created <'2022/02/06' and project=" + projectid + "\",\n \"maxResults\": \"500\"\n }")
		//payload := strings.NewReader("{\n  \"user\": {\n    \"type\": \"user\",\n    \"name\": \"Earline Greenholt\",\n    \"email\": \"125.greenholt.earline@graham.name\",\n    \"time_zone\": \"America/Lima\",\n    \"color\": \"green\",\n    \"role\": \"admin\",\n    \"job_title\": \"Director of Engineering\",\n    \"avatar_url\": \"https://secure.gravatar.com/avatar/1d1a39d4635208d5664082a6c654a73f.png?d=mm&r=PG\",\n    \"description\": \"I'm the boss\"\n  }\n}")

		req, _ := http.NewRequest("GET", url, nil)

		req.Header.Add("Content-Type", "application/json")
		//req.Header.Add("Accept", "application/vnd.pagerduty+json;version=2")
		//req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1internal
		//req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2cloud
		if flag == 1 {
			req.Header.Add("Authorization", "Bearer OTM3MzY4Njg2MzQ1OqX7iWrVPpaFZGz2JL0ljTFPvhTs") //1internal
		} else {
			req.Header.Add("Authorization", "Bearer NzA4MjQ5NTE2NjY5OrhikLI528+hZgX8pEO7pwiH7P3O") //2cloud
		}
		res, _ := http.DefaultClient.Do(req)

		defer res.Body.Close() //修改信息
		body, _ := ioutil.ReadAll(res.Body)
		if len(body) > 2 {
			var dtsissue []Tokentitle
			//fmt.Println(res)
			//fmt.Println(string(body))
			err01 := json.Unmarshal(body, &dtsissue)
			if err01 != nil {
				fmt.Println("error:", err01)
				return
			}
			fmt.Println("33:", issue_idd)
			//fmt.Printf("长度：%s\n", actressissue.Total)
			//token := actress.Issues[2]
			//var fromstatus string = "10000" //intercal
			//var tostatus string = "10114"   //intercal
			//var fromstatus string = "10308" //cloud

			//var tmpfromstatus string
			//var tmptostatus string
			//var tmpfield string
			//var tmpStatustime string

			//Updated        string
			var Title string
			//Status         *Status
			//Creator        *Creator
			//Priority       *Priority //嵌套json
			//dbb1 := getDB()
			//fmt.Printf("长度：%s\n", actressissue.Changelog.Total)
			//tmpStatustimeres := ""
			//
			//var lenHistories = len(actressissue.Changelog.Histories)
			//for i := 0; i < lenHistories; i++ {
			//	var lenItems = len(actressissue.Changelog.Histories[i].Items)
			//	tmptostatus = ""
			//
			//	for j := 0; j < lenItems; j++ {
			//		tmpfield = actressissue.Changelog.Histories[i].Items[j].Field
			//		//tmpfromstatus = actressissue.Changelog.Histories[i].Items[j].From
			//		tmptostatus = actressissue.Changelog.Histories[i].Items[j].To
			//		tmpStatustime = actressissue.Changelog.Histories[i].Created
			//		//tmpStatustime=actressissue.Fields.Changelog.Histories[0].Created
			//		rs := []rune(tmpStatustime)
			//
			//		fmt.Printf("lastInsertId fail: %s", string(rs[0:10])+" "+string(rs[11:19]))
			//		tmpStatustimepar, _ := time.Parse("2006-01-02 15:04:05", string(rs[0:10])+" "+string(rs[11:19]))
			//		tmpStatustimerespar, _ := time.Parse("2006-01-02 15:04:05", tmpStatustimeres)
			//
			//		beforeOrAfter := tmpStatustimerespar.After(tmpStatustimepar)
			//		if tmptostatus == tostatus && tmpfield == needfield {
			//			if tmpStatustimeres == "" || beforeOrAfter {
			//				tmpStatustimeres = tmpStatustime
			//			}
			//
			//			//tmpStatustime=""
			//			//满足条件，写入数据库
			//
			//		} else {
			//			continue
			//		}
			//	}
			//
			//}
			Title = dtsissue[0].Object.Title
			if Title != "" {
				sqlStr := "update jira_issueview set remotelink_title=? where id=?"
				res2, err2 := dbb.Exec(sqlStr, Title, issue_id)
				if err != nil {
					fmt.Println("res fail: ", err)
					return
				}
				id, err2 := res2.LastInsertId()
				if err2 != nil {
					fmt.Printf("lastInsertId fail: %s", err2)
				}
				fmt.Printf("id: %d insert success!", id)
			}

			//for i := 0; i < actress.Total; i++ {
			//	tmpcreator = actress.Issues[i].Fields.Created
			//
			//}
		}

	}
}
func jiracompele() {
	dbb := getDB()
	sqlStr := "UPDATE jira_issueview,(select issue_id,min(created_time) first_time from jira_actionview group by issue_id) b  set first_comment_time=b.first_time WHERE jira_issueview.id=b.issue_id" //将firstcommenttime的数值插入到issue表
	res2, err2 := dbb.Exec(sqlStr)
	if err2 != nil {
		fmt.Println("res fail: ", err2)
		return
	}
	id, err2 := res2.LastInsertId()
	if err2 != nil {
		fmt.Printf("lastInsertId fail: %s", err2)
	}
	fmt.Printf("id: %d insert success!", id)
	sqlStr1 := "UPDATE jira_issueview,(SELECT change_time,id FROM jira_issue_change)a set first_sc_time=a.change_time WHERE jira_issueview.id=a.id" //将changetime的数值插入到issue表first_sc_time
	_, err3 := dbb.Exec(sqlStr1)
	if err3 != nil {
		fmt.Println("res fail: ", err3)
		return
	}
	sqlStr6 := "update jira_issueview set ttr = round(timestampdiff(hour,created_time,resolution_date)/24,2) WHERE ttr is NULL" //计算dts
	_, err8 := dbb.Exec(sqlStr6)
	if err8 != nil {
		fmt.Println("res fail: ", err8)
		return
	}

	sqlStr2 := "update jira_issueview set fdr=1 where ttr<=1" //计算fdr
	_, err4 := dbb.Exec(sqlStr2)
	if err4 != nil {
		fmt.Println("res fail: ", err4)
		return
	}
	sqlStr3 := "update jira_issueview set fdr=0 where (ttr>1 or ttr is null)" //计算fdr
	_, err5 := dbb.Exec(sqlStr3)
	if err5 != nil {
		fmt.Println("res fail: ", err5)
		return
	}

	sqlStr5 := "UPDATE jira_issueview,(select a.id,change_time,first_time, case when change_time is not NULL and first_time is NOT NULL then  (CASE WHEN change_time<first_time THEN change_time ELSE first_time END) ELSE (CASE WHEN change_time is not null  THEN change_time ELSE first_time END) end timfff  from (select distinct id,change_time from jira_issue_change)a    left join  (select issue_id,min(created_time) first_time  from jira_actionview group by issue_id) b   on a.id=b.issue_id   order by change_time asc)  d set jira_issueview.frt=timfff WHERE jira_issueview.id=d.id" //处理frt
	_, err7 := dbb.Exec(sqlStr5)
	if err7 != nil {
		fmt.Println("res fail: ", err7)
		return
	}
	sqlStr4 := "update jira_issueview set frt_hour = round(timestampdiff(minute,created_time,frt)/60,2)" //frt_hour
	_, err6 := dbb.Exec(sqlStr4)
	if err6 != nil {
		fmt.Println("res fail: ", err6)
		return
	}
	sqlStr7 := "UPDATE jira_issueview set flag=0 " //设置flag
	_, err9 := dbb.Exec(sqlStr7)
	if err9 != nil {
		fmt.Println("res fail: ", err9)
		return
	}
	sqlStr8 := "UPDATE jira_issue_change set flag=0  " //设置flag
	_, err10 := dbb.Exec(sqlStr8)
	if err10 != nil {
		fmt.Println("res fail: ", err10)
		return
	}
	fmt.Println("completed！ ")
}
func jiraAdd(issueflag int, start string, end string, fullflag int) { //issueflag表示更新inter  2表示更新dbcloud
	//var issueflag = 1

	jira(issueflag, start, end, fullflag) //新增jiraissue
	jiraUpdateComponent(issueflag, start, end, fullflag)
	jiraUpdateCode(issueflag, start, end, fullflag)
	jiraupdaResolutiondate(issueflag) //重新查询未关单的是否有被关闭的，并更新dts
	jiraaction(issueflag)
	jiraChangelog(issueflag)
	jiraupdaremotelink(issueflag)
	jiraUpdaterootcause(issueflag, start, end, fullflag)
	jiracompele()
}
func main() {
	t := time.Now().Unix()
	fmt.Println(reflect.TypeOf(t))
	var end string = time.Unix(t, 0).Format("2006/01/02")
	t -= 86400 //减一天
	var start string = time.Unix(t, 0).Format("2006/01/02")
	fmt.Println(end)
	fmt.Println(start)
	var fullflag = 1 //为1表示全量取数据，需要自己指定日期，为2表示按天增量
	jiraAdd(3, start, end, fullflag)
	jiraAdd(3, start, end, fullflag)
	//fmt.Println(time.Unix(t, 0).Format("2006-01-02"))
	//t -= 86400 //增加一天
	//fmt.Println(time.Unix(t, 0).Format("2006/01/02"))

	//jiraupdaremotelink(1)
	//jiraUpdaterootcause(1)
	//test()
	//jiraday()//计算每天解决率的，用作可视化展示用，暂时未用到

	//jira()
	//jiraaction()
	//jiraChangelog()

	//jiraUpdateComponent(1, start, end)
	//jiraUpdateCode()
	//jiraupdaResolutiondate()

	//jiraAdd() //增量
}

//做增量：
//jira  jiraUpdateComponent jiraUpdateCode jiraupdaDTS jiraaction jiraChangelog 再sql插入计算
