package controllers

import (
	"Xcx_New/enums"
	"Xcx_New/models"
	"Xcx_New/service"
	"Xcx_New/utils"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/jinzhu/gorm"
	"reflect"
	"strconv"
	"time"
)

type ManagerCenterApiController struct {
	BaseAuthAPIController
}

func ManagerCenterRegistRouters() {
	//药品基础库
	beego.Router("/api/basedruglib/create", &ManagerCenterApiController{}, "post:CreateBaseDrugLib")
	beego.Router("/api/basedruglib/edit", &ManagerCenterApiController{}, "post:EditBaseDrugLib")
	beego.Router("/api/basedruglib/get", &ManagerCenterApiController{}, "get:GetBaseDrugLib")
	beego.Router("/api/basedruglib/list", &ManagerCenterApiController{}, "get:GetBaseDrugLibList")
	beego.Router("/api/medicineinsurancepercent/create", &ManagerCenterApiController{}, "post:CreateMedicineInsurancePercent")
	beego.Router("/api/drugunitsafeguard/create", &ManagerCenterApiController{}, "post:CreateDrugUnitSafeguard")

	beego.Router("/api/medicineinsurancepercent/get", &ManagerCenterApiController{}, "get:GetMedicineInsurancePercent")
	//beego.Router("/api/drugunitsafeguard/get", &ManagerCenterApiController{}, "get:GetDrugUnitSafeguard")
	beego.Router("/api/drug/basedruglib", &ManagerCenterApiController{}, "get:DeleteBaseDrugById")
	//专项字典
	beego.Router("/api/dictionary/getconfiglist", &ManagerCenterApiController{}, "get,post:GetConfigList")
	beego.Router("/api/dictionary/createconfig", &ManagerCenterApiController{}, "Post:CreateConfig")
	beego.Router("/api/dictionary/createchildconfig", &ManagerCenterApiController{}, "Post:CreateChildConfig")
	beego.Router("/api/dictionary/updatechildconfig", &ManagerCenterApiController{}, "Post:UpdateChildConfig")
	beego.Router("/api/dictionary/deletechildconfig", &ManagerCenterApiController{}, "Post:DeleteChildConfig")
	beego.Router("/api/dictionary/updatetemplate", &ManagerCenterApiController{}, "Post:UpdateTemplate")

	//经销商
	beego.Router("/api/stock/dealer/create", &ManagerCenterApiController{}, "post:CreateDealer")
	beego.Router("/api/stock/dealer/modify", &ManagerCenterApiController{}, "post:ModifyDealer")
	beego.Router("/api/stock/dealer/list", &ManagerCenterApiController{}, "get:GetDealersList")
	beego.Router("/api/stock/dealer/delete", &ManagerCenterApiController{}, "post:DeleteDealer")
	beego.Router("/api/stock/dealer/get", &ManagerCenterApiController{}, "get:GetDealer")

	//厂商
	beego.Router("/api/stock/manufacturer/create", &ManagerCenterApiController{}, "post:CreateManufacturer")
	beego.Router("/api/stock/manufacturer/modify", &ManagerCenterApiController{}, "post:ModifyManufacturer")
	beego.Router("/api/stock/manufacturer/list", &ManagerCenterApiController{}, "get:GetManufacturerList")
	beego.Router("/api/stock/manufacturer/delete", &ManagerCenterApiController{}, "post:DeleteManufacturer")
	beego.Router("/api/stock/manufacturer/get", &ManagerCenterApiController{}, "get:GetManufacturer")

	beego.Router("/api/stock/good/info/create", &ManagerCenterApiController{}, "post:CreateGoodInfo")
	beego.Router("/api/stock/good/info/modify", &ManagerCenterApiController{}, "post:ModifyGoodInfo")
	beego.Router("/api/stock/good/info/list", &ManagerCenterApiController{}, "get:GetGoodInfoList")
	beego.Router("/api/info/delete", &ManagerCenterApiController{}, "post:DeleteGoodInfo")
	beego.Router("/api/stock/good/info/get", &ManagerCenterApiController{}, "get:GetGoodInfoByGoodId")
	beego.Router("/api/stock/good/info", &ManagerCenterApiController{}, "get:GetGoodInfoById")

	//门诊大病
	beego.Router("/api/mz/sick/create", &ManagerCenterApiController{}, "post:CreateMZSick")
	beego.Router("/api/mz/sick/modify", &ManagerCenterApiController{}, "post:ModifyMZSick")
	beego.Router("/api/mz/sick/list", &ManagerCenterApiController{}, "get:GetMZSickList")
	beego.Router("/api/mz/sick/delete", &ManagerCenterApiController{}, "post:DeleteMZSick")
	beego.Router("/api/mz/sick/get", &ManagerCenterApiController{}, "get:GetMZSick")

	beego.Router("/api/addition/create", &ManagerCenterApiController{}, "post:CreateAddition")
	beego.Router("/api/addition/modify", &ManagerCenterApiController{}, "post:ModifyAddition")
	beego.Router("/api/addition/list", &ManagerCenterApiController{}, "get:GetAdditionList")
	beego.Router("/api/addition/delete", &ManagerCenterApiController{}, "post:DeleteAddition")
	beego.Router("/api/addition/get", &ManagerCenterApiController{}, "get:GetAddition")

	//门诊诊断
	beego.Router("/api/diagnose/create", &ManagerCenterApiController{}, "post:CreateDiagnose")
	beego.Router("/api/diagnose/modify", &ManagerCenterApiController{}, "post:ModifyDiagnose")
	beego.Router("/api/diagnose/list", &ManagerCenterApiController{}, "get:GetDiagnoseList")
	beego.Router("/api/diagnose/delete", &ManagerCenterApiController{}, "post:DeleteDiagnose")
	beego.Router("/api/diagnose/get", &ManagerCenterApiController{}, "get:GetDiagnose")
	beego.Router("/api/drug/getalldruglist", &ManagerCenterApiController{}, "get:GetAllDrugList")
	beego.Router("/api/drug/postsearchdruglist", &ManagerCenterApiController{}, "get:GetSearchDrugList")

}

