package controllers

import (
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"XT_New/utils"
	"encoding/json"
	"fmt"
	"reflect"
	"strconv"
	"time"

	"github.com/astaxie/beego"
)

type DataApiController struct {
	BaseAuthAPIController
}

func DataApiRegistRouters() {
	beego.Router("/api/getconfiglist", &DataApiController{}, "get,post:GetConfigList")
	beego.Router("/api/createconfig", &DataApiController{}, "Post:CreateConfig")
	beego.Router("/api/createchildconfig", &DataApiController{}, "Post:CreateChildConfig")
	beego.Router("/api/updatechildconfig", &DataApiController{}, "Post:UpdateChildConfig")
	beego.Router("/api/deletechildconfig", &DataApiController{}, "Post:DeleteChildConfig")
	beego.Router("/api/updatetemplate", &DataApiController{}, "Post:UpdateTemplate")

	beego.Router("/api/getadviceconfigs", &DataApiController{}, "Get:GetAdviceConfigs")
	beego.Router("/api/getalladviceconfig", &DataApiController{}, "Get:GetAllAdviceConfigs")

	beego.Router("/api/drugdic/create", &DataApiController{}, "Post:CreateDrugDic")
	beego.Router("/api/drugdic/update", &DataApiController{}, "Put:UpdateDrugDic")
	beego.Router("/api/drugdic/delete", &DataApiController{}, "Delete:DeleteDrugDic")
	beego.Router("/api/drugway/create", &DataApiController{}, "Post:CreateDrugWay")
	beego.Router("/api/drugway/update", &DataApiController{}, "Put:UpdateDrugWay")
	beego.Router("/api/drugway/delete", &DataApiController{}, "Delete:DeleteDrugWay")
	beego.Router("/api/executionfrequency/create", &DataApiController{}, "Post:CreateExecutionFrequency")
	beego.Router("/api/executionfrequency/update", &DataApiController{}, "Put:UpdateExecutionFrequency")
	beego.Router("/api/executionfrequency/delete", &DataApiController{}, "Delete:DeleteExecutionFrequency")
	beego.Router("/api/advicetemplate/create", &DataApiController{}, "Post:CreateAdviceTemplate")
	beego.Router("/api/subadvice/create", &DataApiController{}, "Post:CreateSubAdviceTemplate")
	beego.Router("/api/advicetemplate/update", &DataApiController{}, "Put:UpdateAdviceTemplate")
	beego.Router("/api/advicetemplate/delete", &DataApiController{}, "Delete:DeleteAdviceTemplate")
	beego.Router("/api/advicetemplate/add", &DataApiController{}, "Post:CreateSingleAdviceTemplate")
	beego.Router("/api/adviceparenttemplate/delete", &DataApiController{}, "Delete:DeleteParentAdviceTemplate")
	beego.Router("/api/template/modify", &DataApiController{}, "Post:ModifyTemplateName")

	beego.Router("/api/filed/show", &DataApiController{}, "Post:ModifyFiledIsShow")
	beego.Router("/article/hanleupdatetwo", &DataApiController{}, "Get:GetHandleData")
	beego.Router("/article/updatedatatwo", &DataApiController{}, "Post:UpdateDataTwo")
}

//GetPatientsList 取配置信息列表
func (c *DataApiController) GetConfigList() {
	adminUserInfo := c.GetAdminUserInfo()

	configList, _ := service.GetConfigList(adminUserInfo.CurrentOrgId)

	c.ServeSuccessJSON(map[string]interface{}{
		"configlist": configList,
	})
	return

}

//CreateConfig  创建配置信息
func (c *DataApiController) CreateConfig() {
	adminUserInfo := c.GetAdminUserInfo()

	var dataconfig models.Dataconfig
	var resultConfig models.ConfigViewModel
	code := configFormData(&dataconfig, c.Ctx.Input.RequestBody)
	if code > 0 {
		c.ServeFailJSONWithSGJErrorCode(code)
		return
	}
	// 验证关键字段的值是否重复
	// if (dataconfig.Module == "education" || dataconfig.Module == "summary") {
	// 	thisConfig,_:=service.FindConfigByTitle(dataconfig.Module, dataconfig.FieldName,dataconfig.OrgId)
	// 	if thisConfig.ID >0 {
	// 		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeFieldExist)
	// 		return
	// 	}
	// } else {
	// 	thisConfig,_:=service.FindConfigByFieldname(dataconfig.Module, dataconfig.FieldName,dataconfig.OrgId)
	// 	if thisConfig.ID >0 {
	// 		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeFieldExist)
	// 		return
	// 	}
	// }
	// fieldValue:=service.GetChildValue(dataconfig.Module, dataconfig.ParentId)
	// dataconfig.Value = fieldValue+1

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	dataconfig.OrgId = adminUserInfo.CurrentOrgId
	dataconfig.CreateUserId = adminUserInfo.AdminUser.Id
	dataconfig.Status = 1
	dataconfig.CreatedTime = time.Now().Format("2006-01-02 15:04:05")
	dataconfig.UpdatedTime = time.Now().Format("2006-01-02 15:04:05")
	dataconfig.Remark = string(dataBody["remark"].(string))
	if dataBody["order"] != nil {
		dataconfig.Order = int64(dataBody["order"].(float64))
	} else {
		dataconfig.Order = 0
	}

	err = service.CreateConfig(&dataconfig)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateConfig)
		return
	} else {
		resultConfig.ID = dataconfig.ID
		resultConfig.Module = dataconfig.Module
		resultConfig.Name = dataconfig.Name
		resultConfig.OrgId = dataconfig.OrgId
		resultConfig.ParentId = dataconfig.ParentId
		resultConfig.FieldName = dataconfig.FieldName
		resultConfig.CreateUserId = dataconfig.CreateUserId
		resultConfig.Title = dataconfig.Title
		resultConfig.Content = dataconfig.Content
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"dataconfig": resultConfig,
		"msg":        "ok",
	})
	return
}

