package service

import (
	"Xcx_New/models"
	"github.com/jinzhu/gorm"
	"time"
)

func GetDictionaryConfigList(orgID int64) (dataconfig interface{}, err error) {
	var configList []*models.DictionaryDataconfig

	err = readDb.Model(&models.DictionaryDataconfig{}).Where("(org_id in (0,?) and status = 1) or (status = 0 and delete_id_system > 0 and org_id = ?)", orgID, orgID).Order("orders asc, id asc").Find(&configList).Error
	if err != nil {
		return nil, err
	}

	// configResult := make([]*ConfigViewModel,0)
	childConfig := make(map[int64][]*models.DictionaryDataconfig)
	resultConfig := make(map[string][]*models.DictionaryConfigViewModel)
	deleteSystemChilds := make([]*models.DictionaryDataconfig, 0)
	editSystemChilds := make([]*models.DictionaryDataconfig, 0)
	for _, config := range configList {
		if config.Status == 1 && config.DeleteIdSystem > 0 {
			editSystemChilds = append(editSystemChilds, config)
		}

		if config.Status == 0 && config.DeleteIdSystem > 0 {
			deleteSystemChilds = append(deleteSystemChilds, config)
		}
	}
	continueFlag := false
	for _, config := range configList {
		continueFlag = false
		if config.ParentId == 0 {
			newConfig := &models.DictionaryConfigViewModel{
				ID:           config.ID,
				ParentId:     config.ParentId,
				Module:       config.Module,
				OrgId:        config.OrgId,
				Name:         config.Name,
				FieldName:    config.FieldName,
				Value:        config.Value,
				CreateUserId: config.CreateUserId,
				Status:       config.Status,
				Remark:       config.Remark,
				Title:        config.Title,
				Content:      config.Content,
			}
			// configResult = append(configResult,newConfig)
			result := resultConfig[config.Module]
			if result == nil {
				result = make([]*models.DictionaryConfigViewModel, 0)
			}
			for _, vm := range editSystemChilds {
				if vm.DeleteIdSystem == config.ID {
					continueFlag = true
					break
				}
			}

			for _, _vm := range deleteSystemChilds {
				if _vm.DeleteIdSystem == config.ID {
					continueFlag = true
					break
				}
			}
			if config.OrgId != 0 && config.Status == 0 && config.DeleteIdSystem > 0 {
				continue
			}
			if continueFlag {
				continue
			}
			result = append(result, newConfig)
			resultConfig[config.Module] = result
		} else {
			childs := childConfig[config.ParentId]
			if childs == nil {
				childs = make([]*models.DictionaryDataconfig, 0)
			}
			continueFlag := false
			for _, vm := range editSystemChilds {
				if vm.DeleteIdSystem == config.ID {
					continueFlag = true
					break
				}
			}

			for _, _vm := range deleteSystemChilds {
				if _vm.DeleteIdSystem == config.ID {
					continueFlag = true
					break
				}
			}
			if config.OrgId != 0 && config.Status == 0 && config.DeleteIdSystem > 0 {
				continue
			}
			if continueFlag {
				continue
			}

			childs = append(childs, config)
			childConfig[config.ParentId] = childs
		}
	}

	for _, vm := range resultConfig {
		for _, _vm := range vm {
			_vm.Childs = childConfig[_vm.ID]
		}
		// vm.Childs = childConfig[vm.ID]
	}
	return resultConfig, err
}

func CreateDictionaryConfig(dataconfig *models.DictionaryDataconfig) (err error) {
	// readDb.Model(&models.Dataconfig{}).Where("module = ? and parent_id = 0 and org_id in (0,?)",dataconfig.Module,dataconfig.OrgId).Count(&total)
	err = readDb.Create(&dataconfig).Error
	return
}

func GetDictionaryChildValue(module string, parent_id int64, org_id int64) (value int) {
	readDb.Model(&models.DictionaryDataconfig{}).Where("module=? and parent_id=? and org_id in (0,?)", module, parent_id, org_id).Count(&value)
	return
}

func FindDictionaryConfigByTitle(module string, title string, org_id int64) (dataconfig models.DictionaryDataconfig, err error) {
	err = readDb.Model(&models.DictionaryDataconfig{}).Where("module=? and title=? and org_id in (0,?) and status = 1", module, title, org_id).First(&dataconfig).Error
	return
}

func UpdateDictionaryTemplate(dataconfig *models.DictionaryDataconfig) (err error) {
	err = readDb.Model(&models.DictionaryDataconfig{}).Where("id =?", dataconfig.ID).Update(map[string]interface{}{"title": dataconfig.Title, "content": dataconfig.Content, "update_time": dataconfig.UpdatedTime, "remark": dataconfig.Remark}).Error
	return
}