func (c *ManagerCenterApiController) CreateBaseDrugLib() {
	drug_name := c.GetString("drug_name")
	pinyin := c.GetString("pinyin")
	wubi := c.GetString("wubi")
	drug_alias := c.GetString("drug_alias")
	drug_alias_pinyin := c.GetString("drug_alias_pinyin")
	drug_alias_wubi := c.GetString("drug_alias_wubi")
	drug_category, _ := c.GetInt64("drug_category")
	drug_spec := c.GetString("drug_spec")
	drug_type, _ := c.GetInt64("drug_type")
	drug_stock_limit := c.GetString("drug_stock_limit")
	drug_origin_place := c.GetString("drug_origin_place")
	drug_dosage_form, _ := c.GetInt64("drug_dosage_form")
	medical_insurance_level, _ := c.GetInt64("medical_insurance_level")
	max_unit := c.GetString("max_unit")
	min_unit := c.GetString("min_unit")
	unit_matrixing := c.GetString("unit_matrixing")
	retail_price, _ := c.GetFloat("retail_price")
	last_price, _ := c.GetFloat("last_price")
	drug_control, _ := c.GetInt64("drug_control")
	number := c.GetString("number")
	drug_classify := c.GetString("drug_classify")
	drug_dose, _ := c.GetFloat("drug_dose")
	drug_dose_unit, _ := c.GetInt64("drug_dose_unit")
	medical_insurance_number := c.GetString("medical_insurance_number")
	manufacturer, _ := c.GetInt64("manufacturer")
	pharmacology_category, _ := c.GetInt64("pharmacology_category")
	statistics_category, _ := c.GetInt64("statistics_category")
	code := c.GetString("code")
	is_special_diseases, _ := c.GetInt64("is_special_diseases")
	is_record, _ := c.GetInt64("is_record")
	agent := c.GetString("agent")
	drug_status := c.GetString("drug_status")
	limit_remark := c.GetString("limit_remark")
	delivery_way := c.GetString("delivery_way")
	execution_frequency := c.GetString("execution_frequency")
	single_dose, _ := c.GetFloat("single_dose")
	fmt.Println(single_dose)
	prescribing_number, _ := c.GetFloat("prescribing_number")
	label, _ := c.GetInt64("label")
	sort, _ := c.GetInt64("sort")
	is_use_doctor_advice, _ := c.GetInt64("is_use_doctor_advice")
	is_default, _ := c.GetInt64("is_default")
	is_charge_predict, _ := c.GetInt64("is_charge_predict")
	is_statistics_work, _ := c.GetInt64("is_statistics_work")
	is_charge_use, _ := c.GetInt64("is_charge_use")
	dealer, _ := c.GetInt64("dealer")
	prescription_mark, _ := c.GetInt64("prescription_mark")
	social_security_directory_code := c.GetString("social_security_directory_code")
	record_date := c.GetString("record_date")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", record_date+" 00:00:00", loc)
	drug_remark := c.GetString("drug_remark")
	dose, _ := c.GetFloat("dose")
	dose_unit := c.GetString("dose_unit")
	min_price, _ := c.GetFloat("min_price")
	min_number, _ := c.GetInt64("min_number")
	drug_day := c.GetString("drug_day")
	hosp_appr_flag, _ := c.GetInt64("hosp_appr_flag")
	lmt_used_flag, _ := c.GetInt64("lmt_used_flag")
	prescribing_number_unit := c.GetString("prescribing_number_unit")
	adminInfo := c.GetAdminUserInfo()
	drugLib := &models.BaseDrugLib{
		DrugName:                    drug_name,
		Pinyin:                      pinyin,
		Wubi:                        wubi,
		DrugAlias:                   drug_alias,
		DrugAliasPinyin:             drug_alias_pinyin,
		DrugAliasWubi:               drug_alias_wubi,
		DrugCategory:                drug_category,
		DrugSpec:                    drug_spec,
		DrugType:                    drug_type,
		DrugStockLimit:              drug_stock_limit,
		DrugOriginPlace:             drug_origin_place,
		MedicalInsuranceLevel:       medical_insurance_level,
		DrugDosageForm:              drug_dosage_form,
		MaxUnit:                     max_unit,
		MinUnit:                     min_unit,
		UnitMatrixing:               unit_matrixing,
		RetailPrice:                 retail_price,
		LastPrice:                   last_price,
		DrugControl:                 drug_control,
		Number:                      number,
		DrugClassify:                drug_classify,
		DrugDose:                    drug_dose,
		DrugDoseUnit:                drug_dose_unit,
		MedicalInsuranceNumber:      medical_insurance_number,
		Manufacturer:                manufacturer,
		PharmacologyCategory:        pharmacology_category,
		StatisticsCategory:          statistics_category,
		Code:                        code,
		IsSpecialDiseases:           is_special_diseases,
		IsRecord:                    is_record,
		Agent:                       agent,
		DrugStatus:                  drug_status,
		LimitRemark:                 limit_remark,
		DeliveryWay:                 delivery_way,
		ExecutionFrequency:          execution_frequency,
		SingleDose:                  drug_dose,
		PrescribingNumber:           prescribing_number,
		Label:                       label,
		Sort:                        sort,
		IsUseDoctorAdvice:           is_use_doctor_advice,
		IsDefault:                   is_default,
		IsChargePredict:             is_charge_predict,
		IsStatisticsWork:            is_statistics_work,
		IsChargeUse:                 is_charge_use,
		OrgId:                       adminInfo.CurrentOrgId,
		Status:                      1,
		Ctime:                       time.Now().Unix(),
		Mtime:                       time.Now().Unix(),
		Dealer:                      dealer,
		PrescriptionMark:            prescription_mark,
		SocialSecurityDirectoryCode: social_security_directory_code,
		RecordDate:                  theTime.Unix(),
		DrugRemark:                  drug_remark,
		DrugDay:                     drug_day,
		MinNumber:                   min_number,
		Dose:                        dose,
		MinPrice:                    min_price,
		DoseUnit:                    dose_unit,
		HospApprFlag:                hosp_appr_flag,
		LmtUsedFlag:                 lmt_used_flag,
		PrescribingNumberUnit:       prescribing_number_unit,
	}

	total := service.FindAllDrugLibRecordTotal(adminInfo.CurrentOrgId)
	drug_code := strconv.FormatInt(total+1, 10)
	drug_code = "54000000" + drug_code
	drugLib.DrugCode = drug_code

	count := service.FindBaseDrugLibRecordCountOne(drugLib)

	if count == 0 {
		err := service.CreateBaseDrugLib(drugLib)
		if err == nil {
			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "创建成功",
			})
		} else {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
			return
		}
		return

	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDrugRepeatDataException)
		return
	}

}

