package controllers

import (
	"ColdVerify_server/conf"
	"ColdVerify_server/lib"
	"ColdVerify_server/lib/wx"
	"ColdVerify_server/logs"
	"ColdVerify_server/models/Account"
	"ColdVerify_server/models/InfoCollection"
	"ColdVerify_server/models/System"
	"ColdVerify_server/models/Task"
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"time"
)

type InfoCollectionController struct {
	beego.Controller
}

// 列表 -
func (c *InfoCollectionController) 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
	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_name := c.GetString("T_name")
	T_uuid := c.GetString("T_uuid")
	T_status, _ := c.GetInt("T_status")

	UserMap := Account.UserListToMap(Account.Read_User_List_ALL_1())
	AdminMap := Account.AdminListToMap(Account.Read_Admin_List_ALL_1())
	InfoTemplateMap := InfoCollection.InfoTemplateListToMap(InfoCollection.Read_InfoTemplate_List_ALL())
	InfoTemplateClassMap := InfoCollection.InfoTemplateClassListToMap(InfoCollection.Read_InfoTemplateClass_List_ALL())

	var cnt int
	List, cnt := InfoCollection.Read_InfoCollection_List(T_uuid, T_name, T_status, UserMap, AdminMap, InfoTemplateMap, InfoTemplateClassMap, 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 = cnt

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

// 用户列表
func (c *InfoCollectionController) UserList() {
	// 验证登录 User_is, User_r
	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
	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_name := c.GetString("T_name")
	T_status, _ := c.GetInt("T_status")
	UserMap := Account.UserListToMap(Account.Read_User_List_ALL_1())
	AdminMap := Account.AdminListToMap(Account.Read_Admin_List_ALL_1())
	InfoTemplateMap := InfoCollection.InfoTemplateListToMap(InfoCollection.Read_InfoTemplate_List_ALL())
	InfoTemplateClassMap := InfoCollection.InfoTemplateClassListToMap(InfoCollection.Read_InfoTemplateClass_List_ALL())

	var cnt int
	List, cnt := InfoCollection.Read_UserInfoCollection_List(User_r.T_uuid, T_name, T_status, UserMap, AdminMap, InfoTemplateMap, InfoTemplateClassMap, 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 = cnt

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

// 获取-
func (c *InfoCollectionController) Get() {
	// 验证登录 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
	}

	T_InfoCollection_id := c.GetString("T_InfoCollection_id")
	r, is := InfoCollection.Read_InfoCollection(T_InfoCollection_id)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "获取信息采集失败!"}
		c.ServeJSON()
		return
	}
	UserMap := Account.UserListToMap(Account.Read_User_List_ALL_1())
	AdminMap := Account.AdminListToMap(Account.Read_Admin_List_ALL_1())
	InfoTemplateMap := InfoCollection.InfoTemplateListToMap(InfoCollection.Read_InfoTemplate_List_ALL())
	InfoTemplateClassMap := InfoCollection.InfoTemplateClassListToMap(InfoCollection.Read_InfoTemplateClass_List_ALL())
	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: InfoCollection.InfoCollectionToInfoCollection_R(r, UserMap, AdminMap, InfoTemplateMap, InfoTemplateClassMap)}
	c.ServeJSON()
	return
}

// 添加-
func (c *InfoCollectionController) Add() {

	// 验证登录 User_is, User_r
	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
	}

	T_name := c.GetString("T_name")
	T_uuid := c.GetString("T_uuid") // 用户uuid
	T_InfoTemplate_class := c.GetString("T_InfoTemplate_class")
	T_InfoTemplate_id := c.GetString("T_InfoTemplate_id")

	var_ := InfoCollection.InfoCollection{
		T_uuid:               T_uuid,
		T_name:               T_name,
		T_InfoTemplate_class: T_InfoTemplate_class,
		T_InfoTemplate_id:    T_InfoTemplate_id,
		T_status:             1,
		T_State:              1,
		T_submit_uuid:        User_r.T_uuid,
	}

	T_InfoCollection_id, err := InfoCollection.Add_InfoCollection(var_)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: err.Error()}
		c.ServeJSON()
		return
	}
	System.Add_UserLogs_T(User_r.T_uuid, "信息采集管理", "添加", var_)
	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: T_InfoCollection_id}
	c.ServeJSON()
	return
}