func (c *DataApiController) UpdateTemplate() {
	adminUserInfo := c.GetAdminUserInfo()
	var dataconfig models.Dataconfig
	code := configFormData(&dataconfig, c.Ctx.Input.RequestBody)
	if code > 0 {
		c.ServeFailJSONWithSGJErrorCode(code)
		return
	}

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	dataconfig.OrgId = adminUserInfo.CurrentOrgId
	dataconfig.CreateUserId = adminUserInfo.AdminUser.Id
	dataconfig.Status = 1
	dataconfig.CreatedTime = time.Now().Format("2006-01-02 15:04:05")
	dataconfig.UpdatedTime = time.Now().Format("2006-01-02 15:04:05")
	dataconfig.Remark = string(dataBody["remark"].(string))
	if dataBody["order"] != nil {
		dataconfig.Order = int64(dataBody["order"].(float64))
	} else {
		dataconfig.Order = 0
	}

	// 验证关键字段的值是否重复
	// cur_id := int64(dataBody["id"].(float64))
	// thisConfig,_:=service.FindConfigByTitleForUpdate(dataconfig.Module, dataconfig.Title,dataconfig.OrgId,cur_id)
	// if thisConfig.ID >0 {
	// 	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeFieldExist)
	// 	return
	// }

	configOrgId := int64(dataBody["org_id"].(float64))
	if configOrgId == 0 {
		dataconfig.DeleteIdSystem = int64(dataBody["id"].(float64))
		err := service.CreateConfig(&dataconfig)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateConfig)
			return
		}
	} else {
		dataconfig.ID = int64(dataBody["id"].(float64))
		err = service.UpdateTemplate(&dataconfig)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeUpdateConfig)
			return
		}
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"dataconfig": dataconfig,
		"msg":        "ok",
	})
	return
}

func (c *DataApiController) UpdateChildConfig() {
	adminUserInfo := c.GetAdminUserInfo()
	var dataconfig models.Dataconfig
	code := configChildFormData(&dataconfig, c.Ctx.Input.RequestBody)
	if code > 0 {
		c.ServeFailJSONWithSGJErrorCode(code)
		return
	}

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	dataconfig.OrgId = adminUserInfo.CurrentOrgId
	dataconfig.CreateUserId = adminUserInfo.AdminUser.Id
	dataconfig.Status = 1
	dataconfig.Value = int(int64(dataBody["value"].(float64)))
	dataconfig.CreatedTime = time.Now().Format("2006-01-02 15:04:05")
	dataconfig.UpdatedTime = time.Now().Format("2006-01-02 15:04:05")
	dataconfig.Remark = string(dataBody["remark"].(string))
	if dataBody["order"] != nil {
		dataconfig.Order = int64(dataBody["order"].(float64))
	} else {
		dataconfig.Order = 0
	}
	configOrgId := int64(dataBody["org_id"].(float64))

	// 验证关键字段的值是否重复
	// configId := int64(dataBody["id"].(float64))
	// thisConfig,_:=service.FindConfigByNameForUpdate(dataconfig.Module, dataconfig.Name,dataconfig.ParentId,dataconfig.OrgId,configId)
	// if thisConfig.ID >0 {
	// 	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeFieldExist)
	// 	return
	// }

	if configOrgId == 0 {
		dataconfig.DeleteIdSystem = int64(dataBody["id"].(float64))
		err := service.CreateConfig(&dataconfig)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateConfig)
			return
		}
	} else {
		dataconfig.ID = int64(dataBody["id"].(float64))
		err = service.UpdateChildConfig(&dataconfig)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeUpdateConfig)
			return
		}
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"dataconfig": dataconfig,
		"msg":        "ok",
	})
	return
}

