// 统计后台的 service

package service

import (
	"XT_Admin_Api/models"
	"XT_Admin_Api/models/admin_models"
	"database/sql"
	"fmt"
	"github.com/jinzhu/gorm"
	"strings"
)

func GetAdminAccount(account string, password string) (*admin_models.AdminAccount, error) {
	var model admin_models.AdminAccount
	err := readChargeDb.Where("mobile = ? AND password = ? AND status = 1", account, password).First(&model).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}
	return &model, nil
}

// 获取总机构数
func GetTotalOrgCount() (int, error) {
	var count int
	err := readUserDb.Model(&models.Org{}).Where("status <> 0 AND import <> 1").Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

func GetAdminUserSpecialPermission(orgID int64, appID int64, adminUserID int64, permissionType models.SpecialPermissionType) (*models.AdminUserSpecialPermission, error) {
	var record models.AdminUserSpecialPermission
	err := readDb.Model(&models.AdminUserSpecialPermission{}).Where("org_id = ? AND app_id = ? AND admin_user_id = ? AND permission = ? AND status = 1", orgID, appID, adminUserID, permissionType).First(&record).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &record, nil
}

// 获取一段时间内新增病人数量
func GetNewPatientCount(from int64, to int64) (int, error) {
	var count int
	db := readDb.Raw("SELECT COUNT(DISTINCT id_card_no) AS count FROM xt_patients WHERE status > 0 AND created_time >= ? AND created_time <= ?", from, to)
	rows, err := db.Rows()
	defer rows.Close()

	//rows, err := readDb.Raw("SELECT COUNT(DISTINCT id_card_no) AS count FROM xt_patients WHERE status > 0 AND created_time >= ? AND created_time <= ?", from, to).Rows()
	if err != nil {
		return 0, err
	}
	if rows.Next() {
		rows.Scan(&count)
	}
	return count, nil
}

// 获取所有机构病人数量
func GetPatientTotalCount() (int64, error) {

	var count int64
	db := readDb.Raw("SELECT COUNT(DISTINCT id_card_no) AS count FROM xt_patients")
	rows, err := db.Rows()
	defer rows.Close()

	//rows, err := readDb.Raw("SELECT COUNT(DISTINCT id_card_no) AS count FROM xt_patients").Rows()
	if err != nil {
		return 0, err
	}
	if rows.Next() {
		rows.Scan(&count)
	}
	return count, nil

}

// 获取一段时间内的活跃账户数
func GetActiveAdminUserCount(from int64, to int64) (int64, error) {
	var count int64
	db := readUserDb.Raw("SELECT COUNT(DISTINCT admin_user_id) AS count FROM sgj_user_admin_login_log WHERE ctime >= ? AND ctime <= ? AND operate_type = 1 AND app_type = 3", from, to)
	rows, err := db.Rows()
	defer rows.Close()

	//rows, err := readUserDb.Raw("SELECT COUNT(DISTINCT admin_user_id) AS count FROM sgj_user_admin_login_log WHERE ctime >= ? AND ctime <= ? AND operate_type = 1 AND app_type = 3", from, to).Rows()
	if err != nil {
		return 0, err
	}
	if rows.Next() {
		rows.Scan(&count)
	}
	return count, nil
}

// 获取所有机构账户数量
func GetAdminUserTotalCount() (int64, error) {
	var count int64
	db := readUserDb.Raw("SELECT COUNT(DISTINCT admin_user_id) AS count FROM sgj_user_admin_login_log WHERE operate_type = 1 AND app_type = 3")
	rows, err := db.Rows()
	defer rows.Close()

	//rows, err := readUserDb.Raw("SELECT COUNT(DISTINCT admin_user_id) AS count FROM sgj_user_admin_login_log WHERE operate_type = 1 AND app_type = 3").Rows()
	if err != nil {
		return 0, err
	}
	if rows.Next() {
		rows.Scan(&count)
	}
	return count, nil
}

// 获取一段时间内注册的机构数量
func GetRegistedOrgCount(from int64, to int64) (int64, error) {

	var count int64

	err := readUserDb.Model(&models.Org{}).Where("status <> 0 AND ctime >= ? AND ctime <= ? AND  import <> 1", from, to).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

// 获取一段时间内的活跃机构数
func GetActiveOrgCount(from int64, to int64) (int64, error) {
	var org []*Org
	//readUserDb.Raw("Select count(DISTINCT(org_id)) as count, DATE_FORMAT(date(from_unixtime(ctime)) ,'%Y-%m-%d') as times  from sgj_user_admin_login_log log  JOIN  (Select d.user_org_id from (Select new_role.user_org_id from  (Select count(*) as count,org_id as user_org_id from  sgj_users.sgj_user_admin_role role  where  role.`user_type` = 2 OR role.`user_type` = 3 Group by role.org_id) new_role where new_role.count > 2) d  JOIN (Select user_org_id from (Select count(*) as count,user_org_id from sgj_xt.xt_patients  where  status = 1  Group by user_org_id) new_patient where new_patient.count > 3) c On d.user_org_id = c.user_org_id) new_user_org ON new_user_org.user_org_id = log.org_id  where ctime >= ? AND ctime <= ?  Group by log.org_id", from, to).Scan(&org)
	readUserDb.Raw("Select org_id  from sgj_user_admin_login_log log  JOIN  (Select d.user_org_id from (Select new_role.user_org_id from  (Select count(*) as count,org_id as user_org_id from sgj_users.sgj_user_admin_role role  where  role.`user_type` = 2 OR role.`user_type` = 3 Group by role.org_id) new_role where new_role.count > 2) d  JOIN (Select user_org_id from (Select count(*) as count,user_org_id from sgj_xt.xt_patients  where  status = 1  Group by user_org_id) new_patient where new_patient.count > 3) c On d.user_org_id = c.user_org_id) new_user_org ON new_user_org.user_org_id = log.org_id where ctime >= ? AND ctime <= ?   Group by log.org_id", from, to).Scan(&org)
	return int64(len(org)), nil
}

type Org struct {
	OrgId int64
}

// 获取所有活跃机构数
func GetActiveOrgTotalCount() (int64, error) {
	var org []*Org
	readUserDb.Raw("Select org_id  from sgj_user_admin_login_log log  JOIN  (Select d.user_org_id from (Select new_role.user_org_id from  (Select count(*) as count,org_id as user_org_id from sgj_users.sgj_user_admin_role role  where  role.`user_type` = 2 OR role.`user_type` = 3 Group by role.org_id) new_role where new_role.count > 2) d  JOIN (Select user_org_id from (Select count(*) as count,user_org_id from sgj_xt.xt_patients  where  status = 1  Group by user_org_id) new_patient where new_patient.count > 3) c On d.user_org_id = c.user_org_id) new_user_org ON new_user_org.user_org_id = log.org_id  Group by log.org_id").Scan(&org)
	fmt.Println(org)
	return int64(len(org)), nil
}

// 获取昨天的注册机构总量
func GetYesterDayRegistedOrgCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw("select count(id) as count, DATE_FORMAT(date(from_unixtime(ctime)) ,'%Y-%m-%d') as times  from sgj_user_org  where DATE_SUB(CURDATE(), INTERVAL 1 DAY) = date(from_unixtime(sgj_user_org.ctime)) AND sgj_user_org.status = 1 AND sgj_user_org.import <> 1  GROUP BY date(from_unixtime(ctime));").Scan(&weekStatistics).Error
	return
}

// 获取近昨天的的机构活跃总量
func GetYesterDayActiveOrgCount() (weekStatistics []*admin_models.Statistics, err error) {
	db := readUserDb.Raw(" Select count(DISTINCT(org_id)) as count, DATE_FORMAT(date(from_unixtime(ctime)) ,'%Y-%m-%d') as times  from sgj_user_admin_login_log log  JOIN  (Select d.user_org_id from (Select new_role.user_org_id from  (Select count(*) as count,org_id as user_org_id from  sgj_users.sgj_user_admin_role role  where  role.`user_type` = 2 OR role.`user_type` = 3 Group by role.org_id) new_role where new_role.count > 2) d  JOIN (Select user_org_id from (Select count(*) as count,user_org_id from sgj_xt.xt_patients  where  status = 1  Group by user_org_id) new_patient where new_patient.count > 3) c On d.user_org_id = c.user_org_id) new_user_org ON new_user_org.user_org_id = log.org_id  where DATE_SUB(CURDATE(), INTERVAL 1 DAY) = date(from_unixtime(ctime))  Group by date(from_unixtime(ctime))")
	err = db.Scan(&weekStatistics).Error
	return
}

// 获取昨天的的机构活跃账号总量
func GetYesterDayActiveAdminUserCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw("select count(DISTINCT(admin_user_id)) as count, DATE_FORMAT(date(from_unixtime(ctime)) ,'%Y-%m-%d') as times  from sgj_user_admin_login_log  where DATE_SUB(CURDATE(), INTERVAL 1 DAY) = date(from_unixtime(sgj_user_admin_login_log.ctime))  AND operate_type = 1 AND app_type = 3 GROUP BY date(from_unixtime(ctime));").Scan(&weekStatistics).Error
	return
}