func (c *ManagerCenterApiController) EditBaseDrugLib() {
	id, _ := c.GetInt64("id")
	drug_name := c.GetString("drug_name")
	pinyin := c.GetString("pinyin")
	wubi := c.GetString("wubi")
	drug_alias := c.GetString("drug_alias")
	drug_alias_pinyin := c.GetString("drug_alias_pinyin")
	drug_alias_wubi := c.GetString("drug_alias_wubi")
	drug_category, _ := c.GetInt64("drug_category")
	drug_spec := c.GetString("drug_spec")
	drug_type, _ := c.GetInt64("drug_type")
	drug_stock_limit := c.GetString("drug_stock_limit")
	drug_origin_place := c.GetString("drug_origin_place")
	drug_dosage_form, _ := c.GetInt64("drug_dosage_form")
	medical_insurance_level, _ := c.GetInt64("medical_insurance_level")
	max_unit := c.GetString("max_unit")
	min_unit := c.GetString("min_unit")
	unit_matrixing := c.GetString("unit_matrixing")
	retail_price, _ := c.GetFloat("retail_price")
	last_price, _ := c.GetFloat("last_price")
	drug_control, _ := c.GetInt64("drug_control")
	number := c.GetString("number")
	drug_classify := c.GetString("drug_classify")
	drug_dose, _ := c.GetFloat("drug_dose")
	drug_dose_unit, _ := c.GetInt64("drug_dose_unit")
	medical_insurance_number := c.GetString("medical_insurance_number")
	manufacturer, _ := c.GetInt64("manufacturer")
	pharmacology_category, _ := c.GetInt64("pharmacology_category")
	statistics_category, _ := c.GetInt64("statistics_category")
	code := c.GetString("code")
	is_special_diseases, _ := c.GetInt64("is_special_diseases")
	is_record, _ := c.GetInt64("is_record")
	agent := c.GetString("agent")
	drug_status := c.GetString("drug_status")
	limit_remark := c.GetString("limit_remark")
	delivery_way := c.GetString("delivery_way")
	execution_frequency := c.GetString("execution_frequency")
	single_dose, _ := c.GetFloat("single_dose")
	fmt.Println("sigle_dose", single_dose)
	prescribing_number, _ := c.GetFloat("prescribing_number")
	label, _ := c.GetInt64("label")
	sort, _ := c.GetInt64("sort")
	is_use_doctor_advice, _ := c.GetInt64("is_use_doctor_advice")
	is_default, _ := c.GetInt64("is_default")
	is_charge_predict, _ := c.GetInt64("is_charge_predict")
	is_statistics_work, _ := c.GetInt64("is_statistics_work")
	is_charge_use, _ := c.GetInt64("is_charge_use")
	drug_code := c.GetString("drug_code")
	//unit := c.GetString("unit")
	dealer, _ := c.GetInt64("dealer")
	prescription_mark, _ := c.GetInt64("prescription_mark")
	social_security_directory_code := c.GetString("social_security_directory_code")
	record_date := c.GetString("record_date")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", record_date+" 00:00:00", loc)
	drug_remark := c.GetString("drug_remark")
	min_number, _ := c.GetInt64("min_number")
	drug_day := c.GetString("drug_day")
	dose, _ := c.GetFloat("dose")
	dose_unit := c.GetString("dose_unit")
	total, _ := c.GetFloat("total")

	min_price, _ := c.GetFloat("min_price")
	hosp_appr_flag, _ := c.GetInt64("hosp_appr_flag")
	lmt_used_flag, _ := c.GetInt64("lmt_used_flag")
	prescribing_number_unit := c.GetString("prescribing_number_unit")

	adminInfo := c.GetAdminUserInfo()
	drug, _ := service.FindBaseDrugLibRecord(adminInfo.CurrentOrgId, id)
	drugLib := &models.BaseDrugLib{
		ID:                          id,
		DrugName:                    drug_name,
		Pinyin:                      pinyin,
		Wubi:                        wubi,
		DrugAlias:                   drug_alias,
		DrugAliasPinyin:             drug_alias_pinyin,
		DrugAliasWubi:               drug_alias_wubi,
		DrugCategory:                drug_category,
		DrugSpec:                    drug_spec,
		DrugType:                    drug_type,
		DrugStockLimit:              drug_stock_limit,
		DrugOriginPlace:             drug_origin_place,
		MedicalInsuranceLevel:       medical_insurance_level,
		DrugDosageForm:              drug_dosage_form,
		MaxUnit:                     max_unit,
		MinUnit:                     min_unit,
		UnitMatrixing:               unit_matrixing,
		RetailPrice:                 retail_price,
		LastPrice:                   last_price,
		DrugControl:                 drug_control,
		Number:                      number,
		DrugClassify:                drug_classify,
		DrugDose:                    drug_dose,
		DrugDoseUnit:                drug_dose_unit,
		MedicalInsuranceNumber:      medical_insurance_number,
		Manufacturer:                manufacturer,
		PharmacologyCategory:        pharmacology_category,
		StatisticsCategory:          statistics_category,
		Code:                        code,
		IsSpecialDiseases:           is_special_diseases,
		IsRecord:                    is_record,
		Agent:                       agent,
		DrugStatus:                  drug_status,
		LimitRemark:                 limit_remark,
		DeliveryWay:                 delivery_way,
		ExecutionFrequency:          execution_frequency,
		PrescribingNumber:           prescribing_number,
		Label:                       label,
		Sort:                        sort,
		IsUseDoctorAdvice:           is_use_doctor_advice,
		IsDefault:                   is_default,
		IsChargePredict:             is_charge_predict,
		IsStatisticsWork:            is_statistics_work,
		IsChargeUse:                 is_charge_use,
		OrgId:                       adminInfo.CurrentOrgId,
		Status:                      1,
		Ctime:                       drug.Ctime,
		Mtime:                       time.Now().Unix(),
		DrugCode:                    drug_code,
		Dealer:                      dealer,
		PrescriptionMark:            prescription_mark,
		SocialSecurityDirectoryCode: social_security_directory_code,
		RecordDate:                  theTime.Unix(),
		DrugRemark:                  drug_remark,
		DrugDay:                     drug_day,
		HospApprFlag:                hosp_appr_flag,
		LmtUsedFlag:                 lmt_used_flag,
		MinNumber:                   min_number,
		Dose:                        dose,
		MinPrice:                    min_price,
		DoseUnit:                    dose_unit,
		PrescribingNumberUnit:       prescribing_number_unit,
		Total:                       total,
		SingleDose:                  drug_dose,
	}

	err := service.UpdateBaseDrugLib(drugLib)

	//查询是否存在
	_, errOne := service.GetDrugNameIsExist(id, adminInfo.CurrentOrgId)
	if errOne == gorm.ErrRecordNotFound {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "修改成功",
		})
		return
	} else if errOne == nil {
		//修改xt_drug_name 表
		drugName := models.XtDrugName{
			DrugName: drug_name,
		}
		service.UpdatedDrugName(id, adminInfo.CurrentOrgId, &drugName)
	}

	//查询是否存在
	_, errTwo := service.GetStandNameIsExist(id, adminInfo.CurrentOrgId)
	if errTwo == gorm.ErrRecordNotFound {

		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "修改成功",
		})
		return
	} else if errTwo == nil {
		//修改规格xt_stand_name表
		standName := models.XtStandName{
			DrugName:       drug_name,
			DrugSpec:       drug_spec,
			DrugStockLimit: drug_stock_limit,
			MinUnit:        min_unit,
		}

		service.UpdateStandName(id, adminInfo.CurrentOrgId, &standName)
	}

	_, errThree := service.GetSelfMedicalIsExist(id, adminInfo.CurrentOrgId)

	if errThree == gorm.ErrRecordNotFound {

		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "修改成功",
		})
		return
	} else if errThree == nil {
		//修改药品表
		medical := models.XtSelfMedical{
			DrugName:           drug_name,
			DrugSpec:           drug_spec,
			ExecutionFrequency: execution_frequency,
			PrescribingNumber:  prescribing_number,
			DeliveryWay:        delivery_way,
			SingleDose:         single_dose,
			MinUnit:            min_unit,
		}

		service.UpdateSelfMedical(id, adminInfo.CurrentOrgId, &medical)
	}

	_, errFour := service.GetSelfStosckIsExist(id, adminInfo.CurrentOrgId)
	if errFour == gorm.ErrRecordNotFound {

		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "修改成功",
		})
		return
	} else if errFour == nil {
		stock := models.XtSelfStock{
			DrugSpec: drug_spec,
			DrugName: drug_name,
			MinUnit:  min_unit,
		}
		service.UpdatedSelfStock(&stock, id, adminInfo.CurrentOrgId)
	}

	_, errFive := service.GetOutSelfOutStockIsExist(id, adminInfo.CurrentOrgId)
	if errFive == gorm.ErrRecordNotFound {

		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "修改成功",
		})
		return
	} else if errFive == nil {
		outStock := models.XtSelfOutStock{
			DrugName: drug_name,
			DrugSpec: drug_spec,
		}
		//修改出库表
		service.UpdatedOutSelfStock(&outStock, id, adminInfo.CurrentOrgId)
	}

	_, errSix := service.GetDoctorAdviceIsExist(id, adminInfo.CurrentOrgId)
	if errSix == gorm.ErrRecordNotFound {
		fmt.Println("进来了吗5")
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "修改成功",
		})
		return
	} else if errSix == nil {
		//查询未执行的医嘱
		advice := models.DoctorAdvice{
			AdviceName:         drug_name,
			AdviceDesc:         drug_spec,
			DeliveryWay:        delivery_way,
			ExecutionFrequency: execution_frequency,
			SingleDose:         single_dose,
			SingleDoseUnit:     min_unit,
		}

		service.UpdateNoExcuteDoctorAdvice(id, adminInfo.CurrentOrgId, &advice)
	}

	_, errSeven := service.GetDoctorAdviceTemplateIsExist(id, adminInfo.CurrentOrgId)

	if errSeven == gorm.ErrRecordNotFound {
		fmt.Println("进来了吗6")
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "修改成功",
		})
		return
	} else if errSeven == nil {
		//修改医嘱模板
		template := models.DoctorAdviceTemplate{
			AdviceName:         drug_name,
			AdviceDesc:         drug_spec,
			DeliveryWay:        delivery_way,
			ExecutionFrequency: execution_frequency,
			SingleDose:         single_dose,
			SingleDoseUnit:     min_unit,
		}
		service.UpdatedDoctorAdviceTemplate(id, adminInfo.CurrentOrgId, &template)

	}

	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "修改成功",
		})
		return
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}