func (c *DataApiController) DeleteChildConfig() {
	adminUserInfo := c.GetAdminUserInfo()
	var dataconfig models.Dataconfig
	code := configChildFormData(&dataconfig, c.Ctx.Input.RequestBody)
	if code > 0 {
		c.ServeFailJSONWithSGJErrorCode(code)
		return
	}

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	dataconfig.OrgId = adminUserInfo.CurrentOrgId
	dataconfig.CreateUserId = adminUserInfo.AdminUser.Id
	dataconfig.Status = 0
	dataconfig.Value = int(int64(dataBody["value"].(float64)))
	dataconfig.CreatedTime = time.Now().Format("2006-01-02 15:04:05")
	dataconfig.UpdatedTime = time.Now().Format("2006-01-02 15:04:05")
	dataconfig.Remark = string(dataBody["remark"].(string))
	if dataBody["order"] != nil {
		dataconfig.Order = int64(dataBody["order"].(float64))
	} else {
		dataconfig.Order = 0
	}
	configOrgId := int64(dataBody["org_id"].(float64))
	if configOrgId == 0 {
		dataconfig.DeleteIdSystem = int64(dataBody["id"].(float64))
		err := service.CreateConfig(&dataconfig)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateConfig)
			return
		}
	} else {
		dataconfig.ID = int64(dataBody["id"].(float64))
		err := service.DeleteChildConfig(&dataconfig)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeUpdateConfig)
			return
		}
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"dataconfig": dataconfig,
		"msg":        "ok",
	})
	return
}

//CreateChildConfig  创建子配置信息
func (c *DataApiController) CreateChildConfig() {
	adminUserInfo := c.GetAdminUserInfo()

	var dataconfig models.Dataconfig
	code := configChildFormData(&dataconfig, c.Ctx.Input.RequestBody)
	if code > 0 {
		c.ServeFailJSONWithSGJErrorCode(code)
		return
	}

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	dataconfig.OrgId = adminUserInfo.CurrentOrgId
	dataconfig.CreateUserId = adminUserInfo.AdminUser.Id
	dataconfig.Status = 1
	dataconfig.CreatedTime = time.Now().Format("2006-01-02 15:04:05")
	dataconfig.UpdatedTime = time.Now().Format("2006-01-02 15:04:05")
	dataconfig.Remark = string(dataBody["remark"].(string))
	if dataBody["order"] != nil {
		dataconfig.Order = int64(dataBody["order"].(float64))
	} else {
		dataconfig.Order = 0
	}

	// 验证关键字段的值是否重复
	// thisConfig,_:=service.FindConfigByName(dataconfig.Module, dataconfig.Name,dataconfig.ParentId,dataconfig.OrgId)
	// if thisConfig.ID >0 {
	// 	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeFieldExist)
	// 	return
	// }

	fieldValue := service.GetChildValue(dataconfig.Module, dataconfig.ParentId, dataconfig.OrgId)
	dataconfig.Value = fieldValue + 1

	err = service.CreateConfig(&dataconfig)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateConfig)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"dataconfig": dataconfig,
		"msg":        "ok",
	})
	return
}

func configFormData(dataconfig *models.Dataconfig, data []byte) (code int) {
	configBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(data, &configBody)
	utils.InfoLog(string(data))
	if err != nil {
		utils.ErrorLog(err.Error())
		code = enums.ErrorCodeParamWrong
		return
	}
	if configBody["module"] == nil || reflect.TypeOf(configBody["module"]).String() != "string" {
		utils.ErrorLog("module")
		code = enums.ErrorCodeParamWrong
		return
	}
	module, _ := configBody["module"].(string)
	if len(module) == 0 {
		utils.ErrorLog("len(module) == 0")
		code = enums.ErrorCodeParamWrong
		return
	}
	dataconfig.Module = module

	if module == "education" || module == "summary" || module == "course_disease" || module == "rescue_record" {
		if configBody["title"] == nil || reflect.TypeOf(configBody["title"]).String() != "string" {
			utils.ErrorLog("title")
			code = enums.ErrorCodeParamWrong
			return
		}
		title, _ := configBody["title"].(string)
		if len(title) == 0 {
			utils.ErrorLog("len(title) == 0")
			code = enums.ErrorCodeParamWrong
			return
		}
		dataconfig.Title = title

		if configBody["content"] == nil || reflect.TypeOf(configBody["content"]).String() != "string" {
			utils.ErrorLog("content")
			code = enums.ErrorCodeParamWrong
			return
		}
		content, _ := configBody["content"].(string)
		if len(content) == 0 {
			utils.ErrorLog("len(content) == 0")
			code = enums.ErrorCodeParamWrong
			return
		}
		dataconfig.Content = content
	} else {
		if configBody["name"] == nil || reflect.TypeOf(configBody["name"]).String() != "string" {
			utils.ErrorLog("name")
			code = enums.ErrorCodeParamWrong
			return
		}
		name, _ := configBody["name"].(string)
		if len(name) == 0 {
			utils.ErrorLog("len(name) == 0")
			code = enums.ErrorCodeParamWrong
			return
		}
		dataconfig.Name = name

		if configBody["field_name"] == nil || reflect.TypeOf(configBody["field_name"]).String() != "string" {
			utils.ErrorLog("field_name")
			code = enums.ErrorCodeParamWrong
			return
		}
		field_name, _ := configBody["field_name"].(string)
		if len(field_name) == 0 {
			utils.ErrorLog("len(field_name) == 0")
			code = enums.ErrorCodeParamWrong
			return
		}
		dataconfig.FieldName = field_name
	}
	return
}