// 获取昨天的的机构新增病人总量
func GetYesterDayNewPatientCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readDb.Raw("select count(DISTINCT(id_card_no)) as count, DATE_FORMAT(date(from_unixtime(created_time)) ,'%Y-%m-%d') as times  from xt_patients  where DATE_SUB(CURDATE(), INTERVAL 1 DAY) = date(from_unixtime(created_time)) GROUP BY date(from_unixtime(created_time));").Scan(&weekStatistics).Error
	return
}

// 获取近七天每天的注册机构总量
func GetWeekRegistedOrgCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw("select count(id) as count, DATE_FORMAT(date(from_unixtime(ctime)) ,'%Y-%m-%d') as times  from sgj_user_org  where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(from_unixtime(sgj_user_org.ctime)) AND sgj_user_org.status = 1 AND sgj_user_org.import <> 1 GROUP BY date(from_unixtime(ctime));").Scan(&weekStatistics).Error
	return
}

//func GetWeekActiveOrgCount() (weekStatistics []*admin_models.WeekStatistics, err error) {
//	err = readUserDb.Raw("select count(id) as count, date(from_unixtime(ctime)) as times  from sgj_user_org  where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(from_unixtime(sgj_user_org.ctime)) GROUP BY date(from_unixtime(ctime));").Scan(&weekStatistics).Error
//	return
//}

