package controllers

import (
	"ColdVerify_server/conf"
	"ColdVerify_server/lib"
	"ColdVerify_server/models/Account"
	"ColdVerify_server/models/InfoCollection"
	"ColdVerify_server/models/System"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"strconv"
	"strings"
	"time"
)

type InfoTemplateController struct {
	beego.Controller
	User_r Account.Admin // 登陆的用户
}

func (c *InfoTemplateController) Prepare() {
	GetCookie := c.Ctx.GetCookie("User_tokey")
	GetString := c.GetString("User_tokey")
	// 此接口单独从body获取token验证，此处不做验证
	if strings.Contains(c.Ctx.Request.URL.Path, "/InfoTemplateMapData/Pu") {
		return
	}

	// 验证登录 User_is, User_r
	User_r, User_is := Account.Verification_Admin(GetCookie, GetString)
	if !User_is {
		c.Data["json"] = lib.JSONS{Code: 201, Msg: "请重新登录!"}
		c.ServeJSON()
		return
	}

	// 经销商只能访问列表接口，不能操作

	//if len(User_r.T_Distributor_id) > 0 {
	//	checkUrl := []string{"Add", "Up", "Del", "Copy"}
	//	for _, v := range checkUrl {
	//		if strings.Contains(c.Ctx.Request.URL.Path, v) {
	//			c.Data["json"] = lib.JSONS{Code: 202, Msg: "没有操作权限!"}
	//			c.ServeJSON()
	//			return
	//		}
	//	}
	//}

	c.User_r = User_r
}

// 列表 -
func (c *InfoTemplateController) 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
	}

	T_class, _ := c.GetInt("T_class")
	if T_class <= 0 {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_class Err!"}
		c.ServeJSON()
		return
	}

	T_name := c.GetString("T_name")

	var cnt int64
	List, cnt := InfoCollection.Read_InfoTemplate_List(T_class, T_name, 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 *InfoTemplateController) Add() {

	T_name := c.GetString("T_name")
	T_sort, _ := c.GetInt("T_sort")
	T_class, _ := c.GetInt("T_class")

	var_ := InfoCollection.InfoTemplate{
		T_class: T_class,
		T_name:  T_name,
		T_sort:  T_sort,
	}

	Id, is := InfoCollection.Add_InfoTemplate(var_)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "添加失败!"}
		c.ServeJSON()
		return
	}
	System.Add_UserLogs_T(c.User_r.T_uuid, "信息采集信息采集模版", "添加", var_)

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

// 修改-
func (c *InfoTemplateController) Up() {

	T_name := c.GetString("T_name")
	T_sort, T_sort_err := c.GetInt("T_sort")

	T_InfoTemplate_id := c.GetString("T_InfoTemplate_id")

	r, is := InfoCollection.Read_InfoTemplate(T_InfoTemplate_id)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "Id 错误!"}
		c.ServeJSON()
		return
	}

	// .......
	if len(T_name) > 0 {
		r.T_name = T_name
	}

	if T_sort_err == nil {
		r.T_sort = T_sort
	}

	// .......
	if !InfoCollection.Update_InfoTemplate(r, "T_name", "T_sort") {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "修改失败!"}
		c.ServeJSON()
		return
	}
	System.Add_UserLogs_T(c.User_r.T_uuid, "信息采集信息采集模版", "修改", r)

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

// 删除-
func (c *InfoTemplateController) Del() {

	T_InfoTemplate_id := c.GetString("T_InfoTemplate_id")

	r, is := InfoCollection.Read_InfoTemplate(T_InfoTemplate_id)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "Id 错误!"}
		c.ServeJSON()
		return
	}
	if !InfoCollection.Delete_InfoTemplate(r) {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "删除失败！"}
		c.ServeJSON()
		return
	}

	mapList, _ := InfoCollection.Read_InfoTemplateMap_List(T_InfoTemplate_id, 0, 0)
	for _, v := range mapList {
		if vtm, is := InfoCollection.Read_InfoTemplateMap(v.T_id); is {
			InfoCollection.Delete_InfoTemplateMap(vtm)
		}
	}

	System.Add_UserLogs_T(c.User_r.T_uuid, "信息采集信息采集模版", "删除", r)
	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
	c.ServeJSON()
	return

}