func (c *ManagerCenterApiController) GetBaseDrugLib() {
	id, _ := c.GetInt64("id")
	adminInfo := c.GetAdminUserInfo()
	drug, err := service.FindBaseDrugLibRecord(adminInfo.CurrentOrgId, id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"drug": drug,
		})
		return

	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}

}

func (c *ManagerCenterApiController) GetBaseDrugLibList() {
	page, _ := c.GetInt64("page", 1)
	limit, _ := c.GetInt64("limit", 10)
	is_use, _ := c.GetInt64("is_use", 0)
	is_charge, _ := c.GetInt64("is_charge", 0)
	is_inject, _ := c.GetInt64("is_inject", 0)
	manufacturer, _ := c.GetInt64("manufacturer")
	is_record, _ := c.GetInt64("is_record")

	keyword := c.GetString("keyword")
	adminInfo := c.GetAdminUserInfo()

	if page <= 0 {
		page = 1
	}
	if limit <= 0 {
		limit = 10
	}
	list, total, _ := service.GetBaseDrugLibList(adminInfo.CurrentOrgId, keyword, page, limit, is_use, is_charge, is_inject, manufacturer, is_record)

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

func (c *ManagerCenterApiController) CreateMedicineInsurancePercent() {
	module, _ := c.GetInt64("module", 0)
	adminInfo := c.GetAdminUserInfo()
	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 mips []*models.MedicineInsurancePercentage
	var errs error
	record_time := time.Now().Unix()

	if dataBody["mip"] != nil && reflect.TypeOf(dataBody["mip"]).String() == "[]interface {}" {
		mip_map, _ := dataBody["mip"].([]interface{})
		if len(mip_map) > 0 {
			for _, item := range mip_map {
				items := item.(map[string]interface{})

				if items["type_id"] == nil || reflect.TypeOf(items["type_id"]).String() != "float64" {
					utils.ErrorLog("type_id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				type_id := int64(items["type_id"].(float64))

				if items["medicine_insurance_type"] == nil || reflect.TypeOf(items["medicine_insurance_type"]).String() != "float64" {
					utils.ErrorLog("medicine_insurance_type")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				types := int64(items["medicine_insurance_type"].(float64))

				if items["percent"] == nil || reflect.TypeOf(items["percent"]).String() != "string" {
					utils.ErrorLog("percent")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				percent, _ := strconv.ParseFloat(items["percent"].(string), 64)
				//percent := items["percent"].(float64)
				mip_temp := &models.MedicineInsurancePercentage{
					TypeId:                type_id,
					Status:                1,
					Ctime:                 time.Now().Unix(),
					Mtime:                 time.Now().Unix(),
					RecordTime:            record_time,
					MedicineInsuranceType: types,
					UserOrgId:             adminInfo.CurrentOrgId,
					Percent:               percent,
					Module:                module,
					GoodId:                0,
				}
				mips = append(mips, mip_temp)

			}
		}

		for _, item := range mips {
			errs = service.CreateMedicineInsurancePercentage(item)
		}
	}

	if errs == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "添加成功",
		})
		return

	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}

}

func (c *ManagerCenterApiController) CreateDrugUnitSafeguard() {

}

//GetPatientsList 取配置信息列表
func (c *ManagerCenterApiController) GetConfigList() {
	adminUserInfo := c.GetAdminUserInfo()
	configList, _ := service.GetDictionaryConfigList(adminUserInfo.CurrentOrgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"configlist": configList,
	})
	return

}

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

	var dataconfig models.DictionaryDataconfig
	var resultConfig models.DictionaryConfigViewModel
	code := dictionaryConfigFormData(&dataconfig, c.Ctx.Input.RequestBody)
	if code > 0 {
		c.ServeFailJSONWithSGJErrorCode(code)
		return
	}
	// 验证关键字段的值是否重复

	thisConfig, _ := service.FindDictionaryConfigByTitle(dataconfig.Module, dataconfig.FieldName, adminUserInfo.CurrentOrgId)
	if thisConfig.ID > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeFieldExist)
		return
	}

	fieldValue := service.GetDictionaryChildValue(dataconfig.Module, dataconfig.ParentId, adminUserInfo.CurrentOrgId)
	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.CreateDictionaryConfig(&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 *ManagerCenterApiController) UpdateTemplate() {
	adminUserInfo := c.GetAdminUserInfo()
	var dataconfig models.DictionaryDataconfig
	code := dictionaryConfigFormData(&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.CreateDictionaryConfig(&dataconfig)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateConfig)
			return
		}
	} else {
		dataconfig.ID = int64(dataBody["id"].(float64))
		err = service.UpdateDictionaryTemplate(&dataconfig)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeUpdateConfig)
			return
		}
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"dataconfig": dataconfig,
		"msg":        "ok",
	})
	return
}
func (c *ManagerCenterApiController) UpdateChildConfig() {
	adminUserInfo := c.GetAdminUserInfo()
	var dataconfig models.DictionaryDataconfig
	code := dictionaryConfigChildFormData(&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))
	dataconfig.Order = int64(dataBody["orders"].(float64))
	dataconfig.Code = string(dataBody["code"].(string))
	fmt.Println("dataconfitg------", dataconfig.Order)
	//if dataBody["orders"] != nil {
	//	dataconfig.Order = int64(dataBody["orders"].(float64))
	//	fmt.Println("dataconfig",dataconfig.Order)
	//} 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.CreateDictionaryConfig(&dataconfig)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateConfig)
			return
		}
	} else {
		dataconfig.ID = int64(dataBody["id"].(float64))
		err = service.UpdateDictionaryChildConfig(&dataconfig)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeUpdateConfig)
			return
		}
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"dataconfig": dataconfig,
		"msg":        "ok",
	})
	return
}
func (c *ManagerCenterApiController) DeleteChildConfig() {
	adminUserInfo := c.GetAdminUserInfo()
	var dataconfig models.DictionaryDataconfig
	code := dictionaryConfigChildFormData(&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.CreateDictionaryConfig(&dataconfig)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateConfig)
			return
		}
	} else {
		dataconfig.ID = int64(dataBody["id"].(float64))
		err := service.DeleteDictionaryChildConfig(&dataconfig)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeUpdateConfig)
			return
		}
	}

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

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

	var dataconfig models.DictionaryDataconfig
	code := dictionaryConfigChildFormData(&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))
	dataconfig.Code = string(dataBody["code"].(string))
	fmt.Println("3444444444", dataconfig.Code)
	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.GetDictionaryChildValue(dataconfig.Module, dataconfig.ParentId, dataconfig.OrgId)
	dataconfig.Value = fieldValue + 1

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

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