// 获取近七天每天的机构活跃总量
func GetWeekActiveOrgCount() (weekStatistics []*admin_models.Statistics, err error) {
	//db := readDb.Raw("select count(DISTINCT(user_org_id)) as count, DATE_FORMAT(date(from_unixtime(created_time)) ,'%Y-%m-%d') as times  from  xt_dialysis_order   where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(from_unixtime(created_time)) AND status = 1 GROUP BY date(from_unixtime(created_time));")
	db := readUserDb.Raw(" Select count(DISTINCT(org_id)) as count, DATE_FORMAT(date(from_unixtime(ctime)) ,'%Y-%m-%d') as times  from sgj_user_admin_login_log log  JOIN  (Select d.user_org_id from (Select new_role.user_org_id from  (Select count(*) as count,org_id as user_org_id from  sgj_users.sgj_user_admin_role role  where  role.`user_type` = 2 OR role.`user_type` = 3 Group by role.org_id) new_role where new_role.count > 2) d  JOIN (Select user_org_id from (Select count(*) as count,user_org_id from sgj_xt.xt_patients  where  status = 1  Group by user_org_id) new_patient where new_patient.count > 3) c On d.user_org_id = c.user_org_id) new_user_org ON new_user_org.user_org_id = log.org_id  where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(from_unixtime(ctime))  Group by date(from_unixtime(ctime))")

	err = db.Scan(&weekStatistics).Error
	return
}

// 获取近七天每天的机构活跃账号总量
func GetWeekActiveAdminUserCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw("select count(DISTINCT(admin_user_id)) as count, DATE_FORMAT(date(from_unixtime(ctime)) ,'%Y-%m-%d') as times  from sgj_user_admin_login_log  where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(from_unixtime(sgj_user_admin_login_log.ctime))  AND operate_type = 1 AND app_type = 3 GROUP BY date(from_unixtime(ctime));").Scan(&weekStatistics).Error
	return
}

// 获取近七天每天的机构新增病人总量
func GetWeekNewPatientCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readDb.Raw("select count(DISTINCT(id_card_no)) as count, DATE_FORMAT(date(from_unixtime(created_time)) ,'%Y-%m-%d') as times  from xt_patients  where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(from_unixtime(created_time)) GROUP BY date(from_unixtime(created_time));").Scan(&weekStatistics).Error
	return
}

// 获取近30天每天的注册机构总量
func GetMonthRegistedOrgCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw("select count(id) as count,DATE_FORMAT(date(from_unixtime(ctime)) ,'%Y-%m-%d') as times  from sgj_user_org  where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(from_unixtime(sgj_user_org.ctime)) AND sgj_user_org.status = 1 AND sgj_user_org.import <> 1 GROUP BY date(from_unixtime(ctime));").Scan(&weekStatistics).Error
	return
}

// 获取近30天每天的机构活跃总量
func GetMonthActiveOrgCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw("Select count(DISTINCT(org_id)) as count, DATE_FORMAT(date(from_unixtime(ctime)) ,'%Y-%m-%d') as times  from sgj_user_admin_login_log log  JOIN  (Select d.user_org_id from (Select new_role.user_org_id from  (Select count(*) as count,org_id as user_org_id from  sgj_users.sgj_user_admin_role role  where  role.`user_type` = 2 OR role.`user_type` = 3 Group by role.org_id) new_role where new_role.count > 2) d  JOIN (Select user_org_id from (Select count(*) as count,user_org_id from sgj_xt.xt_patients  where  status = 1  Group by user_org_id) new_patient where new_patient.count > 3) c On d.user_org_id = c.user_org_id) new_user_org ON new_user_org.user_org_id = log.org_id  where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(from_unixtime(ctime))  Group by date(from_unixtime(ctime))").Scan(&weekStatistics).Error
	return
}