// 复制-
func (c *InfoTemplateController) Copy() {

	T_InfoTemplate_id := c.GetString("T_InfoTemplate_id")
	T_name := c.GetString("T_name")
	r, is := InfoCollection.Read_InfoTemplate(T_InfoTemplate_id)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "Id 错误!"}
		c.ServeJSON()
		return
	}

	var_ := InfoCollection.InfoTemplate{
		T_class: r.T_class,
		T_name:  T_name,
		T_sort:  r.T_sort,
	}

	new_id, is := InfoCollection.Add_InfoTemplate(var_)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "复制失败!"}
		c.ServeJSON()
		return
	}

	mapList, _ := InfoCollection.Read_InfoTemplateMap_List(T_InfoTemplate_id, 0, 0)
	tempMap := make(map[string]struct{})
	idList := make([]string, len(mapList))
	// 生成mapList长度的T_id
	for i := 0; i < len(mapList); i++ {
		// 生成编号
		rand_x := 0
		T_id := ""
		for true {
			T_id = lib.GetRandstring(4, "", int64(rand_x))
			_, is = InfoCollection.Read_InfoTemplateMap(T_id)
			if !is {
				if _, ok := tempMap[T_id]; !ok {
					break
				}
			}
			rand_x += 1
		}
		tempMap[T_id] = struct{}{}
		idList[i] = T_id
	}
	mapInsertList := make([]InfoCollection.InfoTemplateMap, 0)
	for i, v := range mapList {
		vtm := InfoCollection.InfoTemplateMap{
			T_id:              idList[i],
			T_InfoTemplate_id: new_id,
			T_name:            v.T_name,
			T_text:            v.T_text,
			T_label:           v.T_label,
			T_sort:            v.T_sort,
		}

		mapInsertList = append(mapInsertList, vtm)
	}

	_, is = InfoCollection.Add_InfoTemplateMapMulti(mapInsertList)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "复制失败!"}
		c.ServeJSON()
		return
	}

	System.Add_UserLogs_T(c.User_r.T_uuid, "信息采集信息采集模版", "复制", var_)

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

/// -----------------------------------------------------------------------------

// 标签列表 -
func (c *InfoTemplateController) Map_List() {
	// 验证登录 User_is, User_r
	_, User_is := Account.Verification_Admin(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
	if !User_is {
		c.Data["json"] = lib.JSONS{Code: 201, Msg: "请重新登录!"}
		c.ServeJSON()
		return
	}

	var r_jsons lib.R_JSONS

	T_sort, _ := c.GetInt("T_sort")           // 排序
	T_flow_sort, _ := c.GetInt("T_flow_sort") // 验证流程排序

	T_InfoTemplate_id := c.GetString("T_InfoTemplate_id")

	var cnt int64
	List, cnt := InfoCollection.Read_InfoTemplateMap_List(T_InfoTemplate_id, T_sort, T_flow_sort)
	r_jsons.List = List
	r_jsons.Num = int(cnt)
	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: r_jsons}
	c.ServeJSON()
	return
}

// 标签添加-
func (c *InfoTemplateController) Map_Add() {

	T_InfoTemplate_id := c.GetString("T_InfoTemplate_id")
	T_name := c.GetString("T_name")
	T_text := c.GetString("T_text")
	T_label, _ := c.GetInt("T_label")
	T_sort, _ := c.GetInt("T_sort")

	var_ := InfoCollection.InfoTemplateMap{
		T_InfoTemplate_id: T_InfoTemplate_id,
		T_name:            T_name,
		T_text:            T_text,
		T_label:           T_label,
		T_sort:            T_sort,
	}

	Id, is := InfoCollection.Add_InfoTemplateMap(var_)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "添加失败!"}
		c.ServeJSON()
		return
	}

	System.Add_UserLogs_T(c.User_r.T_uuid, "信息采集信息采集模版标签", "添加", var_)

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

// 标签修改-
func (c *InfoTemplateController) Map_Up() {

	T_name := c.GetString("T_name")
	T_text := c.GetString("T_text")
	T_label, T_label_err := c.GetInt("T_label")
	T_sort, T_sort_err := c.GetInt("T_sort")

	T_id := c.GetString("T_id")

	r, is := InfoCollection.Read_InfoTemplateMap(T_id)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "Id 错误!"}
		c.ServeJSON()
		return
	}

	// .......
	if len(T_name) > 0 {
		r.T_name = T_name
	}
	if len(T_text) > 0 {
		r.T_text = T_text
	}
	if T_label_err == nil {
		r.T_label = T_label
	}
	if T_sort_err == nil {
		r.T_sort = T_sort
	}

	if !InfoCollection.Update_InfoTemplateMap(r, "T_name", "T_label", "T_text", "T_sort") {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "修改失败!"}
		c.ServeJSON()
		return
	}

	System.Add_UserLogs_T(c.User_r.T_uuid, "信息采集信息采集模版标签", "修改", r)

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