// 修改-
func (c *InfoCollectionController) Up() {
	// 验证登录 User_is, User_r
	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
	}

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

	// .......
	clos := make([]string, 0)
	if len(T_name) > 0 {
		r.T_name = T_name
		clos = append(clos, "T_name")
	}
	if T_status > 0 {
		r.T_status = T_status
		clos = append(clos, "T_status")
	}
	if len(T_InfoTemplate_class) > 0 {
		r.T_InfoTemplate_class = T_InfoTemplate_class
		clos = append(clos, "T_InfoTemplate_class")
	}
	if T_InfoTemplate_id != r.T_InfoTemplate_id {
		// 修改任务信息采集模版
		Task.Update_Task_T_InfoTemplate_id(T_InfoCollection_id, T_InfoTemplate_id)
	}
	if len(T_InfoTemplate_id) > 0 {
		r.T_InfoTemplate_id = T_InfoTemplate_id
		clos = append(clos, "T_InfoTemplate_id")
	}

	if !InfoCollection.Update_InfoCollection(r, clos...) {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "修改失败!"}
		c.ServeJSON()
		return
	}
	System.Add_UserLogs_T(User_r.T_uuid, "信息采集管理", "修改", r)
	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
	c.ServeJSON()
	return
}

// 删除-
func (c *InfoCollectionController) Del() {
	// 验证登录 User_is, User_r
	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
	}

	T_InfoCollection_id := c.GetString("T_InfoCollection_id")
	if r, is := InfoCollection.Read_InfoCollection(T_InfoCollection_id); is {
		if !InfoCollection.Delete_InfoCollection(r) {
			c.Data["json"] = lib.JSONS{Code: 202, Msg: "删除失败！"}
			c.ServeJSON()
			return
		}
		System.Add_UserLogs_T(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 *InfoCollectionController) UpStatus() {
	// 验证登录 User_is, User_r
	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
	}

	T_InfoCollection_id := c.GetString("T_InfoCollection_id")
	T_status, _ := c.GetInt("T_status")
	T_reason := c.GetString("T_reason") //退回原因
	r, is := InfoCollection.Read_InfoCollection(T_InfoCollection_id)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "Id 错误!"}
		c.ServeJSON()
		return
	}
	//_, user_r := Account.Read_User_ByT_uuid(r.T_uuid)

	if T_status == InfoCollection.InfoCollectionStatusSubmitted && (r.T_status != InfoCollection.InfoCollectionStatusWaitSubmit && r.T_status != InfoCollection.InfoCollectionStatusReturn) {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: fmt.Sprintf("当前状态为%s，禁止提交为%s", InfoCollection.InfoCollectionStatusMap[r.T_status], InfoCollection.InfoCollectionStatusMap[T_status])}
		c.ServeJSON()
		return
	}

	if T_status == InfoCollection.InfoCollectionStatusReturnedMoney && r.T_status != InfoCollection.InfoCollectionStatusReceipt {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: fmt.Sprintf("当前状态为%s，禁止提交为%s", InfoCollection.InfoCollectionStatusMap[r.T_status], InfoCollection.InfoCollectionStatusMap[T_status])}
		c.ServeJSON()
		return
	}

	if T_status == InfoCollection.InfoCollectionStatusReturn && (r.T_status != InfoCollection.InfoCollectionStatusSubmitted && r.T_status != InfoCollection.InfoCollectionStatusReturn) {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: fmt.Sprintf("当前状态为%s，禁止提交为%s", InfoCollection.InfoCollectionStatusMap[r.T_status], InfoCollection.InfoCollectionStatusMap[T_status])}
		c.ServeJSON()
		return
	}

	if T_status == InfoCollection.InfoCollectionStatusReceipt && (r.T_status != InfoCollection.InfoCollectionStatusSubmitted && r.T_status != InfoCollection.InfoCollectionStatusReceipt) {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: fmt.Sprintf("当前状态为%s，禁止提交为%s", InfoCollection.InfoCollectionStatusMap[r.T_status], InfoCollection.InfoCollectionStatusMap[T_status])}
		c.ServeJSON()
		return
	}

	// 1待提交 2已提交 3已接收 4已退回 5已回款
	clos := make([]string, 0)
	if T_status > 0 {
		r.T_status = T_status
		clos = append(clos, "T_status")
	}
	//  2已提交  ，计算时间
	if T_status == InfoCollection.InfoCollectionStatusSubmitted {
		if len(r.T_end_time) == 0 {
			r.T_end_time = time.Now().Format("2006-01-02 15:04:05")
			r.T_time_interval, _ = lib.MinutesDifference(r.T_start_time, r.T_end_time)
			clos = append(clos, "T_end_time")
			clos = append(clos, "T_time_interval")
		}
	}
	if T_status == InfoCollection.InfoCollectionStatusReturn {
		r.T_return_times += 1
		clos = append(clos, "T_return_times")
	}

	var returnRecordList []InfoCollection.AuditRecord
	if len(r.T_audit_record) > 0 {
		err := json.Unmarshal([]byte(r.T_audit_record), &returnRecordList)
		if err != nil {
			logs.Error("JSON 反序列化失败:", err)
			return
		}
	}
	returnRecordList = append(returnRecordList, InfoCollection.AuditRecord{
		T_uuid:   User_r.T_uuid,
		T_status: T_status,
		T_reason: T_reason,
		T_time:   time.Now().Format("2006-01-02 15:04:05"),
	})
	returnRecordJson, err := json.Marshal(returnRecordList)
	if err != nil {
		logs.Error("JSON 反序列化失败:", err)
		return
	}
	r.T_audit_record = string(returnRecordJson)
	clos = append(clos, "T_audit_record")

	if !InfoCollection.Update_InfoCollection(r, clos...) {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "修改失败!"}
		c.ServeJSON()
		return
	}
	//AdminMap := Account.AdminListToMap(Account.Read_Admin_List_ALL_1())
	_, company_r := Account.Read_User_ByT_uuid(r.T_uuid)
	// 已提交   [报告负责人]
	if T_status == InfoCollection.InfoCollectionStatusSubmitted {
		go wx.WxSend(conf.VdelUuid, fmt.Sprintf("【%s-%s】信息采集 %s", company_r.T_name, r.T_name, InfoCollection.InfoCollectionStatusMap[T_status]))
	}

	// 已退回
	if T_status == InfoCollection.InfoCollectionStatusReturn {
		System.Add_News(r.T_submit_uuid, fmt.Sprintf("【%s-%s】信息采集 %s,%s", company_r.T_name, r.T_name, InfoCollection.InfoCollectionStatusMap[T_status], T_reason), "")
		go wx.WxSend(r.T_submit_uuid, fmt.Sprintf("【%s-%s】信息采集 %s,%s", company_r.T_name, r.T_name, InfoCollection.InfoCollectionStatusMap[T_status], T_reason))
	}

	if T_status == InfoCollection.InfoCollectionStatusReturnedMoney {
		go wx.WxSend(conf.BoosUuid, fmt.Sprintf("【%s-%s】已回款", company_r.T_name, r.T_name))
	}

	System.Add_UserLogs_T(User_r.T_uuid, "信息采集管理", "修改状态", r)
	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
	c.ServeJSON()
	return
}