func dictionaryConfigFormData(dataconfig *models.DictionaryDataconfig, 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" || module == "nursing_record" || module == "special_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 dictionaryConfigChildFormData(dataconfig *models.DictionaryDataconfig, 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 *ManagerCenterApiController) CreateDealer() {
	dealer_name := c.GetString("dealer_name")
	contact := c.GetString("contact")
	contact_phone := c.GetString("contact_phone")
	platform_number := c.GetString("platform_number")
	email := c.GetString("email")
	contact_address := c.GetString("contact_address")
	remark := c.GetString("remark")
	pinyin := c.GetString("pinyin")
	wubi := c.GetString("wubi")

	if len(dealer_name) <= 0 {
		utils.ErrorLog("len(dealer_name) == 0")

		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := c.GetAdminUserInfo()

	total := service.FindAllDealerTotal(adminUserInfo.CurrentOrgId)
	totalStr := strconv.FormatInt(total+1, 10)
	code := "1000" + totalStr
	dealer := models.Dealer{
		DealerName:     dealer_name,
		Contact:        contact,
		ContactPhone:   contact_phone,
		ContactAddress: contact_address,
		DealerCode:     code,
		Ctime:          time.Now().Unix(),
		Mtime:          time.Now().Unix(),
		Remark:         remark,
		Creater:        adminUserInfo.AdminUser.Id,
		Email:          email,
		PlatformNumber: platform_number,
		OrgId:          adminUserInfo.CurrentOrgId,
		Status:         1,
		PinYin:         pinyin,
		WuBi:           wubi,
	}

	err, dealers := service.AddSigleDealer(&dealer)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"dealer": dealers,
		})

	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)

	}

}
func (c *ManagerCenterApiController) ModifyDealer() {
	id, _ := c.GetInt64("id", 0)
	dealer_name := c.GetString("dealer_name")
	contact := c.GetString("contact")
	contact_phone := c.GetString("contact_phone")
	platform_number := c.GetString("platform_number")
	dealer_code := c.GetString("dealer_code")
	email := c.GetString("email")
	contact_address := c.GetString("contact_address")
	remark := c.GetString("remark")
	pinyin := c.GetString("pinyin")
	wubi := c.GetString("wubi")

	if id <= 0 {
		utils.ErrorLog("id == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if len(dealer_name) <= 0 {
		utils.ErrorLog("len(dealer_name) == 0")

		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := c.GetAdminUserInfo()
	dealer := models.Dealer{
		ID:             id,
		DealerName:     dealer_name,
		Contact:        contact,
		ContactPhone:   contact_phone,
		ContactAddress: contact_address,
		Mtime:          time.Now().Unix(),
		DealerCode:     dealer_code,
		Remark:         remark,
		Creater:        adminUserInfo.AdminUser.Id,
		Email:          email,
		PlatformNumber: platform_number,
		Modifier:       adminUserInfo.AdminUser.Id,
		OrgId:          adminUserInfo.CurrentOrgId,
		Status:         1,
		PinYin:         pinyin,
		WuBi:           wubi,
	}

	err := service.ModifyDealer(&dealer)

	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"dealer": dealer,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) GetDealersList() {
	page, _ := c.GetInt64("page", 1)
	limit, _ := c.GetInt64("limit", 7)
	adminUserInfo := c.GetAdminUserInfo()
	deales, total, err := service.FindAllDealerList(adminUserInfo.CurrentOrgId, page, limit)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"dealer": deales,
			"total":  total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) DeleteDealer() {
	id, _ := c.GetInt64("id", 0)
	total, _ := service.FindStockInByDealerId(id)
	if total > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteDealerWrong)
		return
	}
	err := service.DeleteDealerById(id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) GetDealer() {
	id, _ := c.GetInt64("id", 0)
	dealer, err := service.FindDealerById(id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"dealer": dealer,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) CreateManufacturer() {
	manufacturer_name := c.GetString("manufacturer_name")
	contact := c.GetString("contact")
	contact_phone := c.GetString("contact_phone")
	platform_number := c.GetString("platform_number")
	email := c.GetString("email")
	contact_address := c.GetString("contact_address")
	remark := c.GetString("remark")
	pinyin := c.GetString("pinyin")
	wubi := c.GetString("wubi")

	if len(manufacturer_name) <= 0 {
		utils.ErrorLog("len(manufacturer_name) == 0")

		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := c.GetAdminUserInfo()
	total := service.FindManufacturerTotal(adminUserInfo.CurrentOrgId)
	totalStr := strconv.FormatInt(total+1, 10)
	code := "2000" + totalStr
	manufacturer := models.Manufacturer{
		ManufacturerName: manufacturer_name,
		Contact:          contact,
		ContactPhone:     contact_phone,
		ContactAddress:   contact_address,
		Ctime:            time.Now().Unix(),
		Mtime:            time.Now().Unix(),
		Remark:           remark,
		Creater:          adminUserInfo.AdminUser.Id,
		Email:            email,
		PlatformNumber:   platform_number,
		OrgId:            adminUserInfo.CurrentOrgId,
		Status:           1,
		ManufacturerCode: code,
		PinYin:           pinyin,
		WuBi:             wubi,
	}

	err, manufacturers := service.AddSigleManufacturer(&manufacturer)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"manufacturer": manufacturers,
		})

	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}

}
func (c *ManagerCenterApiController) ModifyManufacturer() {

	id, _ := c.GetInt64("id", 0)
	manufacturer_name := c.GetString("manufacturer_name")
	contact := c.GetString("contact")
	contact_phone := c.GetString("contact_phone")
	platform_number := c.GetString("platform_number")
	email := c.GetString("email")
	contact_address := c.GetString("contact_address")
	remark := c.GetString("remark")
	manufacturer_code := c.GetString("manufacturer_code")
	pinyin := c.GetString("pinyin")
	wubi := c.GetString("wubi")
	if id <= 0 {
		utils.ErrorLog("id == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if len(manufacturer_name) <= 0 {
		utils.ErrorLog("len(manufacturer_name) == 0")

		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := c.GetAdminUserInfo()
	manufacturer := models.Manufacturer{
		ID:               id,
		ManufacturerName: manufacturer_name,
		Contact:          contact,
		ContactPhone:     contact_phone,
		ContactAddress:   contact_address,
		Mtime:            time.Now().Unix(),
		Remark:           remark,
		Creater:          adminUserInfo.AdminUser.Id,
		Email:            email,
		PlatformNumber:   platform_number,
		Modifier:         adminUserInfo.AdminUser.Id,
		OrgId:            adminUserInfo.CurrentOrgId,
		ManufacturerCode: manufacturer_code,
		Status:           1,
		PinYin:           pinyin,
		WuBi:             wubi,
	}

	err := service.ModifyManufacturer(&manufacturer)

	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"manufacturer": manufacturer,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}

}
func (c *ManagerCenterApiController) GetManufacturerList() {
	page, _ := c.GetInt64("page", 1)
	limit, _ := c.GetInt64("limit", 10)
	adminUserInfo := c.GetAdminUserInfo()
	manufacturer, total, err := service.FindAllManufacturerList(adminUserInfo.CurrentOrgId, page, limit)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"manufacturer": manufacturer,
			"total":        total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) DeleteManufacturer() {
	id, _ := c.GetInt64("id", 0)
	total, _ := service.FindStockInByManufacturerId(id)
	if total > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteManufacturerWrong)
		return
	}

	err := service.DeleteManufacturerById(id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) GetManufacturer() {
	id, _ := c.GetInt64("id", 0)
	manufacturer, err := service.FindManufacturerById(id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"manufacturer": manufacturer,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}

}
func (c *ManagerCenterApiController) GetAllDealer() {
	adminUserInfo := c.GetAdminUserInfo()
	dealer, err := service.FindAllDealer(adminUserInfo.CurrentOrgId)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"dealer": dealer,
		})
	} else {

		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) GetAllManufacturer() {
	adminUserInfo := c.GetAdminUserInfo()
	manufacturer, err := service.FindAllManufacturer(adminUserInfo.CurrentOrgId)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"manufacturer": manufacturer,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}

}