func configChildFormData(dataconfig *models.Dataconfig, data []byte) (code int) {
	configBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(data, &configBody)
	utils.InfoLog(string(data))
	if err != nil {
		utils.ErrorLog(err.Error())
		code = enums.ErrorCodeParamWrong
		return
	}

	if configBody["module"] == nil || reflect.TypeOf(configBody["module"]).String() != "string" {
		utils.ErrorLog("module")
		code = enums.ErrorCodeParamWrong
		return
	}
	module, _ := configBody["module"].(string)
	if len(module) == 0 {
		utils.ErrorLog("len(module) == 0")
		code = enums.ErrorCodeParamWrong
		return
	}
	dataconfig.Module = module

	if module == "education" || module == "summary" {
		if configBody["title"] == nil || reflect.TypeOf(configBody["title"]).String() != "string" {
			utils.ErrorLog("title")
			code = enums.ErrorCodeParamWrong
			return
		}
		title, _ := configBody["title"].(string)
		if len(title) == 0 {
			utils.ErrorLog("len(title) == 0")
			code = enums.ErrorCodeParamWrong
			return
		}
		dataconfig.Title = title

		if configBody["content"] == nil || reflect.TypeOf(configBody["content"]).String() != "string" {
			utils.ErrorLog("content")
			code = enums.ErrorCodeParamWrong
			return
		}
		content, _ := configBody["content"].(string)
		if len(content) == 0 {
			utils.ErrorLog("len(content) == 0")
			code = enums.ErrorCodeParamWrong
			return
		}
		dataconfig.Content = content
	} else {
		if configBody["parent_id"] == nil || reflect.TypeOf(configBody["parent_id"]).String() != "float64" {
			utils.ErrorLog("module")
			code = enums.ErrorCodeParamWrong
			return
		}
		parent_id := int64(configBody["parent_id"].(float64))
		if parent_id <= 0 {
			utils.ErrorLog("parent_id <= 0")
			code = enums.ErrorCodeParamWrong
			return
		}
		dataconfig.ParentId = parent_id

		if configBody["name"] == nil || reflect.TypeOf(configBody["name"]).String() != "string" {
			utils.ErrorLog("name")
			code = enums.ErrorCodeParamWrong
			return
		}
		name, _ := configBody["name"].(string)
		if len(name) == 0 {
			utils.ErrorLog("len(name) == 0")
			code = enums.ErrorCodeParamWrong
			return
		}
		dataconfig.Name = name
	}
	return
}

func (c *DataApiController) GetAdviceConfigs() {
	advice_type, _ := c.GetInt64("type", 0)

	adminUserInfo := c.GetAdminUserInfo()
	var drugs []models.DrugDic
	drugways, _, _ := service.GetDrugWayDics(adminUserInfo.CurrentOrgId)
	efs, _, _ := service.GetExecutionFrequencyDics(adminUserInfo.CurrentOrgId)
	adviceTemplates, _ := service.FindAllAdviceTemplate(adminUserInfo.CurrentOrgId, advice_type)
	c.ServeSuccessJSON(map[string]interface{}{
		"drugs":            drugs,
		"drugways":         drugways,
		"efs":              efs,
		"advice_templates": adviceTemplates,
	})
}

func (c *DataApiController) CreateDrugDic() {

	adminUserInfo := c.GetAdminUserInfo()

	var drugdic models.DrugDic
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &drugdic)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if drugdic.Name == "" {
		utils.ErrorLog("医嘱名称不能为空")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	timeNow := time.Now().Unix()
	drugdic.Code = ""
	drugdic.Status = 1
	drugdic.CreatedTime = timeNow
	drugdic.UpdatedTime = timeNow
	drugdic.OrgId = adminUserInfo.CurrentOrgId
	drugdic.Creator = adminUserInfo.AdminUser.Id

	err = service.CreateDrugDic(&drugdic)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"drugdic": drugdic,
	})
	return
}

func (c *DataApiController) UpdateDrugDic() {

	adminUserInfo := c.GetAdminUserInfo()
	id, _ := c.GetInt64("id", 0)
	if id <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	drugdic, _ := service.FindDrugDic(adminUserInfo.CurrentOrgId, id)
	if drugdic == nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBSelectNoResult)
		return
	}

	var drugdicdata models.DrugDic
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &drugdicdata)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if drugdicdata.Name == "" {
		utils.ErrorLog("医嘱名称不能为空")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	timeNow := time.Now().Unix()
	drugdic.UpdatedTime = timeNow
	drugdic.Name = drugdicdata.Name
	drugdic.Spec = drugdicdata.Spec
	drugdic.SpecUnit = drugdicdata.SpecUnit
	drugdic.Form = drugdicdata.Form
	drugdic.FormUnit = drugdicdata.FormUnit

	err = service.UpdateDrugDic(drugdic)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"drugdic": drugdic,
	})
	return
}

