package controllers

import (
	"ColdVerify_local/Nats"
	"ColdVerify_local/Nats/NatsServer"
	"ColdVerify_local/conf"
	"ColdVerify_local/lib"
	"ColdVerify_local/logs"
	"ColdVerify_local/models/System"
	"ColdVerify_local/models/Task"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/vmihailenco/msgpack/v5"
	"github.com/xuri/excelize/v2"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"
)

type TaskDataController struct {
	beego.Controller
}

// 列表 -
func (c *TaskDataController) TaskData_List() {

	var r_jsons lib.R_JSONS
	page, _ := c.GetInt("page")
	if page < 1 {
		page = 1
	}
	page_z, _ := c.GetInt("page_z")
	if page_z < 1 {
		page_z = conf.Page_size
	}

	Time_start := c.GetString("Time_start")
	Time_end := c.GetString("Time_end")
	T_sn := c.GetString("T_sn")
	T_id, err := c.GetInt("T_id")
	if err != nil {
		T_id = -1
	}

	T_task_id := c.GetString("T_task_id")
	Task_r, err := NatsServer.Read_Task(T_task_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}
	if Task_r.T_collection_state == 2 {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "数据采集中，请稍后!"}
		c.ServeJSON()
		return
	}

	var cnt int64
	List, cnt := Task.Read_TaskData_ById_List(Task_r.T_task_id, T_sn, T_id, Time_start, Time_end, page, page_z)
	page_size := math.Ceil(float64(cnt) / float64(page_z))
	r_jsons.List = List
	r_jsons.Page = page
	r_jsons.Page_size = int(page_size)
	r_jsons.Pages = lib.Func_page(int64(page), int64(page_size))
	r_jsons.Num = int(cnt)

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: r_jsons}
	c.ServeJSON()
	return
}

// 列表 -
func (c *TaskDataController) TaskDataClass_List() {
	page, _ := c.GetInt("page")
	if page < 1 {
		page = 1
	}
	page_z, _ := c.GetInt("page_z")
	if page_z < 1 {
		page_z = conf.Page_size
	}
	T_task_id := c.GetString("T_task_id")
	Task_r, err := NatsServer.Read_Task(T_task_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}

	if Task_r.T_collection_state == 2 {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "数据采集中，请稍后!"}
		c.ServeJSON()
		return
	}

	List := Task.Read_TaskData_ById_ClassList(Task_r.T_task_id)

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: List}
	c.ServeJSON()
	return
}

func (c *TaskDataController) TaskDataClass_Edit() {
	T_uuid, _ := lib.GetAdminT_Uuid(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
	T_task_id := c.GetString("T_task_id")
	T_sn := c.GetString("T_sn")
	T_id := c.GetString("T_id")
	Task_r, err := NatsServer.Read_Task(T_task_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}

	err = Task.Update_TaskData_ByT_sn(Task_r.T_task_id, T_sn, T_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "修改失败!"}
		c.ServeJSON()
		return
	}

	System.Add_UserLogs_T(T_uuid, "本地版-任务分裂", "修改分类数据"+Task_r.T_name, Task_r.T_task_id+"|"+T_sn+"|"+T_id)

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
	c.ServeJSON()
	return
}

func (c *TaskDataController) TaskDataClass_Del() {
	T_uuid, _ := lib.GetAdminT_Uuid(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))

	T_task_id := c.GetString("T_task_id")
	T_sn := c.GetString("T_sn")
	Task_r, err := NatsServer.Read_Task(T_task_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}

	err = Task.Delete_TaskData_ByT_sn(Task_r.T_task_id, T_sn)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "删除失败!"}
		c.ServeJSON()
		return
	}

	System.Add_UserLogs_T(T_uuid, "本地版-任务分裂", "删除分类数据"+Task_r.T_name, Task_r.T_task_id+"|"+T_sn)

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
	c.ServeJSON()
	return
}

