package service

import (
	"XT_New/models"
	"strings"
	"time"

	"github.com/jinzhu/gorm"
)

func GetPublicDrugDics() (drugs []*models.DrugDic, total int64, err error) {
	err = readDb.Model(&models.DrugDic{}).Where("org_id = 0 and status=1").Count(&total).Order("id desc").Find(&drugs).Error
	return
}

func GetPublicDrugWayDics() (drugways []*models.DrugwayDic, total int64, err error) {
	err = readDb.Model(&models.DrugwayDic{}).Where("org_id = 0 and status=1").Count(&total).Order("id desc").Find(&drugways).Error
	return
}

func GetPublicExecutionFrequencyDics() (dics []*models.ExecutionFrequencyDic, total int64, err error) {
	err = readDb.Model(&models.ExecutionFrequencyDic{}).Where("org_id = 0 and status=1").Count(&total).Order("id desc").Find(&dics).Error
	return
}

func GetDrugDics(orgid int64) (drugs []*models.DrugDic, total int64, err error) {
	err = readDb.Model(&models.DrugDic{}).Where("org_id =? and status=1", orgid).Count(&total).Order("id desc").Find(&drugs).Error
	return
}

func GetAdviceTemplates(orgid int64) (templates []*models.DoctorAdviceTemplate, total int64, err error) {
	err = readDb.Model(&models.DoctorAdviceTemplate{}).Where("org_id =? and status=1", orgid).Count(&total).Order("id desc").Find(&templates).Error
	return
}

func GetDrugWayDics(orgid int64) (drugways []*models.DrugwayDic, total int64, err error) {
	err = readDb.Model(&models.DrugwayDic{}).Where("(org_id =? or org_id = 0) and status=1", orgid).Count(&total).Order("id desc").Find(&drugways).Error
	return
}

func GetExecutionFrequencyDics(orgid int64) (dics []*models.ExecutionFrequencyDic, total int64, err error) {
	err = readDb.Model(&models.ExecutionFrequencyDic{}).Where("(org_id =? or org_id = 0) and status=1", orgid).Count(&total).Order("id desc").Find(&dics).Error
	return
}

func CreateDrugDic(d *models.DrugDic) (err error) {
	err = readDb.Create(&d).Error
	return
}

func UpdateDrugDic(d *models.DrugDic) (err error) {
	err = readDb.Save(&d).Error
	return
}

func FindDrugDic(orgid, id int64) (*models.DrugDic, error) {
	var drugdic models.DrugDic
	err := readDb.Model(&models.DrugDic{}).Where("id=? and org_id =? and status=1", id, orgid).First(&drugdic).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

	if err != nil {
		return nil, err
	}
	return &drugdic, nil
}

func CreateDrugWay(d *models.DrugwayDic) (err error) {
	err = readDb.Create(&d).Error
	return
}

func FindDrugWay(orgid, id int64) (*models.DrugwayDic, error) {
	var drugway models.DrugwayDic
	err := readDb.Model(&models.DrugwayDic{}).Where("id=? and org_id =? and status=1", id, orgid).First(&drugway).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

	if err != nil {
		return nil, err
	}
	return &drugway, nil
}

func UpdateDrugWay(d *models.DrugwayDic) (err error) {
	err = readDb.Save(&d).Error
	return
}

func CreateExecutionFrequency(d *models.ExecutionFrequencyDic) (err error) {
	err = readDb.Create(&d).Error
	return
}

func FindExecutionFrequency(orgid, id int64) (*models.ExecutionFrequencyDic, error) {
	var ef models.ExecutionFrequencyDic
	err := readDb.Model(&models.ExecutionFrequencyDic{}).Where("id=? and org_id =? and status=1", id, orgid).First(&ef).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

	if err != nil {
		return nil, err
	}
	return &ef, nil
}

func UpdateExecutionFrequency(d *models.ExecutionFrequencyDic) (err error) {
	err = readDb.Save(&d).Error
	return
}

func CreateAdviceTemplate(d *models.DoctorAdviceTemplate) (err error) {
	err = readDb.Create(&d).Error
	return
}

func FindAdviceTemplate(orgid, id int64) (*models.DoctorAdviceTemplate, error) {
	var template models.DoctorAdviceTemplate
	err := readDb.Model(&models.DoctorAdviceTemplate{}).Where("id=? and org_id =? and status=1", id, orgid).First(&template).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

	if err != nil {
		return nil, err
	}
	return &template, nil
}

func UpdateAdviceTemplate(d *models.DoctorAdviceTemplate) (err error) {
	err = writeDb.Save(&d).Error
	return
}

func UpdateAdviceAndSubAdviceTemplate(d *models.DoctorAdviceTemplate) (err error) {
	err = writeDb.Save(&d).Error
	err = writeDb.Model(&models.DoctorAdviceTemplate{}).Where("status=1 AND parent_id = ?", d.ID).Updates(map[string]interface{}{"status": 2, "updated_time": time.Now().Unix()}).Error
	return
}

func CreateTemplate(template *models.DoctorAdviceParentTemplate) (err error) {
	err = readDb.Create(&template).Error
	return
}

//func CreateBatchRecord(template []*models.DoctorAdviceTemplate) (err error) {
//	err = writeDb.Create(template).Error
//	return
//}