// 获取近30天每天的机构活跃账号总量
func GetMonthActiveAdminUserCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw("select count(DISTINCT(admin_user_id)) as count, DATE_FORMAT(date(from_unixtime(ctime)) ,'%Y-%m-%d')as times  from sgj_user_admin_login_log  where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(from_unixtime(sgj_user_admin_login_log.ctime)) AND sgj_user_admin_login_log.app_type = 3  AND sgj_user_admin_login_log.operate_type = 1 GROUP BY date(from_unixtime(ctime));").Scan(&weekStatistics).Error
	return
}

// 获取近30天每天的机构新增病人总量
func GetMonthNewPatientCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readDb.Raw("select count(DISTINCT(id_card_no)) as count, DATE_FORMAT(date(from_unixtime(created_time)) ,'%Y-%m-%d') as times  from xt_patients  where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(from_unixtime(created_time)) GROUP BY date(from_unixtime(created_time));").Scan(&weekStatistics).Error
	return
}

// 获取近3个月每个月的注册机构总量
func GetThreeMonthRegistedOrgCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw("select DATE_FORMAT(date(from_unixtime(sgj_user_org.ctime)) ,'%Y-%m') as times,count(DISTINCT(id)) as count from sgj_user_org where  DATE_FORMAT(date(from_unixtime(sgj_user_org.ctime)),'%Y-%m')>=DATE_FORMAT(date_sub(curdate(), interval 3 month),'%Y-%m') AND sgj_user_org.status = 1 AND sgj_user_org.import <> 1 group by times").Scan(&weekStatistics).Error
	return
}

// 获取近3个月每个月的机构活跃账号总量
func GetThreeMonthActiveAdminUserCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw("select DATE_FORMAT(date(from_unixtime(sgj_user_admin_login_log.ctime)) ,'%Y-%m') as times,count(DISTINCT(admin_user_id)) as count from sgj_user_admin_login_log where  DATE_FORMAT(date(from_unixtime(sgj_user_admin_login_log.ctime)),'%Y-%m')>=DATE_FORMAT(date_sub(curdate(), interval 3 month),'%Y-%m')  AND sgj_user_admin_login_log.app_type = 3  AND sgj_user_admin_login_log.operate_type = 1 group by times").Scan(&weekStatistics).Error
	return
}

// 获取近3个月每个月的机构活跃总量
func GetThreeMonthActiveOrgCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw(" Select count(DISTINCT(org_id)) as count, DATE_FORMAT(date(from_unixtime(ctime)) ,'%Y-%m') as times  from sgj_user_admin_login_log log  JOIN  (Select d.user_org_id from (Select new_role.user_org_id from  (Select count(*) as count,org_id as user_org_id from  sgj_users.sgj_user_admin_role role  where  role.`user_type` = 2 OR role.`user_type` = 3 Group by role.org_id) new_role where new_role.count > 2) d  JOIN (Select user_org_id from (Select count(*) as count,user_org_id from sgj_xt.xt_patients  where  status = 1  Group by user_org_id) new_patient where new_patient.count > 3) c On d.user_org_id = c.user_org_id) new_user_org ON new_user_org.user_org_id = log.org_id  where  DATE_FORMAT(date(from_unixtime(ctime)),'%Y-%m')>=DATE_FORMAT(date_sub(curdate(), interval 3 month),'%Y-%m') Group by times").Scan(&weekStatistics).Error
	return
}

// 获取近3个月每个月机构新增病人总量
func GetThreeMonthNewPatientCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readDb.Raw("select DATE_FORMAT(date(from_unixtime(xt_patients.created_time)) ,'%Y-%m') as times,count(DISTINCT(id_card_no)) as count from xt_patients where  DATE_FORMAT(date(from_unixtime(xt_patients.created_time)),'%Y-%m')>=DATE_FORMAT(date_sub(curdate(), interval 3 month),'%Y-%m') group by times").Scan(&weekStatistics).Error
	return
}

// 获取近半年每个月的注册机构总量
func GetSixMonthRegistedOrgCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw("select DATE_FORMAT(date(from_unixtime(sgj_user_org.ctime)) ,'%Y-%m') as times,count(DISTINCT(id)) as count from sgj_user_org where  DATE_FORMAT(date(from_unixtime(sgj_user_org.ctime)),'%Y-%m')>=DATE_FORMAT(date_sub(curdate(), interval 6 month),'%Y-%m') AND sgj_user_org.status = 1 AND sgj_user_org.import <> 1 group by times").Scan(&weekStatistics).Error
	return
}