// 添加-
func (c *TaskDataController) TaskData_AddS() {
	// 获取登录用户的uuid
	T_uuid, _ := lib.GetAdminT_Uuid(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))

	T_task_id := c.GetString("T_task_id")
	Task_r, err := NatsServer.Read_Task(T_task_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}

	//T_sn|T_id|T_t|T_rh|T_time?

	T_Data := c.GetString("T_Data")
	if len(T_Data) < 5 {
		c.Data["json"] = lib.JSONS{Code: 201, Msg: "err T_Data!"}
		c.ServeJSON()
		return
	}

	T_Data_list := strings.Split(T_Data, "?")
	println(len(T_Data_list), "len(T_Data_list)")
	var T_Data_list_x = 0
	for _, v := range T_Data_list {
		// 2022-08-09 14:25:00|27.7|55.2
		if len(v) < 5 {
			println(v, "len(v) < 5")
			continue
		}
		v_list := strings.Split(v, "|")
		is := Task.Add_TaskData(Task_r.T_task_id, v_list[0], v_list[1], v_list[2], v_list[3], v_list[4])
		if is {
			T_Data_list_x += 1
		}
	}

	System.Add_UserLogs_T(T_uuid, "本地版-任务数据", "添加数据"+Task_r.T_name, Task_r.T_task_id+"结果："+string(len(T_Data_list))+"/"+string(T_Data_list_x)+"|=> "+T_Data)

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: strconv.Itoa(T_Data_list_x)}
	c.ServeJSON()
	return
}

// 添加-
func (c *TaskDataController) TaskData_Add() {
	// 获取登录用户的uuid
	T_uuid, _ := lib.GetAdminT_Uuid(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))

	T_sn := c.GetString("T_sn")
	T_id, _ := c.GetInt("T_id")
	T_t, _ := c.GetFloat("T_t")
	T_rh, _ := c.GetFloat("T_rh")
	T_time := c.GetString("T_time")

	T_task_id := c.GetString("T_task_id")
	Task_r, err := NatsServer.Read_Task(T_task_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}

	is := Task.Add_TaskData(Task_r.T_task_id, T_sn, strconv.Itoa(T_id), fmt.Sprintf("%.2f", T_t), fmt.Sprintf("%.2f", T_rh), T_time)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "添加失败!"}
		c.ServeJSON()
		return
	}

	System.Add_UserLogs_T(T_uuid, "本地版-任务数据", "添加数据"+Task_r.T_name, Task_r.T_task_id+"|"+T_sn+"|"+strconv.Itoa(T_id)+"|"+fmt.Sprintf("%.2f", T_t)+"|"+fmt.Sprintf("%.2f", T_rh)+T_time)

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
	c.ServeJSON()
	return
}

// 修改-
func (c *TaskDataController) TaskData_Up() {
	// 获取登录用户的uuid
	T_uuid, _ := lib.GetAdminT_Uuid(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))

	Id, err := c.GetInt("Id")
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 201, Msg: "Id 错误!"}
		c.ServeJSON()
		return
	}
	T_t, err := c.GetFloat("T_t")
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_t 错误!"}
		c.ServeJSON()
		return
	}
	T_rh, err := c.GetFloat("T_rh")
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_rh 错误!"}
		c.ServeJSON()
		return
	}
	T_time := c.GetString("T_time")

	T_task_id := c.GetString("T_task_id")
	Task_r, err := NatsServer.Read_Task(T_task_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}

	is := Task.Up_TaskData(Task_r.T_task_id, strconv.Itoa(Id), fmt.Sprintf("%.2f", T_t), fmt.Sprintf("%.2f", T_rh), T_time)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "修改失败!"}
		c.ServeJSON()
		return
	}

	System.Add_UserLogs_T(T_uuid, "本地版-任务数据", "修改数据"+Task_r.T_name, Task_r.T_task_id+"|"+strconv.Itoa(Id)+"|"+fmt.Sprintf("%.2f", T_t)+"|"+fmt.Sprintf("%.2f", T_rh)+T_time)

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
	c.ServeJSON()
	return
}