func CreateSubTemplate(template []*models.DoctorAdviceTemplate) (err error) {
	if len(template) > 0 {
		utx := writeDb.Begin()
		if len(template) > 0 {
			thisSQL := "INSERT INTO xt_doctor_advice_template (org_id, advice_name, advice_desc, single_dose, single_dose_unit,prescribing_number," +
				"prescribing_number_unit,delivery_way,execution_frequency,advice_doctor,status,created_time,updated_time,template_id,drug_spec,drug_spec_unit,advice_type,day_count,week_days,frequency_type) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, info := range template {
				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
				insertData = append(insertData, info.OrgId)
				insertData = append(insertData, info.AdviceName)
				insertData = append(insertData, info.AdviceDesc)
				insertData = append(insertData, info.SingleDose)
				insertData = append(insertData, info.SingleDoseUnit)
				insertData = append(insertData, info.PrescribingNumber)
				insertData = append(insertData, info.PrescribingNumberUnit)
				insertData = append(insertData, info.DeliveryWay)
				insertData = append(insertData, info.ExecutionFrequency)
				insertData = append(insertData, info.AdviceDoctor)
				insertData = append(insertData, info.Status)
				insertData = append(insertData, info.CreatedTime)
				insertData = append(insertData, info.UpdatedTime)
				insertData = append(insertData, info.TemplateId)
				insertData = append(insertData, info.DrugSpec)
				insertData = append(insertData, info.DrugSpecUnit)
				insertData = append(insertData, info.AdviceType)
				insertData = append(insertData, info.DayCount)
				insertData = append(insertData, info.WeekDays)
				insertData = append(insertData, info.FrequencyType)
			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return

}

func FindDoctorAdviceTemplateById(id int64, org_id int64) (temps models.DoctorAdviceParentTemplate, err error) {
	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Preload("DoctorAdviceTemplate", "status = 1").Where("org_id = ? AND status=1 AND id = ?", org_id, id).Order("id desc").First(&temps).Error
	return
}

func FindAllAdviceTemplate(org_id int64, advice_type int64) (temps []*models.DoctorAdviceParentTemplate, err error) {
	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Preload("DoctorAdviceTemplate", func(db *gorm.DB) *gorm.DB {
		return db.Select("id,advice_name,advice_desc,single_dose,single_dose_unit,prescribing_number,prescribing_number_unit,delivery_way,execution_frequency,status,created_time,updated_time,parent_id,template_id,drug_spec,drug_spec_unit,advice_type,day_count,week_days,frequency_type, IF(parent_id>0, parent_id, id) as advice_order").Where("status = 1").Order("advice_order desc, id")
	}).Where("org_id = ? AND status=1 AND advice_type = ?", org_id, advice_type).Find(&temps).Error
	return
}

func GetAllAdviceSubTemplates(orgid int64, template_id int64) (total int64, err error) {
	err = readDb.Model(&models.DoctorAdviceTemplate{}).Where("org_id =? AND status=1 AND template_id = ?", orgid, template_id).Count(&total).Error
	return
}

func UpdateParentAdviceTemplates(orgid int64, tempelate_id int64) (err error) {
	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Where("org_id =? AND status=1 AND id = ?", orgid, tempelate_id).Updates(map[string]interface{}{"status": "0", "updated_time": time.Now().Unix()}).Error
	return
}

func FindTemplateRecordByName(orgid int64, name string) (total int64) {
	readDb.Model(&models.DoctorAdviceParentTemplate{}).Where("name = ? AND org_id = ? AND status= 1 ", name, orgid).Count(&total)
	return
}

func FindParentTemplateRecordById(orgid int64, template_id int64) (parentTemplate models.DoctorAdviceParentTemplate, err error) {
	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Where("id = ? AND org_id = ? AND status= 1 ", template_id, orgid).First(&parentTemplate).Error
	return
}

func DeleteParentDoctorAdviceByTemplateId(template_id int64, org_id int64) (err error) {

	ut := writeDb.Begin()
	err = writeDb.Model(&models.DoctorAdviceParentTemplate{}).Where("status=1 AND id = ? AND org_id = ?", template_id, org_id).Updates(map[string]interface{}{"status": "0", "updated_time": time.Now().Unix()}).Error

	if err != nil {
		ut.Rollback()
		return
	}
	err = writeDb.Model(&models.DoctorAdviceTemplate{}).Where("status=1 AND template_id = ? AND org_id = ?", template_id, org_id).Updates(map[string]interface{}{"status": "2", "updated_time": time.Now().Unix()}).Error
	if err != nil {
		ut.Rollback()
		return
	}
	ut.Commit()
	return err
}

func ModifyTemplateName(id int64, template_name string) (err error) {
	err = writeDb.Model(&models.DoctorAdviceParentTemplate{}).Where("status=1 AND id = ?", id).Updates(map[string]interface{}{"name": template_name, "updated_time": time.Now().Unix()}).Error
	return err
}

func FindOtherAllAdviceTemplate(org_id int64) (temps []*models.DoctorAdviceParentTemplate, err error) {
	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Preload("DoctorAdviceTemplate", func(db *gorm.DB) *gorm.DB {
		return db.Select("id,advice_name,advice_desc,single_dose,single_dose_unit,prescribing_number,prescribing_number_unit,delivery_way,execution_frequency,status,created_time,updated_time,parent_id,template_id,drug_spec,drug_spec_unit,advice_type,day_count,week_days,frequency_type, IF(parent_id>0, parent_id, id) as advice_order").Where("status = 1").Order("advice_order desc, id")
	}).Where("org_id = ? AND status=1 ", org_id).Find(&temps).Error
	return
	//.Scan(&advices).Error

}

func GetHandleData(id int64) (models.ConfigViewModel, error) {
	config := models.ConfigViewModel{}
	err := readDb.Model(&config).Where("id=?", id).Find(&config).Error
	return config, err
}

func UpdateDataTwo(id int64, model models.ConfigViewModel) error {

	err := writeDb.Model(&model).Where("id=?", id).Update(map[string]interface{}{"name": model.Name, "orders": model.Order, "remark": model.Remark, "update_time": time.Now().Unix()}).Error
	return err
}