// 获取近半年每个月的机构活跃账号总量
func GetSixMonthActiveAdminUserCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw("select DATE_FORMAT(date(from_unixtime(sgj_user_admin_login_log.ctime)) ,'%Y-%m') as times,count(DISTINCT(admin_user_id)) as count from sgj_user_admin_login_log where  DATE_FORMAT(date(from_unixtime(sgj_user_admin_login_log.ctime)),'%Y-%m')>=DATE_FORMAT(date_sub(curdate(), interval 6 month),'%Y-%m') AND sgj_user_admin_login_log.app_type = 3  AND sgj_user_admin_login_log.operate_type = 1 group by times").Scan(&weekStatistics).Error
	return
}

// 获取近半年每个月的机构活跃总量
func GetSixMonthActiveOrgCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw(" Select count(DISTINCT(org_id)) as count, DATE_FORMAT(date(from_unixtime(ctime)) ,'%Y-%m') as times  from sgj_user_admin_login_log log  JOIN  (Select d.user_org_id from (Select new_role.user_org_id from  (Select count(*) as count,org_id as user_org_id from  sgj_users.sgj_user_admin_role role  where  role.`user_type` = 2 OR role.`user_type` = 3 Group by role.org_id) new_role where new_role.count > 2) d  JOIN (Select user_org_id from (Select count(*) as count,user_org_id from sgj_xt.xt_patients  where  status = 1  Group by user_org_id) new_patient where new_patient.count > 3) c On d.user_org_id = c.user_org_id) new_user_org ON new_user_org.user_org_id = log.org_id  where  DATE_FORMAT(date(from_unixtime(ctime)),'%Y-%m')>=DATE_FORMAT(date_sub(curdate(), interval 6 month),'%Y-%m') Group by times").Scan(&weekStatistics).Error
	return
}

// 获取近半年每个月机构新增病人总量
func GetSixMonthNewPatientCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readDb.Raw("select DATE_FORMAT(date(from_unixtime(xt_patients.created_time)) ,'%Y-%m') as times,count(DISTINCT(id_card_no)) as count from xt_patients where  DATE_FORMAT(date(from_unixtime(xt_patients.created_time)),'%Y-%m')>=DATE_FORMAT(date_sub(curdate(), interval 6 month),'%Y-%m') group by times").Scan(&weekStatistics).Error
	return
}

// 获取近1年每个月的注册机构总量
func GetYearRegistedOrgCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw("select DATE_FORMAT(date(from_unixtime(sgj_user_org.ctime)) ,'%Y-%m') as times,count(DISTINCT(id)) as count from sgj_user_org where  DATE_FORMAT(date(from_unixtime(sgj_user_org.ctime)),'%Y-%m')>=DATE_FORMAT(date_sub(curdate(), interval 12 month),'%Y-%m') AND sgj_user_org.status = 1 AND sgj_user_org.import <> 1 group by times").Scan(&weekStatistics).Error
	return
}

// 获取近1年每个月的机构活跃账号总量
func GetYearActiveAdminUserCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw("select DATE_FORMAT(date(from_unixtime(sgj_user_admin_login_log.ctime)) ,'%Y-%m') as times,count(DISTINCT(admin_user_id)) as count from sgj_user_admin_login_log where  DATE_FORMAT(date(from_unixtime(sgj_user_admin_login_log.ctime)),'%Y-%m')>=DATE_FORMAT(date_sub(curdate(), interval 12 month),'%Y-%m') AND sgj_user_admin_login_log.app_type = 3  AND sgj_user_admin_login_log.operate_type = 1 group by times").Scan(&weekStatistics).Error
	return
}

// 获取近1年每个月的机构活跃总量
func GetYearActiveOrgCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readUserDb.Raw(" Select count(DISTINCT(org_id)) as count, DATE_FORMAT(date(from_unixtime(ctime)) ,'%Y-%m') as times  from sgj_user_admin_login_log log  JOIN  (Select d.user_org_id from (Select new_role.user_org_id from  (Select count(*) as count,org_id as user_org_id from  sgj_users.sgj_user_admin_role role  where  role.`user_type` = 2 OR role.`user_type` = 3 Group by role.org_id) new_role where new_role.count > 2) d  JOIN (Select user_org_id from (Select count(*) as count,user_org_id from sgj_xt.xt_patients  where  status = 1  Group by user_org_id) new_patient where new_patient.count > 3) c On d.user_org_id = c.user_org_id) new_user_org ON new_user_org.user_org_id = log.org_id  where  DATE_FORMAT(date(from_unixtime(ctime)),'%Y-%m')>=DATE_FORMAT(date_sub(curdate(), interval 12 month),'%Y-%m') Group by times").Scan(&weekStatistics).Error
	return
}