// 删除-
func (c *TaskDataController) TaskData_Del() {
	// 获取登录用户的uuid
	T_uuid, _ := lib.GetAdminT_Uuid(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))

	Id, err := c.GetInt("Id")
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 201, Msg: "Id 错误!"}
		c.ServeJSON()
		return
	}

	T_task_id := c.GetString("T_task_id")
	Task_r, err := NatsServer.Read_Task(T_task_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}

	is := Task.Del_TaskData(Task_r.T_task_id, strconv.Itoa(Id))
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "删除失败!"}
		c.ServeJSON()
		return
	}
	System.Add_UserLogs_T(T_uuid, "本地版-任务数据", "删除"+Task_r.T_name, Task_r.T_task_id+"|"+strconv.Itoa(Id))

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
	c.ServeJSON()
	return
}

// 删除-
func (c *TaskDataController) TaskData_Del_t_id() {
	// 获取登录用户的uuid
	T_uuid, _ := lib.GetAdminT_Uuid(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))

	Id, err := c.GetInt("Id")
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 201, Msg: "Id 错误!"}
		c.ServeJSON()
		return
	}

	T_task_id := c.GetString("T_task_id")
	Task_r, err := NatsServer.Read_Task(T_task_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}

	is := Task.Del_TaskData_t_id(Task_r.T_task_id, strconv.Itoa(Id))
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "删除失败!"}
		c.ServeJSON()
		return
	}
	System.Add_UserLogs_T(T_uuid, "本地版-任务数据", "删除"+Task_r.T_name, Task_r.T_task_id+"|"+strconv.Itoa(Id))

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
	c.ServeJSON()
	return
}

// 列表 - 接口
func (c *TaskDataController) Export_Data_Excel() {

	Time_start := c.GetString("Time_start")
	Time_end := c.GetString("Time_end")
	T_sn_str := c.GetString("T_sn_list") //865901058809339,865901058815849,865901058818991,865901058810568
	//T_id, err := c.GetInt("T_id")
	//if err != nil {
	//	T_id = -1
	//
	//}

	T_task_id := c.GetString("T_task_id")
	Task_r, err := NatsServer.Read_Task(T_task_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}

	if Task_r.T_collection_state == 2 {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "数据采集中，请稍后!"}
		c.ServeJSON()
		return
	}

	T_sn_list := strings.Split(T_sn_str, ",")
	DeviceSensor_data_list := []Task.TaskData_{}
	for _, v := range T_sn_list {
		DeviceSensor_data, _ := Task.Read_TaskData_ById_List(Task_r.T_task_id, v, -1, Time_start, Time_end, 1, 9999)
		DeviceSensor_data_list = append(DeviceSensor_data_list, DeviceSensor_data...)
	}

	f := excelize.NewFile() // 设置单元格的值
	// 这里设置表头
	f.SetCellValue("Sheet1", "A1", "编号")
	f.SetCellValue("Sheet1", "B1", "SN")
	f.SetCellValue("Sheet1", "C1", "温度℃")
	f.SetCellValue("Sheet1", "D1", "湿度%")
	f.SetCellValue("Sheet1", "E1", "记录时间")
	// 设置列宽
	f.SetColWidth("Sheet1", "A", "A", 7)
	f.SetColWidth("Sheet1", "B", "B", 20)
	f.SetColWidth("Sheet1", "C", "C", 10)
	f.SetColWidth("Sheet1", "D", "D", 10)
	f.SetColWidth("Sheet1", "E", "E", 22)

	line := 1

	// 循环写入数据
	for _, v := range DeviceSensor_data_list {
		line++
		f.SetCellValue("Sheet1", fmt.Sprintf("A%d", line), v.T_id)
		f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), v.T_sn)
		f.SetCellValue("Sheet1", fmt.Sprintf("C%d", line), strconv.FormatFloat(float64(v.T_t), 'f', 1, 64))
		f.SetCellValue("Sheet1", fmt.Sprintf("D%d", line), strconv.FormatFloat(float64(v.T_rh), 'f', 1, 64))
		f.SetCellValue("Sheet1", fmt.Sprintf("E%d", line), v.T_time)

	}
	fmt.Println("DeviceSensor_data:", len(DeviceSensor_data_list))

	lib.Create_Dir("./ofile")

	timeStr := time.Now().Format("20060102150405")
	// 保存文件
	if err := f.SaveAs("ofile/" + timeStr + ".xlsx"); err != nil {
		fmt.Println(err)
	}

	if !lib.Pload_qiniu("ofile/"+timeStr+".xlsx", "ofile/"+timeStr+".xlsx") {
		c.Data["json"] = lib.JSONS{Code: 203, Msg: "oss!"}
		c.ServeJSON()
		return
	}
	//删除目录
	//err = os.Remove("ofile/" + timeStr + ".xlsx")
	//if err != nil {
	//	fmt.Println(err)
	//}

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: "https://bzdcoldverifyoss.baozhida.cn/" + "ofile/" + timeStr + ".xlsx"}
	c.ServeJSON()
	return
}