func (c *DataApiController) DeleteDrugDic() {
	adminUserInfo := c.GetAdminUserInfo()
	id, _ := c.GetInt64("id", 0)
	if id <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	drugdic, _ := service.FindDrugDic(adminUserInfo.CurrentOrgId, id)
	if drugdic == nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBSelectNoResult)
		return
	}
	timeNow := time.Now().Unix()
	drugdic.UpdatedTime = timeNow
	drugdic.Status = 2

	err := service.UpdateDrugDic(drugdic)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBDelete)
		return
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "ok",
	})
	return
}

func (c *DataApiController) CreateDrugWay() {

	adminUserInfo := c.GetAdminUserInfo()

	var drugway models.DrugwayDic
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &drugway)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if drugway.Name == "" {
		utils.ErrorLog("给药途径不能为空")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	timeNow := time.Now().Unix()
	drugway.Code = ""
	drugway.Status = 1
	drugway.CreatedTime = timeNow
	drugway.UpdatedTime = timeNow
	drugway.OrgId = adminUserInfo.CurrentOrgId
	drugway.Creator = adminUserInfo.AdminUser.Id

	err = service.CreateDrugWay(&drugway)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"drugway": drugway,
	})
	return
}

func (c *DataApiController) UpdateDrugWay() {

	adminUserInfo := c.GetAdminUserInfo()
	id, _ := c.GetInt64("id", 0)
	if id <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	drugway, _ := service.FindDrugWay(adminUserInfo.CurrentOrgId, id)
	if drugway == nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBSelectNoResult)
		return
	}

	var drugwaydata models.DrugwayDic
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &drugwaydata)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if drugwaydata.Name == "" {
		utils.ErrorLog("给药途径不能为空")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	timeNow := time.Now().Unix()
	drugway.UpdatedTime = timeNow
	drugway.Name = drugwaydata.Name

	err = service.UpdateDrugWay(drugway)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"drugway": drugway,
	})
	return
}

func (c *DataApiController) DeleteDrugWay() {
	adminUserInfo := c.GetAdminUserInfo()
	id, _ := c.GetInt64("id", 0)
	if id <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	drugway, _ := service.FindDrugWay(adminUserInfo.CurrentOrgId, id)
	if drugway == nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBSelectNoResult)
		return
	}

	timeNow := time.Now().Unix()
	drugway.UpdatedTime = timeNow
	drugway.Status = 2

	err := service.UpdateDrugWay(drugway)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBDelete)
		return
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "ok",
	})
	return
}

func (c *DataApiController) CreateExecutionFrequency() {

	adminUserInfo := c.GetAdminUserInfo()

	var ef models.ExecutionFrequencyDic
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &ef)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if ef.Name == "" {
		utils.ErrorLog("执行频率不能为空")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	timeNow := time.Now().Unix()
	ef.Code = ""
	ef.Status = 1
	ef.CreatedTime = timeNow
	ef.UpdatedTime = timeNow
	ef.OrgId = adminUserInfo.CurrentOrgId
	ef.Creator = adminUserInfo.AdminUser.Id

	err = service.CreateExecutionFrequency(&ef)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"ef": ef,
	})
	return
}

func (c *DataApiController) UpdateExecutionFrequency() {

	adminUserInfo := c.GetAdminUserInfo()
	id, _ := c.GetInt64("id", 0)
	if id <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	ef, _ := service.FindExecutionFrequency(adminUserInfo.CurrentOrgId, id)
	if ef == nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBSelectNoResult)
		return
	}

	var efdata models.ExecutionFrequencyDic
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &efdata)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if efdata.Name == "" {
		utils.ErrorLog("执行频率不能为空")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	timeNow := time.Now().Unix()
	ef.UpdatedTime = timeNow
	ef.Name = efdata.Name

	err = service.UpdateExecutionFrequency(ef)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"ef": ef,
	})
	return
}

func (c *DataApiController) DeleteExecutionFrequency() {
	adminUserInfo := c.GetAdminUserInfo()
	id, _ := c.GetInt64("id", 0)
	if id <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	ef, _ := service.FindExecutionFrequency(adminUserInfo.CurrentOrgId, id)
	if ef == nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBSelectNoResult)
		return
	}

	timeNow := time.Now().Unix()
	ef.UpdatedTime = timeNow
	ef.Status = 2

	err := service.UpdateExecutionFrequency(ef)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBDelete)
		return
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "ok",
	})
	return
}