func (c *ManagerCenterApiController) CreateGoodInfo() {
	good_id, _ := c.GetInt64("good_id", 0)
	specification_name := c.GetString("specification_name")
	good_unit, _ := c.GetInt64("good_unit", -1)
	buy_price, _ := c.GetFloat("buy_price", 0)
	sell_price, _ := c.GetFloat("sell_price", 0)
	remark := c.GetString("remark")
	manufacturer, _ := c.GetInt64("manufacturer", 0)
	dealer, _ := c.GetInt64("dealer", 0)
	expiry_date_warn_day_count, _ := c.GetInt64("expiry_date_warn_day_count", 0)
	stock_warn_count, _ := c.GetInt64("stock_warn_count", 0)
	is_reuse, _ := c.GetInt64("is_reuse", 0)

	good_name := c.GetString("good_name")
	pinyin := c.GetString("pinyin")
	wubi := c.GetString("wubi")
	good_kind, _ := c.GetInt64("good_kind", 0)
	medical_insurance_level, _ := c.GetInt64("medical_insurance_level", 0)
	retail_price, _ := c.GetFloat("retail_price", 0)
	fmt.Println(retail_price)
	medical_insurance_number := c.GetString("medical_insurance_number")
	is_special_diseases, _ := c.GetInt64("is_special_diseases", 0)
	is_record, _ := c.GetInt64("is_record")
	statistics_category, _ := c.GetInt64("statistics_category")
	good_status := c.GetString("good_status")

	default_count, _ := c.GetInt64("default_count")
	sign, _ := c.GetInt64("sign")
	is_default, _ := c.GetInt64("is_default")
	is_charge_use, _ := c.GetInt64("is_charge_use")
	is_charge_predict, _ := c.GetInt64("is_charge_predict")
	is_statistics_work, _ := c.GetInt64("is_statistics_work")
	sort, _ := c.GetInt64("sort")
	is_doctor_use, _ := c.GetInt64("is_doctor_use")
	agent := c.GetString("agent")
	good_number := c.GetString("good_number")

	social_security_directory_code := c.GetString("social_security_directory_code")
	production_type := c.GetString("production_type")
	special_medical := c.GetString("special_medical")
	min_number, _ := c.GetInt64("min_number")
	packing_unit := c.GetString("packing_unit")
	packing_price, _ := c.GetFloat("packing_price")
	min_unit := c.GetString("min_unit")
	default_count_unit := c.GetString("default_count_unit")
	adminUserInfo := c.GetAdminUserInfo()

	totals := service.FindGoodInfoByNameTwo(specification_name, adminUserInfo.CurrentOrgId, good_id, good_name)
	if totals > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeGoodInfoNameExistError)
		return
	}

	total := service.FindAllGoodInfoTotal(adminUserInfo.CurrentOrgId)
	code := strconv.FormatInt(total+1, 10)
	code = "24000000" + code

	goodInfo := models.GoodInfo{
		GoodCode:                    code,
		SpecificationName:           specification_name,
		GoodTypeId:                  good_id,
		GoodUnit:                    good_unit,
		BuyPrice:                    buy_price,
		SellPrice:                   sell_price,
		Remark:                      remark,
		Ctime:                       time.Now().Unix(),
		Manufacturer:                manufacturer,
		Dealer:                      dealer,
		ExpiryDateWarnDayCount:      expiry_date_warn_day_count,
		StockWarnCount:              stock_warn_count,
		IsReuse:                     is_reuse,
		Status:                      1,
		OrgId:                       adminUserInfo.CurrentOrgId,
		Creater:                     adminUserInfo.AdminUser.Id,
		GoodName:                    good_name,
		Pinyin:                      pinyin,
		Wubi:                        wubi,
		GoodKind:                    good_kind,
		MedicalInsuranceNumber:      medical_insurance_number,
		IsSpecialDiseases:           is_special_diseases,
		IsRecord:                    is_record,
		StatisticsCategory:          statistics_category,
		GoodStatus:                  good_status,
		DefaultCount:                default_count,
		Sign:                        sign,
		IsDefault:                   is_default,
		IsChargeUse:                 is_charge_use,
		IsChargePredict:             is_charge_predict,
		IsStatisticsWork:            is_statistics_work,
		Sort:                        sort,
		IsDoctorUse:                 is_doctor_use,
		Agent:                       agent,
		GoodNumber:                  good_number,
		MedicalInsuranceLevel:       medical_insurance_level,
		RetailPrice:                 packing_price,
		SocialSecurityDirectoryCode: social_security_directory_code,
		ProductionType:              production_type,
		SpecialMedical:              special_medical,
		MinNumber:                   min_number,
		PackingUnit:                 packing_unit,
		PackingPrice:                packing_price,
		DefaultCountUnit:            default_count_unit,
		MinUnit:                     min_unit,
	}
	err, goodInfos := service.AddSigleGoodInfo(&goodInfo)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"goodInfo": goodInfos,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}

}