func (c *TaskDataController) Check() {
	T_task_id := c.GetString("T_task_id")
	Task_r, err := NatsServer.Read_Task(T_task_id)
	if Task_r.T_collection_state == 2 {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "数据采集中，请稍后!"}
		c.ServeJSON()
		return
	}
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}
	type R_JSONS struct {
		T_sn               string // SN
		T_id               string // 编号
		T_unm              int    // 数据量
		T_time_interval    int64  // 时间间隔
		Time_start         string // 开始
		Time_end           string //  结束
		Result             int    //  200 OK, 201 可以补 , 202 不能补
		Result_str         string //  提示内容
		Result_Time_start  string //  2022-8-05 21:01
		Result_Time_defect int64  //  缺失时间间隔
	}
	var r_jsons []R_JSONS

	List := Task.Read_TaskData_ById_ClassList(Task_r.T_task_id)
	for _, v := range List {
		var r_json R_JSONS
		r_json.T_sn = v.T_sn
		r_json.T_id = v.T_id
		r_json.Result = 200

		DeviceSensor_data := Task.Read_TaskData_ById_List_(Task_r.T_task_id, v.T_sn)
		r_json.T_unm = len(DeviceSensor_data)

		if r_json.T_unm > 2 {
			r_json.T_id = DeviceSensor_data[0].T_id
			r_json.Time_end = DeviceSensor_data[len(DeviceSensor_data)-1].T_time
			r_json.Time_start = DeviceSensor_data[0].T_time

			formatTime_a, _ := time.Parse("2006-1-2 15:04", DeviceSensor_data[0].T_time)
			formatTime_b, _ := time.Parse("2006-1-2 15:04", DeviceSensor_data[1].T_time)
			formatTime_x := formatTime_b.Unix() - formatTime_a.Unix()
			r_json.T_time_interval = formatTime_x
			println("formatTime_x:", v.T_id, v.T_sn, formatTime_x)
			if formatTime_x > 60*30 || formatTime_x < 60 {
				r_json.Result = 202
				r_json.Result_str = "数据异常（数据的第一个时间与第二个时间相差 " + strconv.FormatInt(formatTime_x, 10) + "秒）,必须大于60秒，小于30分钟"
				r_jsons = append(r_jsons, r_json)
				continue
			}
			for data_i := 2; data_i < len(DeviceSensor_data); data_i++ {
				formatTime_a = formatTime_b
				formatTime_b, _ = time.Parse("2006-1-2 15:04", DeviceSensor_data[data_i].T_time)
				formatTime_ := formatTime_b.Unix() - formatTime_a.Unix()
				println("formatTime_x-:", formatTime_)
				if formatTime_ < formatTime_x {
					r_json.Result = 202
					r_json.Result_str = "开始时间：" + DeviceSensor_data[data_i-1].T_time + "  离下一条时间间隔:" + strconv.FormatInt(formatTime_, 10) + "秒，间隔小于时间间隔，不能自动补充"
					break
				}
				if formatTime_x != formatTime_ {
					if formatTime_ > 60*30 {
						r_json.Result = 202
						r_json.Result_str = "开始时间：" + DeviceSensor_data[data_i-1].T_time + "  离下一条时间间隔:" + strconv.FormatInt(formatTime_, 10) + "秒，相差时间大于30分钟，不能自动补充"
						break
					}
					r_json.Result = 201
					r_json.Result_str = "开始时间：" + DeviceSensor_data[data_i-1].T_time + "  离下一条时间间隔:" + strconv.FormatInt(formatTime_, 10) + "秒"
					r_json.Result_Time_start = DeviceSensor_data[data_i-1].T_time
					r_json.Result_Time_defect = formatTime_
					println(r_json.Result_str)
					break
				}

			}
		} else {
			r_json.Result = 202
			r_json.Result_str = "数据量太少 必须大于 2条以上！"
		}

		r_jsons = append(r_jsons, r_json)
	}

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: r_jsons}
	c.ServeJSON()
	return
}

