package service

import (
	"Xcx_New/models"
	_ "github.com/astaxie/beego"
	_ "strconv"
	_ "strings"
	"time"
)

//GetPatientList 返回患者的列表
func GetConfigList(orgID int64) (dataconfig interface{}, err error) {
	var configList []*models.Dataconfig

	err = readDb.Model(&models.Dataconfig{}).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.Dataconfig)
	resultConfig := make(map[string][]*models.ConfigViewModel)
	deleteSystemChilds := make([]*models.Dataconfig, 0)
	editSystemChilds := make([]*models.Dataconfig, 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.ConfigViewModel{
				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.ConfigViewModel, 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.Dataconfig, 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 FindConfigByFieldname(module string, field_name string, org_id int64) (dataconfig models.Dataconfig, err error) {
	err = readDb.Model(&models.Dataconfig{}).Where("module=? and field_name=? and org_id in (0,?) and status = 1", module, field_name, org_id).First(&dataconfig).Error
	return
}

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

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

func FindConfigByNameForUpdate(module string, name string, parent_id int64, org_id int64, id int64) (dataconfig models.Dataconfig, err error) {
	err = readDb.Model(&models.Dataconfig{}).Where("module=? and name=? and parent_id=? and org_id in (0,?) and id != ? and status = 1", module, name, parent_id, org_id, id).First(&dataconfig).Error
	return
}

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

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

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

func CreateConfig(dataconfig *models.Dataconfig) (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 GetChildValue(module string, parent_id int64, org_id int64) (value int) {
	readDb.Model(&models.Dataconfig{}).Where("module=? and parent_id=? and org_id in (0,?)", module, parent_id, org_id).Count(&value)
	return
}

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

func FindFiledByOrgId(org_id int64) (filedConfig []*models.FiledConfig, err error) {
	err = readDb.Model(&models.FiledConfig{}).Where("org_id =? AND  sys_module = 0", org_id).Find(&filedConfig).Error
	return
}

func FindQualityByOrgId(orgid int64) (xtquality []*models.XtQualityControlStandard, err error) {

	err = readDb.Model(&models.XtQualityControlStandard{}).Where("user_org_id =? and status =1 and is_status = 1", orgid).Find(&xtquality).Error
	return
}

func GetDefaultSystolicPressure(orgid int64) (xtquality []*models.XtQualityControlStandard, err error) {

	err = readDb.Model(&models.XtQualityControlStandard{}).Where("user_org_id = ? and status = 1 and is_status =0", orgid).Find(&xtquality).Error
	return
}

func FindeInspectionByOrgId(orgid int64) (xtquality []*models.XtCheckConfiguration, err error) {

	err = readDb.Model(&models.XtQualityControlStandard{}).Where("user_org_id = ? and status =1", orgid).Find(&xtquality).Error
	return
}

func BatchInsertFiledConfig(org_id int64) (err error) {
	err = readDb.Exec("INSERT  INTO sgj_xt.xt_filed_config  ( org_id,  module,  filed_name,  filed_name_cn,  is_show ) SELECT ?,  module,  filed_name,  filed_name_cn,  is_show FROM sgj_xt.xt_filed_config  WHERE org_id = 0 AND is_show = 1", org_id).Error
	return
}

func BatchInsertQualityControl(org_id int64) (err error) {

	err = readDb.Exec("INSERT INTO xt_quality_control_standard(user_org_id,inspection_major,inspection_minor,min_range,large_range,sort,created_time,status,range_type,range_value,is_status) SELECT ?,inspection_major,inspection_minor,min_range,large_range,sort,created_time,status,range_type,range_value,is_status FROM xt_quality_control_standard where user_org_id = 0 and is_status = 1", org_id).Error
	return
}

func BathInsertQualityControlTwo(org_id int64) (err error) {
	err = readDb.Exec("INSERT INTO xt_quality_control_standard(user_org_id,inspection_major,inspection_minor,min_range,large_range,sort,created_time,status,range_type,range_value,is_status) SELECT ?,inspection_major,inspection_minor,min_range,large_range,sort,created_time,status,range_type,range_value,is_status FROM xt_quality_control_standard where user_org_id = 0 and is_status = 0", org_id).Error
	return
}

func BatchInspectionConfiguration(orgid int64) (err error) {

	err = readDb.Exec("INSERT INTO xt_check_configuration(user_org_id,inspection_major,inspection_frequency,sort,created_time,status) SELECT ?,inspection_major,inspection_frequency,sort,created_time,status FROM xt_check_configuration where user_org_id = 0", orgid).Error
	return
}

func ShowFiledConfig(org_id int64, isShow int, id int64) (err error) {
	err = readDb.Model(&models.FiledConfig{}).Where("org_id = ? AND id = ?", org_id, id).Updates(map[string]interface{}{"ctime": time.Now().Unix(), "mtime": time.Now().Unix(), "is_show": isShow}).Error
	return
}

func FindSysDialysisFiledByOrgId() (filedConfig []*models.FiledConfig, err error) {
	err = readDb.Model(&models.FiledConfig{}).Where("org_id =? AND id in (11250,11251,11252,11253,11254,11255,11256,11257,11258,11259,11260,11261,11262)", 0).Find(&filedConfig).Error
	return
}

func BatchInsertFiledSystemConfig(org_id int64) (err error) {
	err = readDb.Exec("INSERT  INTO sgj_xt.xt_filed_config  ( org_id,  module,  filed_name,  filed_name_cn,  is_show ) SELECT ?,  module,  filed_name,  filed_name_cn,  is_show FROM sgj_xt.xt_filed_config  WHERE org_id = 9442", org_id).Error
	return
}

func BatchInsertDoctorSchedule(orgid int64) (err error) {

	err = readDb.Exec("INSERT INTO sgj_xt.xt_doctor_schedules(user_org_id,class_name,class_attributes,timeone_start,timeone_type,timeone_end,timetwo_start,timetwo_type,timetwo_end,work_time,remarks,status,ctime,minute) SELECT ?, class_name,class_attributes,timeone_start,timeone_type,timeone_end,timetwo_start,timetwo_type,timetwo_end,work_time,remarks,status,ctime,minute FROM xt_doctor_schedules WHERE user_org_id = 0", orgid).Error
	return
}

func CreateContinueSchedule(schedule *models.ContinueSchedule) error {

	err := writeDb.Model(&schedule).Create(&schedule).Error
	return err
}