func (c *DataApiController) CreateAdviceTemplate() {
	templateName := c.GetString("template_name")
	advice_type, _ := c.GetInt64("advice_type")

	fmt.Println(templateName)

	if templateName == "" {
		utils.ErrorLog("模版名称不能为空")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamEmptyWrong)
		return
	}

	if advice_type < 0 {
		utils.ErrorLog("医嘱模版类型不能为空")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAdviceTypeWrong)
		return
	}

	adminUserInfo := c.GetAdminUserInfo()

	appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.CurrentOrgId, adminUserInfo.AdminUser.Id, adminUserInfo.CurrentAppId)
	if appRole.UserType == 3 {
		headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
		if getPermissionErr != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		} else if headNursePermission == nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateAdvice)
			return
		}
	}

	//total := service.FindTemplateRecordByName(adminUserInfo.CurrentOrgId, templateName);
	//if total > 0 {
	//	utils.ErrorLog("模版名称已经存在")
	//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNameWrong)
	//	return
	//}

	template := &models.DoctorAdviceParentTemplate{
		Name:        templateName,
		OrgId:       adminUserInfo.CurrentOrgId,
		Status:      1,
		CreatedTime: time.Now().Unix(),
		UpdatedTime: time.Now().Unix(),
		AdviceType:  advice_type,
	}

	createErr := service.CreateTemplate(template)
	if createErr != nil {
		utils.ErrorLog("%v", createErr)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	var subTemplate []*models.DoctorAdviceTemplate
	if dataBody["data"] != nil && reflect.TypeOf(dataBody["data"]).String() == "[]interface {}" {
		subTemp, _ := dataBody["data"].([]interface{})
		if len(subTemp) > 0 {
			for _, item := range subTemp {
				items := item.(map[string]interface{})
				if items["advice_name"] == nil || reflect.TypeOf(items["advice_name"]).String() != "string" {
					utils.ErrorLog("advice_name")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				advice_name, _ := items["advice_name"].(string)
				advice_desc, _ := items["advice_desc"].(string)
				single_dose_unit, _ := items["single_dose_unit"].(string)
				prescribing_number_unit, _ := items["prescribing_number_unit"].(string)
				delivery_way, _ := items["delivery_way"].(string)
				execution_frequency, _ := items["execution_frequency"].(string)
				drug_spec, _ := items["drug_spec"].(string)
				drug_spec_unit, _ := items["drug_spec_unit"].(string)
				single_dose := items["single_dose"].(float64)
				prescribing_number := items["prescribing_number"].(float64)

				day_count, _ := strconv.ParseInt(items["day_count"].(string), 10, 64)
				weekdays := items["weekdays"].(string)
				frequency_type := int64(items["frequency_type"].(float64))

				subTemps := &models.DoctorAdviceTemplate{
					AdviceName:            advice_name,
					Status:                1,
					CreatedTime:           time.Now().Unix(),
					UpdatedTime:           time.Now().Unix(),
					OrgId:                 adminUserInfo.CurrentOrgId,
					AdviceDesc:            advice_desc,
					AdviceType:            advice_type,
					SingleDoseUnit:        single_dose_unit,
					PrescribingNumber:     prescribing_number,
					PrescribingNumberUnit: prescribing_number_unit,
					DeliveryWay:           delivery_way,
					ExecutionFrequency:    execution_frequency,
					TemplateId:            template.ID,
					DrugSpec:              drug_spec,
					DrugSpecUnit:          drug_spec_unit,
					SingleDose:            single_dose,
					AdviceDoctor:          adminUserInfo.AdminUser.Id,
					DayCount:              day_count,
					WeekDays:              weekdays,
					FrequencyType:         frequency_type,
				}
				subTemplate = append(subTemplate, subTemps)

			}
		}
	}
	//errs := service.CreateBatchRecord(subTemplate)
	errs := service.CreateSubTemplate(subTemplate)
	if errs != nil {
		utils.ErrorLog(errs.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
		return
	}
	templates, _ := service.FindDoctorAdviceTemplateById(template.ID, adminUserInfo.CurrentOrgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"template": templates,
	})
	return
}

func (c *DataApiController) UpdateAdviceTemplate() {

	adminUserInfo := c.GetAdminUserInfo()
	id, _ := c.GetInt64("id", 0)
	if id <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	template, _ := service.FindAdviceTemplate(adminUserInfo.CurrentOrgId, id)
	if template == nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBSelectNoResult)
		return
	}

	//TODO 根据路由来做权限
	//appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.CurrentOrgId, adminUserInfo.AdminUser.Id, adminUserInfo.CurrentAppId)
	//if appRole.UserType == 3 {
	//	headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
	//	if getPermissionErr != nil {
	//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
	//		return
	//	} else if headNursePermission == nil {
	//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
	//		return
	//	}
	//}

	var templatedata models.DoctorAdviceTemplate
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &templatedata)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if templatedata.AdviceName == "" {
		utils.ErrorLog("不能为空")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	timeNow := time.Now().Unix()
	template.UpdatedTime = timeNow
	template.AdviceName = templatedata.AdviceName
	template.AdviceDesc = templatedata.AdviceDesc
	template.SingleDose = templatedata.SingleDose
	template.SingleDoseUnit = templatedata.SingleDoseUnit
	template.PrescribingNumber = templatedata.PrescribingNumber
	template.PrescribingNumberUnit = templatedata.PrescribingNumberUnit
	template.DrugSpec = templatedata.DrugSpec
	template.DrugSpecUnit = templatedata.DrugSpecUnit
	template.DeliveryWay = templatedata.DeliveryWay
	template.ExecutionFrequency = templatedata.ExecutionFrequency

	template.FrequencyType = templatedata.FrequencyType
	template.DayCount = templatedata.DayCount
	template.WeekDays = templatedata.WeekDays

	err = service.UpdateAdviceTemplate(template)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"template": template,
	})
	return
}