func UpdateDictionaryChildConfig(dataconfig *models.DictionaryDataconfig) (err error) {
	err = readDb.Model(&models.DictionaryDataconfig{}).Where("id =?", dataconfig.ID).Update(map[string]interface{}{"name": dataconfig.Name, "update_time": dataconfig.UpdatedTime, "remark": dataconfig.Remark, "orders": dataconfig.Order, "code": dataconfig.Code}).Error
	return
}

func DeleteDictionaryChildConfig(dataconfig *models.DictionaryDataconfig) (err error) {
	err = readDb.Model(&models.DictionaryDataconfig{}).Where("id =?", dataconfig.ID).Update(map[string]interface{}{"status": dataconfig.Status, "update_time": dataconfig.UpdatedTime}).Error
	return
}

func CreateBaseDrugLib(lib *models.BaseDrugLib) (err error) {
	err = writeDb.Create(&lib).Error
	return
}

func UpdateBaseDrugLib(lib *models.BaseDrugLib) (err error) {
	err = writeDb.Save(lib).Error
	return
}

func FindBaseDrugLibRecordCount(lib *models.BaseDrugLib) (count int64) {
	readDb.Model(&models.BaseDrugLib{}).Where("org_id = ? AND drug_name = ? AND  drug_category = ? AND drug_spec=? AND drug_type=? AND status = 1", lib.OrgId, lib.DrugName, lib.DrugCategory, lib.DrugSpec, lib.DrugType).Count(&count)
	return
}

func FindBaseDrugLibRecordCountOne(lib *models.BaseDrugLib) (count int64) {
	readDb.Model(&models.BaseDrugLib{}).Where("org_id = ? and drug_name = ? and dose = ? and dose_unit = ? and min_number = ? and min_unit = ? and max_unit = ? and manufacturer = ? and status = 1", lib.OrgId, lib.DrugName, lib.Dose, lib.DoseUnit, lib.MinNumber, lib.MinUnit, lib.MaxUnit, lib.Manufacturer).Count(&count)
	return
}

func FindAllDrugLibRecordTotal(org_id int64) (count int64) {
	readDb.Model(&models.BaseDrugLib{}).Where("org_id = ? AND status = 1", org_id).Count(&count)
	return
}

func FindBaseDrugLibRecord(org_id int64, id int64) (lib models.BaseDrugLib, err error) {
	err = readDb.Model(&models.BaseDrugLib{}).Where("org_id = ? AND id = ? AND status = 1", org_id, id).First(&lib).Error
	return
}

func GetBaseDrugLibList(org_id int64, keyword string, page int64, limit int64, is_use int64, is_charge int64, is_inject int64, manufacturer int64, isRecord int64) (list []*models.BaseDrugLib, total int64, err error) {

	db := readDb.Model(&models.BaseDrugLib{}).Where("org_id = ?  AND status = 1", org_id)
	if len(keyword) != 0 {
		keyword = "%" + keyword + "%"
		db = db.Where("drug_name Like ?", keyword)

	}

	if is_use != 0 {
		if is_use == 1 {
			db = db.Where("find_in_set('停用',drug_status) = 0")

		} else {
			db = db.Where("find_in_set('停用',drug_status) > 0")
		}
	}

	if is_charge != 0 {
		//db = db.Where("drug_name Like ?", keyword)
		if is_charge == 1 {
			db = db.Where("find_in_set('收费',drug_status) > 0")

		} else {
			db = db.Where("find_in_set('收费',drug_status) = 0")
		}
	}

	if is_inject != 0 {
		//db = db.Where("drug_name Like ?", keyword)
		if is_inject == 1 {
			db = db.Where("find_in_set('注射类',drug_status) > 0")

		} else {
			db = db.Where("find_in_set('注射类',drug_status) = 0")
		}

	}

	if manufacturer > 0 {
		db = db.Where("manufacturer = ?", manufacturer)
	}
	if isRecord > 0 {
		db = db.Where("is_mark = ?", isRecord)
	}
	offset := (page - 1) * limit

	err = db.Count(&total).Offset(offset).Limit(limit).Order("ctime desc").Find(&list).Error
	return
}

func CreateMedicineInsurancePercentage(mip *models.MedicineInsurancePercentage) (err error) {
	err = writeDb.Create(mip).Error
	return
}

func CreateUnitSafeguard(dus *models.DrugUnitSafeguard) (err error) {
	err = writeDb.Create(dus).Error
	return
}

func AddSigleMZSick(dealer *models.OutpatientServiceSick) (error, *models.OutpatientServiceSick) {
	err := writeDb.Create(&dealer).Error
	return err, dealer
}

func ModifyMZSick(mesick *models.OutpatientServiceSick) error {
	err := writeDb.Save(&mesick).Error

	return err
}