// 获取近1年每个月机构新增病人总量
func GetYearNewPatientCount() (weekStatistics []*admin_models.Statistics, err error) {
	err = readDb.Raw("select DATE_FORMAT(date(from_unixtime(xt_patients.created_time)) ,'%Y-%m') as times,count(DISTINCT(id_card_no)) as count from xt_patients where  DATE_FORMAT(date(from_unixtime(xt_patients.created_time)),'%Y-%m')>=DATE_FORMAT(date_sub(curdate(), interval 12 month),'%Y-%m') AND status > 0 group by times").Scan(&weekStatistics).Error
	return
}

//func GetAllAdmin() (admin []*admin_models.AdminAccount, err error) {
//	err = readChargeDb.Model(&admin_models.AdminAccount{}).Where("is_admin <> 1 AND (status = 1 OR status = 2)").Find(&admin).Error
//	return
//}

func GetAllAdmin() (admin []*admin_models.AdminAccount, err error) {
	err = readChargeDb.Model(&admin_models.AdminAccount{}).Where("is_admin <> 1 AND (status = 1 OR status = 2)").Find(&admin).Error
	return
}

func CreateAdmin(admin *admin_models.AdminAccount) (err error) {
	err = readChargeDb.Model(&admin_models.AdminAccount{}).Create(&admin).Error
	return
}

func FindUserInfoByAccount(account string) (admin admin_models.AdminAccount, err error) {
	err = readChargeDb.Model(&admin_models.AdminAccount{}).Where("mobile = ? AND status = 1", account).First(&admin).Error
	return
}

func FindAdminById(id int64) (admin admin_models.AdminAccount, err error) {
	err = readChargeDb.Model(&admin_models.AdminAccount{}).Where("id = ?", id).First(&admin).Error
	return
}

func UpdateAdmin(admin *admin_models.AdminAccount) (err error) {
	err = readChargeDb.Model(&admin_models.AdminAccount{}).Save(&admin).Error
	return
}

func DeleteAdmin(id int64) (err error) {
	err = readChargeDb.Model(&admin_models.AdminAccount{}).Where("id = ?", id).Updates(map[string]interface{}{"status": 0}).Error
	//err = readChargeDb.Model(&models.OrgFollow{}).Where("admin_user_id = ?", id).Updates(map[string]interface{}{"status": 0}).Error

	return

}

func UpdateAdminTwo(id int64) (err error) {
	err = readChargeDb.Model(&admin_models.AdminAccount{}).Where("id = ?", id).Updates(map[string]interface{}{"status": 1}).Error
	//err = readChargeDb.Model(&models.OrgFollow{}).Where("admin_user_id = ?", id).Updates(map[string]interface{}{"status": 0}).Error

	return

}

func FindAllOrg() (org []*models.Org, err error) {
	err = readUserDb.Select("id, org_name").Where("status = 1").Find(&org).Error

	return
}

type FollowViewModel struct {
	models.OrgFollow
	OrgName string `gorm:"column:org_name" json:"org_name"`
}

func FindFollowOrg(admin_id int64) ([]*FollowViewModel, error) {
	var vms []*FollowViewModel = make([]*FollowViewModel, 0)
	rows, err := readUserDb.Raw("SELECT follow.*, org.org_name as org_name FROM sgj_org_follow as follow join sgj_user_org as org on org.id = follow.org_id  WHERE (follow.admin_user_id = ? AND follow.status = 1)", admin_id).Rows()
	defer rows.Close()
	if err != nil {
		return nil, err
	}
	for rows.Next() {
		var vm FollowViewModel
		readDb.ScanRows(rows, &vm)
		vms = append(vms, &vm)
	}
	fmt.Println(vms)
	return vms, nil
}

type OrgViewModel struct {
	Id      int64  `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"` // 机构 ID
	OrgName string `gorm:"column:org_name" json:"org_name"`
}

func FindUnFollowOrgByIds(id int64) (orgViewModel []*OrgViewModel, err error) {
	err = readUserDb.Raw("Select id, org_name From  sgj_user_org  Where NOT EXISTS (Select id, org_name FROM sgj_org_follow Where sgj_org_follow.org_id = sgj_user_org.id AND sgj_org_follow.admin_user_id = ? AND sgj_org_follow.status = 1)", id).Scan(&orgViewModel).Error
	return

}