func (c *TaskDataController) Check_Asyn() {
	T_task_id := c.GetString("T_task_id")
	Task_r, err := NatsServer.Read_Task(T_task_id)
	if Task_r.T_collection_state == 2 {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "数据采集中，请稍后!"}
		c.ServeJSON()
		return
	}
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}
	type R_JSONS struct {
		T_sn               string // SN
		T_id               string // 编号
		T_unm              int    // 数据量
		T_time_interval    int64  // 时间间隔
		Time_start         string // 开始
		Time_end           string //  结束
		Result             int    //  200 OK, 201 可以补 , 202 不能补
		Result_str         string //  提示内容
		Result_Time_start  string //  2022-8-05 21:01
		Result_Time_defect int64  //  缺失时间间隔
	}

	List := Task.Read_TaskData_ById_ClassList(Task_r.T_task_id)

	r_jsons := make([]R_JSONS, 0)
	var limitMaxNum = 10
	var chData = make(chan int, limitMaxNum)
	var jobGroup sync.WaitGroup
	var tasknum = len(List)

	for i := 0; i < tasknum; i++ {
		chData <- 1
		jobGroup.Add(1)
		go func(index int, wg *sync.WaitGroup, res *[]R_JSONS) {
			defer wg.Done()
			var r_json R_JSONS
			r_json.T_sn = List[index].T_sn
			r_json.T_id = List[index].T_id

			r_json.Result = 200

			DeviceSensor_data := Task.Read_TaskData_ById_List_(Task_r.T_task_id, List[index].T_sn)
			r_json.T_unm = len(DeviceSensor_data)

			if r_json.T_unm > 2 {
				r_json.T_id = DeviceSensor_data[0].T_id
				r_json.Time_end = DeviceSensor_data[len(DeviceSensor_data)-1].T_time
				r_json.Time_start = DeviceSensor_data[0].T_time

				formatTime_a, _ := time.Parse("2006-1-2 15:04", DeviceSensor_data[0].T_time)
				formatTime_b, _ := time.Parse("2006-1-2 15:04", DeviceSensor_data[1].T_time)
				formatTime_x := formatTime_b.Unix() - formatTime_a.Unix()
				r_json.T_time_interval = formatTime_x
				println("formatTime_x:", List[index].T_id, List[index].T_sn, formatTime_x)
				if formatTime_x > 60*30 || formatTime_x < 60 {
					r_json.Result = 202
					r_json.Result_str = "数据异常（数据的第一个时间与第二个时间相差 " + strconv.FormatInt(formatTime_x, 10) + "秒）,必须大于60秒，小于30分钟"
					*res = append(*res, r_json)
					<-chData
					return
				}

				for data_i := 2; data_i < len(DeviceSensor_data); data_i++ {
					formatTime_a = formatTime_b
					formatTime_b, _ = time.Parse("2006-1-2 15:04", DeviceSensor_data[data_i].T_time)
					formatTime_ := formatTime_b.Unix() - formatTime_a.Unix()
					if formatTime_ < formatTime_x {
						println("formatTime_x-:", formatTime_)
						r_json.Result = 202
						r_json.Result_str = "开始时间：" + DeviceSensor_data[data_i-1].T_time + "  离下一条时间间隔:" + strconv.FormatInt(formatTime_, 10) + "秒，间隔小于时间间隔，不能自动补充"
						break
					}
					if formatTime_x != formatTime_ {
						if formatTime_ > 60*30 {
							println("formatTime_x-:", formatTime_)
							r_json.Result = 202
							r_json.Result_str = "开始时间：" + DeviceSensor_data[data_i-1].T_time + "  离下一条时间间隔:" + strconv.FormatInt(formatTime_, 10) + "秒，相差时间大于30分钟，不能自动补充"
							break
						}
						r_json.Result = 202
						r_json.Result_str = "开始时间：" + DeviceSensor_data[data_i-1].T_time + "  离下一条时间间隔:" + strconv.FormatInt(formatTime_, 10) + "秒"
						r_json.Result_Time_start = DeviceSensor_data[data_i-1].T_time
						r_json.Result_Time_defect = formatTime_
						println(r_json.Result_str)
						break
					}
				}

			} else {
				r_json.Result = 202
				r_json.Result_str = "数据量太少 必须大于 2条以上！"
			}
			*res = append(*res, r_json)
			<-chData
		}(i, &jobGroup, &r_jsons)
	}
	//使用Wait等待所有任务执行完毕
	jobGroup.Wait()

	sort.Slice(r_jsons, func(i, j int) bool {
		return r_jsons[i].T_id < r_jsons[j].T_id
	})

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: r_jsons}
	c.ServeJSON()
	return
}