// 退回记录列表
func (c *InfoCollectionController) AuditRecordList() {
	// 验证登录 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
	}

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

	var auditRecordList []InfoCollection.AuditRecord
	if len(r.T_audit_record) > 0 {
		err := json.Unmarshal([]byte(r.T_audit_record), &auditRecordList)
		if err != nil {
			logs.Error("JSON 反序列化失败:", err)
			return
		}
	}
	AdminMap := Account.AdminListToMap(Account.Read_Admin_List_ALL_1())
	var auditRecordList2 []InfoCollection.AuditRecord

	if T_status == 0 {
		for i := 0; i < len(auditRecordList); i++ {
			auditRecordList[i].T_uuid_name = AdminMap[auditRecordList[i].T_uuid]
			auditRecordList2 = append(auditRecordList2, auditRecordList[i])
		}
		c.Data["json"] = lib.JSONS{Data: auditRecordList2, Code: 200, Msg: "ok!"}
		c.ServeJSON()
		return
	}

	for i := 0; i < len(auditRecordList); i++ {
		if auditRecordList[i].T_status == T_status {
			auditRecordList[i].T_uuid_name = AdminMap[auditRecordList[i].T_uuid]
			auditRecordList2 = append(auditRecordList2, auditRecordList[i])
		}
	}
	c.Data["json"] = lib.JSONS{Data: auditRecordList2, Code: 200, Msg: "ok!"}
	c.ServeJSON()
	return
}

// 信息采集统计
func (c *InfoCollectionController) Statistics() {
	// 验证登录 User_is, User_r
	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
	}

	List, cnt := InfoCollection.Read_UserInfoCollection_List(User_r.T_uuid, "", 0, map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}, 0, 999)
	res := make(map[int]int)
	for k, _ := range InfoCollection.InfoCollectionStatusMap {
		res[k] = 0
	}
	res[0] = cnt
	for _, r := range List {
		res[r.T_status] += 1
	}

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

// 修改-
func (c *InfoCollectionController) Copy() {
	// 验证登录 User_is, User_r
	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
	}

	T_name := c.GetString("T_name")
	T_InfoCollection_id := c.GetString("T_InfoCollection_id") // 信息采集id
	r, is := InfoCollection.Read_InfoCollection(T_InfoCollection_id)
	if !is {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "Id 错误!"}
		c.ServeJSON()
		return
	}

	var_ := InfoCollection.InfoCollection{
		T_uuid:               r.T_uuid,
		T_name:               T_name,
		T_InfoTemplate_class: r.T_InfoTemplate_class,
		T_InfoTemplate_id:    r.T_InfoTemplate_id,
		T_status:             1,
		T_State:              1,
		T_submit_uuid:        User_r.T_uuid,
	}

	T_InfoCollection_id, err := InfoCollection.Add_InfoCollection(var_)
	if err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: err.Error()}
		c.ServeJSON()
		return
	}
	System.Add_UserLogs_T(User_r.T_uuid, "信息采集管理", "复制", r)
	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
	c.ServeJSON()
	return
}