// 标签删除-
func (c *InfoTemplateController) Map_Del() {

	T_id := c.GetString("T_id")

	if r, is := InfoCollection.Read_InfoTemplateMap(T_id); is {
		if !InfoCollection.Delete_InfoTemplateMap(r) {
			c.Data["json"] = lib.JSONS{Code: 202, Msg: "删除失败！"}
			c.ServeJSON()
			return
		}
		System.Add_UserLogs_T(c.User_r.T_uuid, "信息采集信息采集模版标签", "删除", r)
		c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
		c.ServeJSON()
		return
	}

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

/// -----------------------------------------------------------------------------

// 标签数据列表 -
func (c *InfoTemplateController) Map_Data_List() {

	T_InfoTemplate_id := c.GetString("T_InfoTemplate_id")

	T_InfoCollection_id := c.GetString("T_InfoCollection_id")
	_, is := InfoCollection.Read_InfoCollection(T_InfoCollection_id)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_InfoCollection_id 错误!"}
		c.ServeJSON()
		return
	}

	Map_List := InfoCollection.Read_InfoTemplateMap_List_For_Data(T_InfoTemplate_id)
	Data := InfoCollection.Read_InfoTemplateMapData_List(T_InfoCollection_id, T_InfoTemplate_id, Map_List)

	type JSONS struct {
		//必须的大写开头
		Code int16
		Msg  string
		Data interface{} // 泛型
	}

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

// 添加标签数据
func (c *InfoTemplateController) Map_Data_Pu() {
	//验证登录 User_is, User_r

	type RequestBody struct {
		User_tokey          string
		T_InfoCollection_id string
		T_InfoTemplate_id   string
		InfoTemplateMapData []InfoCollection.InfoTemplateMapData_R
	}

	var body RequestBody
	data := c.Ctx.Input.RequestBody
	err := json.Unmarshal(data, &body)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "json返序列化失败:" + err.Error()}
		c.ServeJSON()
	}

	User_r, User_is := Account.Verification_Admin(body.User_tokey, "")
	if !User_is {
		System.Add_UserLogs_T(User_r.T_uuid, "信息采集模版标签数据", "未登录-保存", body)
		c.Data["json"] = lib.JSONS{Code: 201, Msg: "请重新登录!"}
		c.ServeJSON()
		return
	}
	infoCollection, is := InfoCollection.Read_InfoCollection(body.T_InfoCollection_id)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_InfoCollection_id 错误!"}
		c.ServeJSON()
		return
	}

	// 如果信息采集开始时间为空，则设置为当前时间
	if len(infoCollection.T_start_time) == 0 {
		infoCollection.T_start_time = time.Now().Format("2006-01-02 15:04:05")
		if !InfoCollection.Update_InfoCollection(infoCollection, "T_start_time") {
			c.Data["json"] = lib.JSONS{Code: 202, Msg: "修改信息采集开始时间失败!"}
			c.ServeJSON()
			return
		}
	}

	MapDataList := make([]InfoCollection.InfoTemplateMapData, 0)
	for _, v := range body.InfoTemplateMapData {
		val := InfoCollection.InfoTemplateMapData{
			T_InfoCollection_id:  body.T_InfoCollection_id,
			T_InfoTemplate_id:    body.T_InfoTemplate_id,
			T_InfoTemplateMap_id: v.T_InfoTemplateMap_id,
			T_value:              v.T_value,
		}
		MapDataList = append(MapDataList, val)
	}
	ids, is := InfoCollection.AddOrUpdate_InfoTemplateMapData(MapDataList)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "保存失败"}
		c.ServeJSON()
		return
	}
	System.Add_UserLogs_T(User_r.T_uuid, "信息采集模版标签数据", "保存", body)

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