func (c *DataApiController) DeleteAdviceTemplate() {
	adminUserInfo := c.GetAdminUserInfo()
	parent_id, _ := c.GetInt64("parent_id", 0)
	id, _ := c.GetInt64("id", 0)

	if id <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	template, _ := service.FindAdviceTemplate(adminUserInfo.CurrentOrgId, id)
	if template == nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBSelectNoResult)
		return
	}

	//appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.CurrentOrgId, adminUserInfo.AdminUser.Id, adminUserInfo.CurrentAppId)
	//if appRole.UserType == 3 {
	//	headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
	//	if getPermissionErr != nil {
	//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
	//		return
	//	} else if headNursePermission == nil {
	//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
	//		return
	//	}
	//}

	timeNow := time.Now().Unix()
	template.ID = id
	template.UpdatedTime = timeNow
	template.ParentId = parent_id
	template.Status = 2

	if parent_id > 0 { //删除子医嘱
		err := service.UpdateAdviceTemplate(template)
		if err != nil {
			utils.ErrorLog("%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBDelete)
			return
		}
	} else { //删除该医嘱下的所有子医嘱
		err := service.UpdateAdviceAndSubAdviceTemplate(template)
		if err != nil {
			utils.ErrorLog("%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBDelete)
			return
		}
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "ok",
	})
	return
}

func (c *DataApiController) CreateSingleAdviceTemplate() {
	drug_spec := c.GetString("drug_spec")
	drug_spec_unit := c.GetString("drug_spec_unit")
	advice_name := c.GetString("advice_name")
	advice_desc := c.GetString("advice_desc")
	single_dose, _ := c.GetFloat("single_dose", 0)
	single_dose_unit := c.GetString("single_dose_unit")
	prescribing_number, _ := c.GetFloat("prescribing_number", 0)
	prescribing_number_unit := c.GetString("prescribing_number_unit")
	delivery_way := c.GetString("delivery_way")
	execution_frequency := c.GetString("execution_frequency")
	template_id, _ := c.GetInt64("template_id", -1)

	advice_type, _ := c.GetInt64("advice_type", -1)
	frequency_type, _ := c.GetInt64("frequency_type", -1)
	week_days := c.GetString("week_days")
	day_count, _ := c.GetInt64("day_count", -1)

	adminUserInfo := c.GetAdminUserInfo()

	template := models.DoctorAdviceTemplate{
		OrgId:                 adminUserInfo.CurrentOrgId,
		AdviceDoctor:          adminUserInfo.AdminUser.Id,
		AdviceType:            advice_type,
		FrequencyType:         frequency_type,
		WeekDays:              week_days,
		DayCount:              day_count,
		Status:                1,
		CreatedTime:           time.Now().Unix(),
		UpdatedTime:           time.Now().Unix(),
		DrugSpec:              drug_spec,
		DrugSpecUnit:          drug_spec_unit,
		AdviceName:            advice_name,
		AdviceDesc:            advice_desc,
		SingleDose:            single_dose,
		SingleDoseUnit:        single_dose_unit,
		PrescribingNumber:     prescribing_number,
		PrescribingNumberUnit: prescribing_number_unit,
		DeliveryWay:           delivery_way,
		ExecutionFrequency:    execution_frequency,
		TemplateId:            template_id,
	}

	if template.AdviceName == "" {
		utils.ErrorLog("医嘱名字不能为空")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamAdviceEmptyWrong)
		return
	}

	appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.CurrentOrgId, adminUserInfo.AdminUser.Id, adminUserInfo.CurrentAppId)
	if appRole.UserType == 3 {
		headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
		if getPermissionErr != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		} else if headNursePermission == nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateAdvice)
			return
		}
	}

	err := service.CreateAdviceTemplate(&template)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"template": template,
	})
	return

}

func (c *DataApiController) DeleteParentAdviceTemplate() {
	template_id, _ := c.GetInt64("template_id", 0)
	adminUserInfo := c.GetAdminUserInfo()

	_, err := service.FindParentTemplateRecordById(adminUserInfo.CurrentOrgId, template_id)

	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	err1 := service.DeleteParentDoctorAdviceByTemplateId(template_id, adminUserInfo.CurrentOrgId)
	if err1 != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBDelete)
		return
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "删除成功",
	})

}