func FindAllMZSickList(orgId int64, page int64, limit int64) (list []*models.OutpatientServiceSick, total int64, err error) {
	offset := (page - 1) * limit
	db := readDb.Model(&models.OutpatientServiceSick{})
	db = db.Where("user_org_id = ? AND status = 1", orgId)
	err = db.Count(&total).Offset(offset).Limit(limit).Order("ctime desc").Find(&list).Error
	return
}

func DeleteMZSickById(id int64) error {
	err := writeDb.Model(&models.OutpatientServiceSick{}).Where("id = ? AND status = 1", id).Updates(map[string]interface{}{"mtime": time.Now().Unix(), "status": 0}).Error
	return err
}

func FindMZSickById(id int64) (*models.OutpatientServiceSick, error) {
	dealer := &models.OutpatientServiceSick{}
	err := readDb.Model(&models.OutpatientServiceSick{}).Where("id = ? AND status = 1", id).First(&dealer).Error
	return dealer, err
}

func GetDrugWareoutInfo(id int64) (*models.XtDrugWarehouseInfo, error) {

	info := models.XtDrugWarehouseInfo{}
	err = XTReadDB().Model(&info).Where("drug_id = ? and status = 1", id).Find(&info).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &info, nil
}

func GetDrugWareOutById(id int64) (*models.XtDrugWarehouseOutInfo, error) {

	info := models.XtDrugWarehouseOutInfo{}
	err := XTReadDB().Model(&info).Where("drug_id = ? and status = 1", id).Find(&info).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &info, nil
}

func DeleteBaseDrugById(id int64) error {

	drug := models.XtBaseDrug{}
	err := XTWriteDB().Model(&drug).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
	return err
}

func AddSigleAddition(dealer *models.XtHisAddtionConfig) (error, *models.XtHisAddtionConfig) {
	err := writeDb.Create(&dealer).Error
	return err, dealer
}

func ModifyAddition(mesick *models.XtHisAddtionConfig) error {
	err := writeDb.Save(&mesick).Error

	return err
}

func FindAllAdditionList(orgId int64, page int64, limit int64) (list []*models.XtHisAddtionConfig, total int64, err error) {
	offset := (page - 1) * limit
	db := readDb.Model(&models.XtHisAddtionConfig{})
	db = db.Where("user_org_id = ? AND status = 1", orgId)
	err = db.Count(&total).Offset(offset).Limit(limit).Order("ctime desc").Find(&list).Error
	return
}

func DeleteAdditionById(id int64) error {
	err := writeDb.Model(&models.XtHisAddtionConfig{}).Where("id = ? AND status = 1", id).Updates(map[string]interface{}{"mtime": time.Now().Unix(), "status": 0}).Error
	return err
}

func FindAdditionById(id int64) (*models.XtHisAddtionConfig, error) {
	dealer := &models.XtHisAddtionConfig{}
	err := readDb.Model(&models.XtHisAddtionConfig{}).Where("id = ? AND status = 1", id).First(&dealer).Error
	return dealer, err
}

func AddSigleDiagnose(dealer *models.HisXtDiagnoseConfig) (error, *models.HisXtDiagnoseConfig) {
	err := writeDb.Create(&dealer).Error
	return err, dealer
}

func ModifyDiagnose(mesick *models.HisXtDiagnoseConfig) error {
	err := writeDb.Save(&mesick).Error

	return err
}

func FindAllDiagnoseList(orgId int64, page int64, limit int64) (list []*models.HisXtDiagnoseConfig, total int64, err error) {
	offset := (page - 1) * limit
	db := readDb.Model(&models.HisXtDiagnoseConfig{})
	db = db.Where("user_org_id = ? AND status = 1", orgId)
	err = db.Count(&total).Offset(offset).Limit(limit).Order("ctime desc").Find(&list).Error
	return
}

func DeleteDiagnoseById(id int64) error {
	err := writeDb.Model(&models.HisXtDiagnoseConfig{}).Where("id = ? AND status = 1", id).Updates(map[string]interface{}{"mtime": time.Now().Unix(), "status": 0}).Error
	return err
}

func FindDiagnoseById(id int64) (*models.HisXtDiagnoseConfig, error) {
	dealer := &models.HisXtDiagnoseConfig{}
	err := readDb.Model(&models.HisXtDiagnoseConfig{}).Where("id = ? AND status = 1", id).First(&dealer).Error
	return dealer, err
}

func GetDoseCode(dose_id int64, user_org_id int64) (error, string) {
	var data models.DictDataconfig
	err := readDb.Model(&models.DictDataconfig{}).Where(" (user_org_id = ? Or user_org_id = 0) AND parent_id = 4 AND module = 'system' AND status = 1 AND value = ?", user_org_id, dose_id).First(&data).Error
	return err, data.Code
}

func GetAllDrugList(orgid int64) (drug []*models.BaseDrugLib, err error) {

	err = XTReadDB().Model(&drug).Where("org_id = ? and status = 1", orgid).Find(&drug).Error
	return drug, err
}