func (c *ManagerCenterApiController) ModifyGoodInfo() {
	id, _ := c.GetInt64("id", 0)
	good_id, _ := c.GetInt64("good_id", 0)
	specification_name := c.GetString("specification_name")
	good_unit, _ := c.GetInt64("good_unit", -1)
	buy_price, _ := c.GetFloat("buy_price", 0)
	sell_price, _ := c.GetFloat("sell_price", 0)
	remark := c.GetString("remark")
	manufacturer, _ := c.GetInt64("manufacturer", 0)
	dealer, _ := c.GetInt64("dealer", 0)
	expiry_date_warn_day_count, _ := c.GetInt64("expiry_date_warn_day_count", 0)
	stock_warn_count, _ := c.GetInt64("stock_warn_count", 0)
	is_reuse, _ := c.GetInt64("is_reuse", 0)
	code := c.GetString("good_code")

	good_name := c.GetString("good_name")
	pinyin := c.GetString("pinyin")
	wubi := c.GetString("wubi")
	good_kind, _ := c.GetInt64("good_kind", 0)
	medical_insurance_level, _ := c.GetInt64("medical_insurance_level", 0)
	retail_price, _ := c.GetFloat("retail_price", 0)
	fmt.Println(retail_price)
	medical_insurance_number := c.GetString("medical_insurance_number")
	is_special_diseases, _ := c.GetInt64("is_special_diseases", 0)
	is_record, _ := c.GetInt64("is_record")
	statistics_category, _ := c.GetInt64("statistics_category")
	good_status := c.GetString("good_status")

	default_count, _ := c.GetInt64("default_count")
	sign, _ := c.GetInt64("sign")
	is_default, _ := c.GetInt64("is_default")
	is_charge_use, _ := c.GetInt64("is_charge_use")
	is_charge_predict, _ := c.GetInt64("is_charge_predict")
	is_statistics_work, _ := c.GetInt64("is_statistics_work")
	sort, _ := c.GetInt64("sort")
	is_doctor_use, _ := c.GetInt64("is_doctor_use")
	agent := c.GetString("agent")
	good_number := c.GetString("good_number")

	social_security_directory_code := c.GetString("social_security_directory_code")
	production_type := c.GetString("production_type")
	special_medical := c.GetString("special_medical")

	min_number, _ := c.GetInt64("min_number")
	packing_unit := c.GetString("packing_unit")
	packing_price, _ := c.GetFloat("packing_price")
	default_count_unit := c.GetString("default_count_unit")
	min_unit := c.GetString("min_unit")
	total, _ := c.GetFloat("total")

	adminUserInfo := c.GetAdminUserInfo()

	goodInfo := models.GoodInfo{
		ID:                          id,
		GoodCode:                    code,
		SpecificationName:           specification_name,
		GoodTypeId:                  good_id,
		GoodUnit:                    good_unit,
		BuyPrice:                    buy_price,
		SellPrice:                   sell_price,
		Remark:                      remark,
		Mtime:                       time.Now().Unix(),
		Manufacturer:                manufacturer,
		Dealer:                      dealer,
		ExpiryDateWarnDayCount:      expiry_date_warn_day_count,
		StockWarnCount:              stock_warn_count,
		IsReuse:                     is_reuse,
		Status:                      1,
		OrgId:                       adminUserInfo.CurrentOrgId,
		Modifier:                    adminUserInfo.AdminUser.Id,
		GoodName:                    good_name,
		Pinyin:                      pinyin,
		Wubi:                        wubi,
		GoodKind:                    good_kind,
		MedicalInsuranceNumber:      medical_insurance_number,
		IsSpecialDiseases:           is_special_diseases,
		IsRecord:                    is_record,
		StatisticsCategory:          statistics_category,
		GoodStatus:                  good_status,
		DefaultCount:                default_count,
		Sign:                        sign,
		IsDefault:                   is_default,
		IsChargeUse:                 is_charge_use,
		IsChargePredict:             is_charge_predict,
		IsStatisticsWork:            is_statistics_work,
		Sort:                        sort,
		IsDoctorUse:                 is_doctor_use,
		Agent:                       agent,
		GoodNumber:                  good_number,
		MedicalInsuranceLevel:       medical_insurance_level,
		RetailPrice:                 packing_price,
		SpecialMedical:              special_medical,
		SocialSecurityDirectoryCode: social_security_directory_code,
		ProductionType:              production_type,
		MinNumber:                   min_number,
		PackingUnit:                 packing_unit,
		PackingPrice:                packing_price,
		DefaultCountUnit:            default_count_unit,
		MinUnit:                     min_unit,
		Total:                       total,
	}

	totals := service.FindGoodInfoByNameOne(specification_name, adminUserInfo.CurrentOrgId, good_id, id, good_name)
	if totals > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeGoodInfoNameExistError)
		return
	}
	err, goodInfos := service.ModifyGoodInfo(&goodInfo)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"goodInfo": goodInfos,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}

}
func (c *ManagerCenterApiController) GetGoodInfoList() {
	page, _ := c.GetInt64("page", 1)
	limit, _ := c.GetInt64("limit", 7)
	keyword := c.GetString("keyword")
	is_use, _ := c.GetInt64("is_use")
	is_charge, _ := c.GetInt64("is_charge")
	good_kind, _ := c.GetInt64("good_kind")
	is_mark, _ := c.GetInt64("is_mark")
	manufacturer, _ := c.GetInt64("manufacturer")
	adminUserInfo := c.GetAdminUserInfo()
	goodInfos, total, err := service.FindGoodInfoList(adminUserInfo.CurrentOrgId, page, limit, keyword, is_use, is_charge, good_kind, is_mark, manufacturer)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"list":  goodInfos,
			"total": total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}

}
func (c *ManagerCenterApiController) DeleteGoodInfo() {
	id, _ := c.GetInt64("id", 0)
	adminUserInfo := c.GetAdminUserInfo()

	total, _ := service.FindWarehouseInfoTotalByGoodId(id)
	total2, _ := service.FindWarehouseOutInfoTotalByGoodId(id)

	if total > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteGoodInfoFail)
		return
	}
	if total2 > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteGoodInfoFail)
		return
	}

	err := service.DeleteGoodInfoById(id, adminUserInfo.AdminUser.Id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}

}