func (c *InfoTemplateController) Map_Data_Copy() {

	T_copy_InfoCollection_id := c.GetString("T_copy_InfoCollection_id")
	copy_InfoCollection, is := InfoCollection.Read_InfoCollection(T_copy_InfoCollection_id)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_copy_InfoCollection_id 错误!"}
		c.ServeJSON()
		return
	}
	T_paste_InfoCollection_id := c.GetString("T_paste_InfoCollection_id")
	paste_InfoCollection, is := InfoCollection.Read_InfoCollection(T_paste_InfoCollection_id)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "T_paste_InfoCollection_id 错误!"}
		c.ServeJSON()
		return
	}

	if copy_InfoCollection.T_InfoTemplate_id != paste_InfoCollection.T_InfoTemplate_id {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "仅支持相同信息采集模版间复制!"}
		c.ServeJSON()
		return
	}

	list := InfoCollection.Read_MapData_List(T_copy_InfoCollection_id, copy_InfoCollection.T_InfoTemplate_id)

	MapDataList := make([]InfoCollection.InfoTemplateMapData, 0)
	for _, v := range list {
		val := InfoCollection.InfoTemplateMapData{
			T_InfoCollection_id:  paste_InfoCollection.T_InfoCollection_id,
			T_InfoTemplate_id:    paste_InfoCollection.T_InfoTemplate_id,
			T_InfoTemplateMap_id: v.T_InfoTemplateMap_id,
			T_value:              v.T_value,
		}
		MapDataList = append(MapDataList, val)
	}
	var ids []int64
	ids, is = InfoCollection.AddOrUpdate_InfoTemplateMapData(MapDataList)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "保存失败"}
		c.ServeJSON()
		return
	}
	System.Add_UserLogs_T(c.User_r.T_uuid, "信息采集模版标签数据", "复制", MapDataList)

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

func (c *InfoTemplateController) Class_List() {
	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: InfoCollection.Read_InfoTemplateClass_List()}
	c.ServeJSON()
	return
}
func (c *InfoTemplateController) Class_Add() {

	T_name := c.GetString("T_name")
	T_fid, _ := c.GetInt("T_fid")

	var_ := InfoCollection.InfoTemplateClass{
		T_name:  T_name,
		T_fid:   T_fid,
		T_State: 1,
	}

	Id, err := InfoCollection.Add_InfoTemplateClass(var_)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 203, Msg: "添加失败"}
		c.ServeJSON()
		return
	}

	System.Add_UserLogs_T(c.User_r.T_uuid, "信息采集模版分类", "添加", var_)

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

	T_id, _ := c.GetInt("T_id")
	T_name := c.GetString("T_name")

	R_InfoTemplateToolClass, err := InfoCollection.Read_InfoTemplateClass_ById(T_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 203, Msg: "T_id Err!"}
		c.ServeJSON()
		return
	}

	if len(T_name) > 0 {
		R_InfoTemplateToolClass.T_name = T_name
	}

	if is := InfoCollection.Update_InfoTemplateClass(R_InfoTemplateToolClass, "T_name"); !is {
		c.Data["json"] = lib.JSONS{Code: 203, Msg: "修改失败"}
		c.ServeJSON()
		return
	}

	System.Add_UserLogs_T(c.User_r.T_uuid, "信息采集模版分类", "修改", R_InfoTemplateToolClass)

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

	T_id, _ := c.GetInt("T_id")
	R_InfoTemplateToolClass, err := InfoCollection.Read_InfoTemplateClass_ById(T_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 203, Msg: "T_id Err!"}
		c.ServeJSON()
		return
	}

	ids := InfoCollection.ReadInfoTemplateClassIds_T_path(R_InfoTemplateToolClass.T_path)

	if is := InfoCollection.Delete_InfoTemplateClass_ByIds(ids); !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "删除失败!"}
		c.ServeJSON()
		return
	}

	System.Add_UserLogs(c.User_r.T_uuid, "信息采集模版分类", "删除", strconv.Itoa(T_id))

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

// 复制信息采集-分类-标签
func (c *InfoTemplateController) Class_Copy() {

	T_id, _ := c.GetInt("T_id") // 要复制的信息采集分类id
	T_name := c.GetString("T_name")

	// 查询要复制的信息采集分类id
	R_InfoTemplateClass, err := InfoCollection.Read_InfoTemplateClass_ById(T_id)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 203, Msg: "T_id Err!"}
		c.ServeJSON()
		return
	}
	if len(T_name) > 0 && T_name != R_InfoTemplateClass.T_name {
		R_InfoTemplateClass.T_name = T_name
	} else {
		R_InfoTemplateClass.T_name = R_InfoTemplateClass.T_name + "_副本"
	}

	_, err = InfoCollection.CopyInfoTemplateClassTree(R_InfoTemplateClass.T_path, R_InfoTemplateClass.T_fid, R_InfoTemplateClass.T_name)

	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "复制信息采集模版分类失败"}
		c.ServeJSON()
		return
	}

	System.Add_UserLogs_T(c.User_r.T_uuid, "信息采集模版分类", "复制", T_id)

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