func (c *DataApiController) CreateSubAdviceTemplate() {
	drug_spec := c.GetString("drug_spec")
	drug_spec_unit := c.GetString("drug_spec_unit")
	advice_name := c.GetString("advice_name")
	advice_desc := c.GetString("advice_desc")
	single_dose, _ := c.GetFloat("single_dose", 0)
	single_dose_unit := c.GetString("single_dose_unit")
	prescribing_number, _ := c.GetFloat("prescribing_number", 0)
	prescribing_number_unit := c.GetString("prescribing_number_unit")
	delivery_way := c.GetString("delivery_way")
	execution_frequency := c.GetString("execution_frequency")
	template_id, _ := c.GetInt64("template_id", 0)
	parent_id, _ := c.GetInt64("parent_id", 0)

	adminUserInfo := c.GetAdminUserInfo()

	appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.CurrentOrgId, adminUserInfo.AdminUser.Id, adminUserInfo.CurrentAppId)
	if appRole.UserType == 3 {
		headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
		if getPermissionErr != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		} else if headNursePermission == nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateAdvice)
			return
		}
	}

	template := models.DoctorAdviceTemplate{
		OrgId:                 adminUserInfo.CurrentOrgId,
		AdviceDoctor:          adminUserInfo.AdminUser.Id,
		Status:                1,
		CreatedTime:           time.Now().Unix(),
		UpdatedTime:           time.Now().Unix(),
		DrugSpec:              drug_spec,
		DrugSpecUnit:          drug_spec_unit,
		AdviceName:            advice_name,
		AdviceDesc:            advice_desc,
		SingleDose:            single_dose,
		SingleDoseUnit:        single_dose_unit,
		PrescribingNumber:     prescribing_number,
		PrescribingNumberUnit: prescribing_number_unit,
		DeliveryWay:           delivery_way,
		ExecutionFrequency:    execution_frequency,
		TemplateId:            template_id,
		ParentId:              parent_id,
	}

	if template.AdviceName == "" {
		utils.ErrorLog("医嘱名字不能为空")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamAdviceEmptyWrong)
		return
	}
	err := service.CreateAdviceTemplate(&template)
	if err != nil {
		utils.ErrorLog("%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"template": template,
	})
	return

}

func (this *DataApiController) ModifyTemplateName() {
	template_name := this.GetString("template_name")
	template_id, _ := this.GetInt64("template_id", 0)

	if len(template_name) <= 0 {
		utils.ErrorLog("模版名字不能为空")
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamEmptyWrong)
		return
	}

	if template_id == 0 {
		utils.ErrorLog("模版不存在")
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamTemplateNOEXISTWrong)
		return
	}

	adminUserInfo := this.GetAdminUserInfo()

	template, _ := service.FindParentTemplateRecordById(adminUserInfo.CurrentOrgId, template_id)
	var err error
	if template.Name == template_name {
		err = service.ModifyTemplateName(template_id, template_name)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
			return
		}
	} else {
		//total := service.FindTemplateRecordByName(adminUserInfo.CurrentOrgId, template_name);
		//if total > 0 {
		//	utils.ErrorLog("模版名称已经存在")
		//	this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNameWrong)
		//	return
		//}
		err = service.ModifyTemplateName(template_id, template_name)

		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
			return
		}
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"template_name": template_name,
		"template_id":   template_id,
	})

}

func (this *DataApiController) ModifyFiledIsShow() {
	id, _ := this.GetInt64("id", 0)
	is_show, _ := this.GetInt("is_show", 0)
	adminUserInfo := this.GetAdminUserInfo()
	err := service.ShowFiledConfig(adminUserInfo.CurrentOrgId, is_show, id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
		return
	} else {

		this.ServeSuccessJSON(map[string]interface{}{
			"id":      id,
			"is_show": is_show,
		})
	}
}

func (c *DataApiController) GetAllAdviceConfigs() {

	adminUserInfo := c.GetAdminUserInfo()
	var drugs []models.DrugDic
	drugways, _, _ := service.GetDrugWayDics(adminUserInfo.CurrentOrgId)
	efs, _, _ := service.GetExecutionFrequencyDics(adminUserInfo.CurrentOrgId)
	adviceTemplates, _ := service.FindOtherAllAdviceTemplate(adminUserInfo.CurrentOrgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"drugs":            drugs,
		"drugways":         drugways,
		"efs":              efs,
		"advice_templates": adviceTemplates,
	})
}

func (c *DataApiController) GetHandleData() {
	id, _ := c.GetInt64("id")
	config, err := service.GetHandleData(id)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
		return
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"config": config,
	})
}

func (c *DataApiController) UpdateDataTwo() {
	id, _ := c.GetInt64("id")
	//fmt.Print("id",id)
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	//fmt.Print("err",err)
	//fmt.Print("id",id)
	name := dataBody["name"].(string)
	// fmt.Print("name",name)
	order := int64(dataBody["order"].(float64))
	// fmt.Print("order",order)
	remake := dataBody["remark"].(string)
	// fmt.Print("remake",remake)
	configModel := models.ConfigViewModel{
		Name:   name,
		Order:  order,
		Remark: remake,
	}
	err = service.UpdateDataTwo(id, configModel)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
		return
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"configModel": configModel,
	})
}