func (c *ManagerCenterApiController) GetGoodInfoByGoodId() {
	id, _ := c.GetInt64("id", 0)
	goodInfo, err := service.FindGoodInfoByGoodId(id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"list": goodInfo,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (c *ManagerCenterApiController) GetGoodInfoById() {
	id, _ := c.GetInt64("id", 0)
	goodInfo, err := service.FindGoodInfoById(id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"goodInfo": goodInfo,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (c *ManagerCenterApiController) GetMedicineInsurancePercent() {
	adminUser := c.GetAdminUserInfo()
	type_id, _ := c.GetInt64("type_id", 0)
	module, _ := c.GetInt64("module", 0)

	mip, err := service.GetLastMedicineInsurance(adminUser.CurrentOrgId, type_id, module)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"mip": mip,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (c *ManagerCenterApiController) CreateMZSick() {
	class_name := c.GetString("class_name")
	content_code := c.GetString("content_code")
	country_code := c.GetString("country_code")
	country_content_name := c.GetString("country_content_name")
	remark := c.GetString("remark")
	pinyin := c.GetString("pinyin")
	wubi := c.GetString("wubi")

	if len(class_name) <= 0 {
		utils.ErrorLog("len(class_name) == 0")

		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if len(content_code) <= 0 {
		utils.ErrorLog("len(content_code) == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := c.GetAdminUserInfo()

	dealer := models.OutpatientServiceSick{
		ClassName:          class_name,
		ContentCode:        content_code,
		CountryCode:        country_code,
		CountryContentName: country_content_name,
		Ctime:              time.Now().Unix(),
		Mtime:              time.Now().Unix(),
		Remark:             remark,
		UserOrgId:          adminUserInfo.CurrentOrgId,
		Status:             1,
		Pinyin:             pinyin,
		Wubi:               wubi,
	}

	err, dealers := service.AddSigleMZSick(&dealer)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"sick": dealers,
		})

	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)

	}

}
func (c *ManagerCenterApiController) ModifyMZSick() {
	id, _ := c.GetInt64("id", 0)

	class_name := c.GetString("class_name")
	content_code := c.GetString("content_code")
	country_code := c.GetString("country_code")
	country_content_name := c.GetString("country_content_name")
	remark := c.GetString("remark")
	pinyin := c.GetString("pinyin")
	wubi := c.GetString("wubi")

	if id <= 0 {
		utils.ErrorLog("id == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if len(class_name) <= 0 {
		utils.ErrorLog("len(class_name) == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if len(content_code) <= 0 {
		utils.ErrorLog("len(content_code) == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := c.GetAdminUserInfo()
	dealer := models.OutpatientServiceSick{
		ID:                 id,
		ClassName:          class_name,
		ContentCode:        content_code,
		CountryCode:        country_code,
		CountryContentName: country_content_name,
		Ctime:              time.Now().Unix(),
		Mtime:              time.Now().Unix(),
		Remark:             remark,
		UserOrgId:          adminUserInfo.CurrentOrgId,
		Pinyin:             pinyin,
		Wubi:               wubi,
		Status:             1,
	}

	err := service.ModifyMZSick(&dealer)

	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"sick": dealer,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) GetMZSickList() {
	page, _ := c.GetInt64("page", 1)
	limit, _ := c.GetInt64("limit", 7)
	adminUserInfo := c.GetAdminUserInfo()
	mzSick, total, err := service.FindAllMZSickList(adminUserInfo.CurrentOrgId, page, limit)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"sick":  mzSick,
			"total": total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) DeleteMZSick() {
	id, _ := c.GetInt64("id", 0)
	err := service.DeleteMZSickById(id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) GetMZSick() {
	id, _ := c.GetInt64("id", 0)
	mzSick, err := service.FindMZSickById(id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"sick": mzSick,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (c *ManagerCenterApiController) DeleteBaseDrugById() {

	id, _ := c.GetInt64("id")
	//查询入库单
	_, errcode := service.GetDrugWareoutInfo(id)
	if errcode == gorm.ErrRecordNotFound {
		//查询出库单
		_, errcodes := service.GetDrugWareOutById(id)
		if errcodes == gorm.ErrRecordNotFound {
			//删除
			service.DeleteBaseDrugById(id)
			returnData := make(map[string]interface{}, 0)
			returnData["msg"] = "ok"
			c.ServeSuccessJSON(returnData)
			return
		} else if errcodes == nil {
			c.ServeFailJsonSend(enums.ErrorCodeDataException, "已出库")
			return
		}
	} else if errcode == nil {
		c.ServeFailJsonSend(enums.ErrorCodeDataException, "已入库")
		return
	}
}

func (c *ManagerCenterApiController) CreateAddition() {
	name := c.GetString("name")
	code := c.GetString("code")
	//price, _ := c.GetFloat("price")

	price := c.GetString("price")
	price_float, _ := strconv.ParseFloat(price, 64)

	if len(name) <= 0 {
		utils.ErrorLog("len(name) == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	//if len(code) <= 0 {
	//	utils.ErrorLog("len(code) == 0")
	//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
	//	return
	//}

	adminUserInfo := c.GetAdminUserInfo()

	addition := models.XtHisAddtionConfig{
		Name:      name,
		Code:      code,
		Status:    1,
		Price:     price_float,
		Ctime:     time.Now().Unix(),
		Mtime:     time.Now().Unix(),
		UserOrgId: adminUserInfo.CurrentOrgId,
	}

	err, additions := service.AddSigleAddition(&addition)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"addition": additions,
		})

	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)

	}

}
func (c *ManagerCenterApiController) ModifyAddition() {
	id, _ := c.GetInt64("id", 0)

	name := c.GetString("name")
	code := c.GetString("code")
	price, _ := c.GetFloat("price")

	if id <= 0 {
		utils.ErrorLog("id == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if len(name) <= 0 {
		utils.ErrorLog("len(class_name) == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	//if len(code) <= 0 {
	//	utils.ErrorLog("len(content_code) == 0")
	//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
	//	return
	//}

	adminUserInfo := c.GetAdminUserInfo()
	addition := models.XtHisAddtionConfig{
		ID:        id,
		Name:      name,
		Code:      code,
		Ctime:     time.Now().Unix(),
		Mtime:     time.Now().Unix(),
		UserOrgId: adminUserInfo.CurrentOrgId,
		Price:     price,
		Status:    1,
	}

	err := service.ModifyAddition(&addition)

	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"addition": addition,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) GetAdditionList() {
	page, _ := c.GetInt64("page", 1)
	limit, _ := c.GetInt64("limit", 7)
	adminUserInfo := c.GetAdminUserInfo()
	addition, total, err := service.FindAllAdditionList(adminUserInfo.CurrentOrgId, page, limit)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"addition": addition,
			"total":    total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) DeleteAddition() {
	id, _ := c.GetInt64("id", 0)

	err := service.DeleteAdditionById(id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) GetAddition() {
	id, _ := c.GetInt64("id", 0)
	addition, err := service.FindAdditionById(id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"addition": addition,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (c *ManagerCenterApiController) CreateDiagnose() {
	class_name := c.GetString("class_name")
	content_code := c.GetString("content_code")
	country_code := c.GetString("country_code")
	country_content_name := c.GetString("country_content_name")
	remark := c.GetString("remark")
	pinyin := c.GetString("pinyin")
	wubi := c.GetString("wubi")

	if len(class_name) <= 0 {
		utils.ErrorLog("len(class_name) == 0")

		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if len(content_code) <= 0 {
		utils.ErrorLog("len(content_code) == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := c.GetAdminUserInfo()

	dealer := models.HisXtDiagnoseConfig{
		ClassName:          class_name,
		ContentCode:        content_code,
		CountryCode:        country_code,
		CountryContentName: country_content_name,
		Ctime:              time.Now().Unix(),
		Mtime:              time.Now().Unix(),
		Remark:             remark,
		UserOrgId:          adminUserInfo.CurrentOrgId,
		Status:             1,
		Pinyin:             pinyin,
		Wubi:               wubi,
	}

	err, dealers := service.AddSigleDiagnose(&dealer)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"sick": dealers,
		})

	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)

	}

}
func (c *ManagerCenterApiController) ModifyDiagnose() {
	id, _ := c.GetInt64("id", 0)

	class_name := c.GetString("class_name")
	content_code := c.GetString("content_code")
	country_code := c.GetString("country_code")
	country_content_name := c.GetString("country_content_name")
	remark := c.GetString("remark")
	pinyin := c.GetString("pinyin")
	wubi := c.GetString("wubi")

	if id <= 0 {
		utils.ErrorLog("id == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if len(class_name) <= 0 {
		utils.ErrorLog("len(class_name) == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if len(content_code) <= 0 {
		utils.ErrorLog("len(content_code) == 0")
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := c.GetAdminUserInfo()
	dealer := models.HisXtDiagnoseConfig{
		ID:                 id,
		ClassName:          class_name,
		ContentCode:        content_code,
		CountryCode:        country_code,
		CountryContentName: country_content_name,
		Ctime:              time.Now().Unix(),
		Mtime:              time.Now().Unix(),
		Remark:             remark,
		UserOrgId:          adminUserInfo.CurrentOrgId,
		Pinyin:             pinyin,
		Wubi:               wubi,
		Status:             1,
	}

	err := service.ModifyDiagnose(&dealer)

	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"sick": dealer,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) GetDiagnoseList() {
	page, _ := c.GetInt64("page", 1)
	limit, _ := c.GetInt64("limit", 7)
	adminUserInfo := c.GetAdminUserInfo()
	mzSick, total, err := service.FindAllDiagnoseList(adminUserInfo.CurrentOrgId, page, limit)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"sick":  mzSick,
			"total": total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) DeleteDiagnose() {
	id, _ := c.GetInt64("id", 0)
	err := service.DeleteDiagnoseById(id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *ManagerCenterApiController) GetDiagnose() {
	id, _ := c.GetInt64("id", 0)
	mzSick, err := service.FindDiagnoseById(id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"sick": mzSick,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (c *ManagerCenterApiController) GetAllDrugList() {

	orgId := c.GetAdminUserInfo().CurrentOrgId

	list, err := service.GetAllDrugList(orgId)
	manufacturerList, _ := service.GetAllManufacturerList(orgId)
	dealerList, _ := service.GetAllDealerList(orgId)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"list":             list,
			"manufacturerList": manufacturerList,
			"dealerList":       dealerList,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (c *ManagerCenterApiController) GetSearchDrugList() {
	keyword := c.GetString("keyword")
	orgId := c.GetAdminUserInfo().CurrentOrgId
	list, err := service.GetSearchDrugList(keyword, orgId)
	manufacturerList, _ := service.GetAllManufacturerList(orgId)
	dealerList, _ := service.GetAllDealerList(orgId)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"list":             list,
			"manufacturerList": manufacturerList,
			"dealerList":       dealerList,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