// 打包数据本地数据
func (c *TaskDataController) TaskData_Import_TaskData() {
	// 获取登录用户的uuid
	T_uuid, _ := lib.GetAdminT_Uuid(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))

	T_task_id := c.GetString("T_task_id")
	_, err := NatsServer.Read_Task(T_task_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}
	if err = lib.Create_Dir(conf.Sql_Temp_Dir); err != nil {
		logs.Println("创建sql临时文件失败")
	}
	sql_file := fmt.Sprintf("%sZ_TaskData_%s.sql", conf.Sql_Temp_Dir, T_task_id)
	org, err := Task.Dump_TaskData(T_task_id, conf.MysqlServer2_Username, conf.MysqlServer2_Password, conf.MysqlServer2_UrlPort, conf.MysqlServer2_Database, sql_file)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "z_task_data_" + T_task_id + "线上数据导出失败!"}
		c.ServeJSON()
		return
	}
	System.Add_UserLogs_T(T_uuid, "本地版-任务数据-打包本地数据", "导出线上数据Z_TaskData_"+T_task_id, org)

	i := 0
	flag := false
	Task.CREATE_TaskData(conf.Local_AliasName, T_task_id)
	for i < 10 {
		Task.Truncate_TaskData(conf.Local_AliasName, T_task_id)
		org, err = Task.Insert_TaskData(conf.MysqlServer_Username, conf.MysqlServer_Password, conf.MysqlServer_UrlPort, conf.MysqlServer_Database, sql_file)
		if err != nil {
			logs.Println("任务数据-打包本地数据", "线下导入数据Z_TaskData_"+T_task_id, err.Error())
		} else {
			if Task.Check_TaskData_Num(T_task_id) {
				System.Add_UserLogs_T(T_uuid, "本地版-任务数据-打包本地数据", "线下导入数据Z_TaskData_"+T_task_id, org)
				flag = true
				break
			}
		}
		i++
	}
	// 重试10次后仍然没有成功导入数据
	if !flag {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "z_task_data_" + T_task_id + "线下导入数据失败!"}
		c.ServeJSON()
		return
	}

	//删除导出的sql文件
	_ = os.Remove(sql_file)

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
	c.ServeJSON()

}

