package controllers

import (
	"FollowUp_Notice/conf"
	"FollowUp_Notice/lib"
	"FollowUp_Notice/models/Account"
	"FollowUp_Notice/models/Patient"
	"FollowUp_Notice/models/System"
	"FollowUp_Notice/models/Tag"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"strconv"
	"strings"
)

type TagController struct {
	beego.Controller
	User Account.User
}

func (c *TagController) Prepare() {
	c.User = *Account.User_r
}

// 疾病
func (c *TagController) Tag_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_name := c.GetString("T_name")

	R_List, R_cnt := Tag.Read_Tag_List(c.User.Id, T_name, page, page_z)

	var r_jsons lib.R_JSONS
	r_jsons.Num = R_cnt
	r_jsons.Data = R_List
	r_jsons.Page = page
	r_jsons.Page_size = int(math.Ceil(float64(R_cnt) / float64(page_z)))

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

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

	var_ := Tag.Tag{
		T_name:  T_name,
		T_sort:  T_sort,
		T_State: 1,
		T_uid:   c.User.Id,
	}

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

	System.Add_UserLogs_T(c.User.T_uuid, "标签", "添加", var_)

	c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: Id}
	c.ServeJSON()
	return
}
func (c *TagController) Tag_Edit() {
	T_id, _ := c.GetInt("T_id")
	T_name := c.GetString("T_name")
	T_sort, _ := c.GetInt("T_sort")

	Tag_r, err := Tag.Read_Tag_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 {
		Tag_r.T_name = T_name
	}
	Tag_r.T_sort = T_sort

	if err = Tag.Update_Tag(Tag_r, "T_name", "T_sort"); err != nil {
		c.Data["json"] = lib.JSONS{Code: 203, Msg: "修改失败"}
		c.ServeJSON()
		return
	}

	System.Add_UserLogs_T(c.User.T_uuid, "标签", "修改", Tag_r)

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

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

	if err = Tag.Delete_Tag(Tag_r); err != nil {
		c.Data["json"] = lib.JSONS{Code: 202, Msg: "删除失败!"}
		c.ServeJSON()
		return
	}
	PatientList, _ := Patient.Read_Patient_List(0, "", "", T_id, 0, 0, 0, 0, 0, 0, 0, 9999)
	for _, r := range PatientList {
		T_tag := strings.Replace(r.T_tag_str, fmt.Sprintf("|%d|", T_id), "", -1)
		var_ := Patient.Patient{Id: r.Id, T_tag: T_tag}
		Patient.Update_Patient(var_, "T_tag")
	}
	System.Add_UserLogs(c.User.T_uuid, "标签", "删除", strconv.Itoa(T_id))

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