func CreateFollowInfo(Follows []*models.OrgFollow) (err error) {
	if len(Follows) > 0 {
		utx := writeUserDb.Begin()
		if len(Follows) > 0 {
			thisSQL := "INSERT INTO sgj_org_follow (org_id,admin_user_id,ctime,mtime,status) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, info := range Follows {
				insertParams = append(insertParams, "(?,?,?,?,?)")
				insertData = append(insertData, info.OrgId)
				insertData = append(insertData, info.AdminUserId)
				insertData = append(insertData, info.Ctime)
				insertData = append(insertData, info.Mtime)
				insertData = append(insertData, info.Status)
			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return

}

func UpdateFollow(follow *models.OrgFollow) (err error) {
	err = readUserDb.Model(&models.OrgFollow{}).Save(follow).Error
	return
}

func FindFollowRecordByID(follow *models.OrgFollow) (info models.OrgFollow, err error) {
	err = readUserDb.Model(&models.OrgFollow{}).Where("org_id = ? AND admin_user_id = ?", follow.OrgId, follow.AdminUserId).First(&info).Error
	return
}

func FindFollowInfoById(org_id int64, admin_user_id int64) (info models.OrgFollow, err error) {
	err = readUserDb.Model(&models.OrgFollow{}).Where("org_id = ? AND status = 1 AND admin_user_id = ?", org_id, admin_user_id).First(&info).Error
	return
}

func GetAllWaitFollowOrgList(keyword string, page int64, limit int64, id int64) (orgViewModel []*OrgViewModel, err error, total int64) {
	type Total struct {
		Count int64
	}
	var totals Total
	offset := (page - 1) * limit
	db := readUserDb
	if len(keyword) > 0 {
		likeKey := "%" + keyword + "%"
		err = db.Raw("Select id, org_name From  sgj_user_org  Where NOT EXISTS (Select id, org_name FROM sgj_org_follow Where sgj_org_follow.org_id = sgj_user_org.id AND sgj_org_follow.admin_user_id = ? AND sgj_org_follow.status = 1 ) AND import <> 1 AND (sgj_user_org.org_name Like ? OR sgj_user_org.org_short_name Like ?) AND status = 1 ORDER BY sgj_user_org.ctime DESC", id, likeKey, likeKey).Offset(offset).Limit(limit).Scan(&orgViewModel).Error
		readUserDb.Raw("Select count(id) as count From  sgj_user_org  Where NOT EXISTS (Select id, org_name FROM sgj_org_follow Where sgj_org_follow.org_id = sgj_user_org.id AND sgj_org_follow.admin_user_id = ? AND sgj_org_follow.status = 1)  AND import <> 1 AND (sgj_user_org.org_name Like ? OR sgj_user_org.org_short_name Like ?) AND status = 1", id, likeKey, likeKey).Scan(&totals)

	} else {
		db = db.Raw("Select id, org_name From  sgj_user_org  Where NOT EXISTS (Select id, org_name FROM sgj_org_follow Where sgj_org_follow.org_id = sgj_user_org.id AND sgj_org_follow.admin_user_id = ? AND sgj_org_follow.status = 1)  AND import <> 1 AND status = 1 ORDER BY sgj_user_org.ctime DESC", id)
		err = db.Offset(offset).Limit(limit).Scan(&orgViewModel).Error
		readUserDb.Raw("Select count(id) as count From  sgj_user_org  Where NOT EXISTS (Select id, org_name FROM sgj_org_follow Where sgj_org_follow.org_id = sgj_user_org.id AND sgj_org_follow.admin_user_id = ? AND sgj_org_follow.status = 1)  AND import <> 1 AND status = 1", id).Scan(&totals)

	}

	return orgViewModel, err, totals.Count
}

func FindAllFollowOrg(keyword string, page int64, limit int64, admin_id int64) (follow []*FollowViewModel, err error, total int64) {
	type Total struct {
		Count int64
	}
	var totals Total

	offset := (page - 1) * limit

	if len(keyword) > 0 {
		var vms []*FollowViewModel = make([]*FollowViewModel, 0)
		var rows *sql.Rows
		var errs error
		likeKey := "%" + keyword + "%"
		rows, errs = readUserDb.Raw("SELECT follow.*, org.org_name as org_name, org.ctime as time FROM sgj_org_follow as follow join sgj_user_org as org on org.id = follow.org_id AND (org.org_name Like ? OR org.org_short_name Like ?) AND org.import <> 1 AND org.status = 1  WHERE (follow.admin_user_id = ? AND follow.status = 1) ORDER BY time DESC", likeKey, likeKey, admin_id).Offset(offset).Limit(limit).Rows()
		readUserDb.Raw("SELECT count(follow.id) as count FROM sgj_org_follow as follow join sgj_user_org as org on org.id = follow.org_id AND (org.org_name Like ? OR org.org_short_name Like ?) AND org.import <> 1 AND org.status = 1  WHERE follow.admin_user_id = ? AND follow.status = 1", likeKey, likeKey, admin_id).Scan(&totals)

		defer rows.Close()
		if errs != nil {
			return nil, errs, totals.Count
		}
		for rows.Next() {
			var vm FollowViewModel
			readDb.ScanRows(rows, &vm)
			vms = append(vms, &vm)
		}

		return vms, nil, totals.Count
	} else {
		var vms []*FollowViewModel = make([]*FollowViewModel, 0)
		var rows *sql.Rows
		var errs error
		rows, errs = readUserDb.Raw("SELECT follow.*, org.org_name as org_name, org.ctime as time FROM sgj_org_follow as follow join sgj_user_org as org on org.id = follow.org_id   AND org.import <> 1  AND org.status = 1 WHERE follow.admin_user_id = ? AND follow.status = 1 ORDER BY time DESC", admin_id).Offset(offset).Limit(limit).Rows()
		readUserDb.Raw("SELECT count(follow.id) as count FROM sgj_org_follow as follow join sgj_user_org as org on org.id = follow.org_id  AND org.import <> 1 AND org.status = 1  WHERE follow.admin_user_id = ? AND follow.status = 1", admin_id).Scan(&totals)

		defer rows.Close()
		if errs != nil {
			return nil, errs, totals.Count
		}
		for rows.Next() {
			var vm FollowViewModel
			readDb.ScanRows(rows, &vm)
			vms = append(vms, &vm)
		}

		return vms, nil, totals.Count
	}

}

// 获取累积客户数
func GetCustomCount() (int64, error) {
	var count int64
	err := readUserDb.Model(&models.KyyChargeCustom{}).Where("status = 1").Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

// 本年新增收费客户
func GetCurYearCustomCount() (int64, error) {
	var count int64
	err := readUserDb.Model(&models.KyyChargeCustom{}).Where("status = 1 and YEAR(FROM_UNIXTIME(ctime)) = YEAR(CURDATE())").Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

// 统计本年新增标准版客户
func GetCurYearStandCustomCount() (int64, error) {
	var count int64
	err := readUserDb.Model(&models.KyyChargeCustom{}).Where("status = 1 and YEAR(FROM_UNIXTIME(ctime)) = YEAR(CURDATE()) and custom_type = 1").Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

// 统计本年新增尊享版客户
func GetCurYearDeluxeCustomCount() (int64, error) {
	var count int64
	err := readUserDb.Model(&models.KyyChargeCustom{}).Where("status = 1 and YEAR(FROM_UNIXTIME(ctime)) = YEAR(CURDATE()) and custom_type = 2").Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

// 统计本年新增专业版客户
func GetCurYearProfessionalCustomCount() (int64, error) {
	var count int64
	err := readUserDb.Model(&models.KyyChargeCustom{}).Where("status = 1 and YEAR(FROM_UNIXTIME(ctime)) = YEAR(CURDATE()) and custom_type = 3").Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

// 统计本年新增其他版客户
func GetCurYearOtherCustomCount() (int64, error) {
	var count int64
	err := readUserDb.Model(&models.KyyChargeCustom{}).Where("status = 1 and YEAR(FROM_UNIXTIME(ctime)) = YEAR(CURDATE()) and custom_type = 4").Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

func GetCurYearContractPriceCount() (float64, error) {
	var count float64
	err := readUserDb.Model(&models.KyyChargeContract{}).Select("sum(sumamt) as count").Where("status = 1 and YEAR(FROM_UNIXTIME(ctime)) = YEAR(CURDATE())").Find(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

func GetCurYearSoftwarePriceCount() (float64, error) {
	var count float64
	err := readUserDb.Model(&models.KyyChargeContract{}).Select("sum(software_price) as count").Where("status = 1 and YEAR(FROM_UNIXTIME(ctime)) = YEAR(CURDATE())").Find(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

func GetCurYearHardwarePriceCount() (float64, error) {
	var count float64
	err := readUserDb.Model(&models.KyyChargeContract{}).Select("sum(hardware_price) as count").Where("status = 1 and YEAR(FROM_UNIXTIME(ctime)) = YEAR(CURDATE())").Find(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

func GetCurYearPaymentCollectionSumamtPriceCount() (float64, error) {
	var count float64
	err := readUserDb.Model(&models.KyyChargeContract{}).Select("sum(payment_collection_sumamt) as count").Where("status = 1 and YEAR(FROM_UNIXTIME(ctime)) = YEAR(CURDATE())").Find(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

func GetCurYearPaymentCollectionSoftwarePriceCount() (float64, error) {
	var count float64
	err := readUserDb.Model(&models.KyyChargeContract{}).Select("sum(software_sumamt) as count").Where("status = 1 and YEAR(FROM_UNIXTIME(ctime)) = YEAR(CURDATE())").Find(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

func GetCurYearPaymentCollectionHardwarePriceCount() (float64, error) {
	var count float64
	err := readUserDb.Model(&models.KyyChargeContract{}).Select("sum(hardware_sumamt) as count").Where("status = 1 and YEAR(FROM_UNIXTIME(ctime)) = YEAR(CURDATE())").Find(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}