// 更新线上数据
func (c *TaskDataController) TaskData_Up_TaskData() {
	// 获取登录用户的uuid
	T_uuid, _ := lib.GetAdminT_Uuid(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))

	T_task_id := c.GetString("T_task_id")

	Task_r, err := NatsServer.Read_Task(T_task_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}
	if err = lib.Create_Dir(conf.Sql_Temp_Dir); err != nil {
		logs.Println("创建sql临时文件失败")
	}
	sql_file := fmt.Sprintf("%sZ_TaskData_%s.sql", conf.Sql_Temp_Dir, T_task_id)
	org, err := Task.Dump_TaskData(T_task_id, conf.MysqlServer_Username, conf.MysqlServer_Password, conf.MysqlServer_UrlPort, conf.MysqlServer_Database, sql_file)
	if err != nil {
		logs.Println(T_uuid, "任务数据-更新线上数据", "导出线下数据Z_TaskData_"+T_task_id, err.Error())
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "z_task_data_" + T_task_id + "线下数据导出失败!"}
		c.ServeJSON()
		return
	}
	System.Add_UserLogs_T(T_uuid, "本地版-任务数据-更新线上数据", "线上导入数据Z_TaskData_"+T_task_id, org)

	i := 0
	flag := false
	for i < 10 {
		Task.Truncate_TaskData(conf.Server_AliasName, T_task_id)
		org, err = Task.Insert_TaskData(conf.MysqlServer2_Username, conf.MysqlServer2_Password, conf.MysqlServer2_UrlPort, conf.MysqlServer2_Database, sql_file)
		if err != nil {
			logs.Println(T_uuid, "任务数据-更新线上数据", "线上导入数据Z_TaskData_"+T_task_id, err.Error())
		} else {
			if Task.Check_TaskData_Num(T_task_id) {
				System.Add_UserLogs_T(T_uuid, "本地版-任务数据-更新线上数据", "线上导入数据Z_TaskData_"+T_task_id, org)
				flag = true
				break
			}
		}
		i++
	}
	// 重试10次后仍然没有成功导入数据
	if !flag {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "z_task_data_" + T_task_id + "线上导入数据失败!"}
		c.ServeJSON()
		return
	}

	//删除导出的sql文件
	_ = os.Remove(sql_file)

	// 线上数据更新后 将当前任务 交付审核 标志 为 1
	Task_r.T_delivery_state = 1
	err = NatsServer.Update_Task(Task_r)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "修改失败!"}
		c.ServeJSON()
		return
	}
	// 向线上用户日志表写入数据
	System.Add_UserLogs_T(T_uuid, "本地版-任务", "修改", Task_r)

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
	c.ServeJSON()

}

// 更新线上数据后台执行
func (c *TaskDataController) TaskData_Up_TaskData_Back() {
	// 获取登录用户的uuid
	T_uuid, _ := lib.GetAdminT_Uuid(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))

	T_task_id := c.GetString("T_task_id")

	Task_r, err := NatsServer.Read_Task(T_task_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_task_id 错误!"}
		c.ServeJSON()
		return
	}
	// 采集中
	Task_r.T_delivery_state = 2
	err = NatsServer.Update_Task(Task_r)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "提交失败!"}
		c.ServeJSON()
		return
	}

	data := Nats.Up_TaskData_Back{
		T_uuid: T_uuid,
		Task:   Task_r,
	}
	b, _ := msgpack.Marshal(&data)
	_ = lib.Nats.Publish("ColdVerify_Local_Up_TaskData", b)

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
	c.ServeJSON()

}
