package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"hongze/hongze_cygx/utils"
	"strconv"
	"strings"
	"time"
)

// 报名
type CygxActivityMeetDetailLog struct {
	AttendanceId int       `orm:"column(attendance_id);pk;"description:"主键ID"`
	ActivityId   int       `description:"活动ID"`
	RealName     string    `description:"姓名"`
	Mobile       string    `description:"手机号"`
	CompanyName  string    `description:"公司名称"`
	CompanyId    int       `description:"公司id 不在数据库的用户为0"`
	CreateTime   time.Time `description:"创建时间"`
	ActivityTime string    `description:"活动时间"`
}

// 批量添加
func AddCygxActivityMeetDetailLogMulti(items []*CygxActivityMeetDetailLog) (err error) {
	o := orm.NewOrm()
	if len(items) > 0 {
		//批量添加
		_, err = o.InsertMulti(len(items), items)
	}
	return
}

// 列表
func GetCygxActivityMeetDetailLogList(condition string, pars []interface{}) (items []*CygxActivityMeetDetailLog, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_activity_meet_detail_log as art WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func GetOfflineMeetingDetailListCompanyIdStr(companyIdStr string) (item []*CygxActivityMeetDetailLog, err error) {
	if companyIdStr == "" {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_activity_offline_meeting_detail WHERE company_id IN (` + companyIdStr + `)`
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

func GetOfflineMeetingDetailListCompanyName(companyName string) (item []*CygxActivityMeetDetailLog, err error) {
	o := orm.NewOrm()
	sql := `SELECT l.* 
			FROM
			cygx_activity_meet_detail_log AS l INNER JOIN company AS c ON c.company_name = l.company_name 
			WHERE
	l.company_name IN (` + companyName + `)  GROUP BY l.company_name`
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

// 添加
func AddCygxActivityMeetDetailLog(item *CygxActivityMeetDetailLog) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

func GetActivityMeetDetailLog(mobileStr string) (item []*CygxActivityMeetDetailLog, err error) {
	if mobileStr == "" {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT l.* 
			FROM
			cygx_activity_meet_detail_log  as l
			WHERE l.mobile IN (` + mobileStr + `)  GROUP BY l.mobile `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

func GetActivityMeetDetailLogByMobile() (item []*CygxActivityMeetDetailLog, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM  cygx_activity_meet_detail_log WHERE mobile !='' GROUP BY mobile `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

// 获取数量
func GetActivityMeetDetailLogCount(condition string) (count int, err error) {
	o := orm.NewOrm()
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_activity_meet_detail_log WHERE 1=1 `
	if condition != "" {
		sqlCount += condition
	}
	err = o.Raw(sqlCount).QueryRow(&count)
	return
}

// 报名
type CygxActivityMeetDetailLogCountResp struct {
	Mobile    string `description:"手机号"`
	CompanyId int    `description:"公司id 不在数据库的用户为0"`
	Count     int    `description:"公司id 不在数据库的用户为0"`
}

// 获取数量
func GetActivityMeetDetailLogCountCompany(companyIds []int) (item []*CygxActivityMeetDetailLogCountResp, err error) {
	lenArr := len(companyIds)
	if lenArr == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `  SELECT company_id, COUNT(1) AS count  FROM cygx_activity_meet_detail_log WHERE 1=1 AND company_id IN  (` + utils.GetOrmInReplace(lenArr) + `)   GROUP BY company_id`
	_, err = o.Raw(sql, companyIds).QueryRows(&item)
	return
}

// 获取数量
func GetActivityMeetDetailLogCountMobile(mobiles []string) (item []*CygxActivityMeetDetailLogCountResp, err error) {
	lenArr := len(mobiles)
	if lenArr == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `  SELECT mobile, COUNT(1) AS count  FROM cygx_activity_meet_detail_log WHERE 1=1 AND mobile IN  (` + utils.GetOrmInReplace(lenArr) + `)   GROUP BY company_id`
	_, err = o.Raw(sql, mobiles).QueryRows(&item)
	return
}

// 修改公司参会数量
func UpdateActivityMeetDetailLog(companyName string, num int) (err error) {
	sql := ` UPDATE cygx_activity_meet_detail_log SET  company_meet_num= ?  WHERE company_name = ?`
	o := orm.NewOrm()
	_, err = o.Raw(sql, num, companyName).Exec()
	return
}

// 修改个人参会数量
func UpdateActivityMeetDetailLogByUser(mobile string, num int) (err error) {
	sql := ` UPDATE cygx_activity_meet_detail_log SET  user_meet_num= ?  WHERE mobile = ?`
	o := orm.NewOrm()
	_, err = o.Raw(sql, num, mobile).Exec()
	return
}

// 添加线上到会记录(下载使用)
func AddCygxActivityMeetDetailLogOnline(list []*CygxActivityAttendanceDetail, activityId int) (err error) {
	o, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}
	defer func() {
		fmt.Println(err)
		if err == nil {
			o.Commit()
		} else {
			o.Rollback()
		}
	}()
	var CompanyName string
	var MobileStr string
	var items []*CygxActivityMeetDetailLog
	//删除原有数据
	sql := ` DELETE FROM cygx_activity_meet_detail_log WHERE activity_id = ?`
	_, err = o.Raw(sql, activityId).Exec()
	if err != nil {
		return
	}
	//插入新的数据
	for _, v := range list {
		item := new(CygxActivityMeetDetailLog)
		item.ActivityId = v.ActivityId
		item.Mobile = v.Mobile
		item.CompanyName = v.CompanyName
		item.CompanyId = v.CompanyId
		item.CreateTime = v.CreateTime
		CompanyName += "'" + v.CompanyName + "',"
		MobileStr += v.Mobile + ","
		items = append(items, item)
	}
	CompanyName = strings.TrimRight(CompanyName, ",")
	MobileStr = strings.TrimRight(MobileStr, ",")
	_, err = o.InsertMulti(1, items)
	listCompany, err := GetOfflineMeetingDetailListCompanyName(CompanyName)
	if err != nil {
		return
	}
	//修改公司对应的数量
	var condition string
	for _, v := range listCompany {
		var total int
		condition = ` AND company_name = '` + v.CompanyName + `' `
		total, err = GetActivityMeetDetailLogCount(condition)
		if err != nil {
			return
		}
		sql := ` UPDATE cygx_activity_meet_detail_log SET  company_meet_num= ?  WHERE company_name = ?`
		_, err = o.Raw(sql, total, v.CompanyName).Exec()
		if err != nil {
			return
		}
	}
	listMobile, err := GetActivityMeetDetailLog(MobileStr)
	if err != nil {
		return
	}
	//修改个人对应的数量
	for _, v := range listMobile {
		var total int
		condition = ` AND mobile = '` + v.Mobile + `' `
		total, err = GetActivityMeetDetailLogCount(condition)
		if err != nil {
			return
		}
		sql := ` UPDATE cygx_activity_meet_detail_log SET  user_meet_num= ?  WHERE mobile = ?`
		_, err = o.Raw(sql, total, v.Mobile).Exec()
		if err != nil {
			return
		}
	}
	return
}

// 添加线上到会记录
func AddCygxActivityMeetDetailLogOnlineByListNew(list []*CygxActivityAttendanceDetail, activityIds string) (err error) {
	o, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}
	defer func() {
		fmt.Println(err)
		if err == nil {
			o.Commit()
		} else {
			o.Rollback()
		}
	}()
	var CompanyName string
	var MobileStr string
	var items []*CygxActivityMeetDetailLog
	//删除原有数据
	sql := ` DELETE FROM cygx_activity_meet_detail_log WHERE activity_id IN (` + activityIds + `)`
	_, err = o.Raw(sql).Exec()
	if err != nil {
		return
	}
	//插入新的数据
	for _, v := range list {
		item := new(CygxActivityMeetDetailLog)
		item.ActivityId = v.ActivityId
		item.Mobile = v.Mobile
		fmt.Println(v.CompanyName)
		item.CompanyName = v.CompanyName
		item.CompanyId = v.CompanyId
		item.ActivityTime = v.ActivityTime
		item.CreateTime = v.CreateTime
		if strings.Index(CompanyName, v.CompanyName) == -1 && v.CompanyName != "" {
			CompanyName += "'" + v.CompanyName + "',"
		}
		if strings.Index(MobileStr, v.Mobile) == -1 && v.Mobile != "" {
			MobileStr += v.Mobile + ","
		}
		items = append(items, item)
	}
	CompanyName = strings.TrimRight(CompanyName, ",")
	MobileStr = strings.TrimRight(MobileStr, ",")
	_, err = o.InsertMulti(1, items)
	listCompany, err := GetOfflineMeetingDetailListCompanyName(CompanyName)
	fmt.Println("公司数量", len(listCompany))
	if err != nil {
		return
	}
	//修改公司对应的数量
	var condition string
	for _, v := range listCompany {
		var total int
		condition = ` AND company_name = '` + v.CompanyName + `' `
		total, err = GetActivityMeetDetailLogCount(condition)
		if err != nil {
			return
		}
		sql := ` UPDATE cygx_activity_meet_detail_log SET  company_meet_num= ?  WHERE company_name = ?`
		_, err = o.Raw(sql, total, v.CompanyName).Exec()
		fmt.Println("处理公司", v.CompanyName)
		if err != nil {
			return
		}
	}
	listMobile, err := GetActivityMeetDetailLog(MobileStr)
	fmt.Println("用户数量", len(listMobile))
	if err != nil {
		return
	}
	//修改个人对应的数量
	for _, v := range listMobile {
		var total int
		condition = ` AND mobile = '` + v.Mobile + `' `
		total, err = GetActivityMeetDetailLogCount(condition)
		if err != nil {
			return
		}
		sql := ` UPDATE cygx_activity_meet_detail_log SET  user_meet_num= ?  WHERE mobile = ?`
		_, err = o.Raw(sql, total, v.Mobile).Exec()
		fmt.Println("处理用户", v.Mobile)
		if err != nil {
			return
		}
	}
	fmt.Println("user_end")
	return
}

// 添加线下到会记录
func AddCygxActivityMeetDetailLogOffline(activityId int) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	var condition string
	var pars []interface{}
	condition = `  AND activity_id = ? `
	pars = append(pars, activityId)
	listOfflineMeeting, err := GetOfflineMeetingList(condition, pars)
	if err != nil {
		return
	}
	var meetingUids string
	for _, v := range listOfflineMeeting {
		meetingUids += strconv.Itoa(v.UserId) + ","
	}
	meetingUids = strings.TrimRight(meetingUids, ",")
	if meetingUids == "" {
		meetingUids = "-1"
	}
	var CompanyIdStr string
	var MobileStr string
	var items []*CygxActivityMeetDetailLog
	list, err := GetOfflineMeetingListByUser(meetingUids, activityId)
	fmt.Println(len(list))
	if err != nil {
		return
	}
	//删除原有数据
	sql := ` DELETE FROM cygx_activity_meet_detail_log WHERE activity_id = ?`
	_, err = to.Raw(sql, activityId).Exec()
	if err != nil {
		return
	}
	//插入新的数据
	for _, v := range list {
		item := new(CygxActivityMeetDetailLog)
		item.ActivityId = v.ActivityId
		item.Mobile = v.Mobile
		item.CompanyName = v.CompanyName
		item.CompanyId = v.CompanyId
		item.CreateTime = v.CreateTime
		CompanyIdStr += strconv.Itoa(v.CompanyId) + ","
		if v.Mobile != "" {
			MobileStr += v.Mobile + ","
		}
		items = append(items, item)
	}
	CompanyIdStr = strings.TrimRight(CompanyIdStr, ",")
	MobileStr = strings.TrimRight(MobileStr, ",")
	for _, v := range items {
		_, err = to.Insert(v)
		if err != nil {
			return
		}
	}
	listCompanyId, err := GetOfflineMeetingDetailListCompanyIdStr(CompanyIdStr)
	if err != nil {
		return
	}
	//修改公司对应的数量
	//var condition string
	for _, v := range listCompanyId {
		var total int
		condition = ` AND company_name = '` + v.CompanyName + `' `
		total, err = GetActivityMeetDetailLogCount(condition)
		if err != nil {
			return
		}
		sql := ` UPDATE cygx_activity_meet_detail_log SET  company_meet_num= ?  WHERE company_name = ?`
		_, err = to.Raw(sql, total, v.CompanyName).Exec()
		if err != nil {
			return
		}
	}
	listMobile, err := GetActivityMeetDetailLog(MobileStr)
	if err != nil {
		return
	}
	//修改个人对应的数量
	for _, v := range listMobile {
		var total int
		condition = ` AND mobile = '` + v.Mobile + `' `
		total, err = GetActivityMeetDetailLogCount(condition)
		if err != nil {
			return
		}
		sql := ` UPDATE cygx_activity_meet_detail_log SET  user_meet_num= ?  WHERE mobile = ?`
		_, err = to.Raw(sql, total, v.Mobile).Exec()
		if err != nil {
			return
		}
	}
	return
}

// 添加线上到会记录
func AddCygxActivityMeetDetailLogOnlineByList(list []*CygxActivityAttendanceDetail, activityIds string) (err error) {
	o, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}
	defer func() {
		fmt.Println(err)
		if err == nil {
			o.Commit()
		} else {
			o.Rollback()
		}
	}()
	var CompanyName string
	var MobileStr string
	var items []*CygxActivityMeetDetailLog
	//删除原有数据
	sql := ` DELETE FROM cygx_activity_meet_detail_log WHERE activity_id IN (` + activityIds + `)`
	_, err = o.Raw(sql).Exec()
	if err != nil {
		return
	}
	//插入新的数据
	for _, v := range list {
		item := new(CygxActivityMeetDetailLog)
		item.ActivityId = v.ActivityId
		item.Mobile = v.Mobile
		fmt.Println(v.CompanyName)
		item.CompanyName = v.CompanyName
		item.CompanyId = v.CompanyId
		item.ActivityTime = v.ActivityTime
		item.CreateTime = v.CreateTime
		if strings.Index(CompanyName, v.CompanyName) == -1 && v.CompanyName != "" {
			CompanyName += "'" + v.CompanyName + "',"
		}
		if strings.Index(MobileStr, v.Mobile) == -1 && v.Mobile != "" {
			MobileStr += v.Mobile + ","
		}
		items = append(items, item)
	}
	CompanyName = strings.TrimRight(CompanyName, ",")
	MobileStr = strings.TrimRight(MobileStr, ",")
	_, err = o.InsertMulti(1, items)
	listCompany, err := GetOfflineMeetingDetailListCompanyName(CompanyName)
	fmt.Println("公司数量", len(listCompany))
	if err != nil {
		return
	}
	//修改公司对应的数量
	var condition string
	for _, v := range listCompany {
		var total int
		condition = ` AND company_name = '` + v.CompanyName + `' `
		total, err = GetActivityMeetDetailLogCount(condition)
		if err != nil {
			return
		}
		sql := ` UPDATE cygx_activity_meet_detail_log SET  company_meet_num= ?  WHERE company_name = ?`
		_, err = o.Raw(sql, total, v.CompanyName).Exec()
		fmt.Println("处理公司", v.CompanyName)
		if err != nil {
			return
		}
	}
	listMobile, err := GetActivityMeetDetailLog(MobileStr)
	fmt.Println("用户数量", len(listMobile))
	if err != nil {
		return
	}
	//修改个人对应的数量
	for _, v := range listMobile {
		var total int
		condition = ` AND mobile = '` + v.Mobile + `' `
		total, err = GetActivityMeetDetailLogCount(condition)
		if err != nil {
			return
		}
		sql := ` UPDATE cygx_activity_meet_detail_log SET  user_meet_num= ?  WHERE mobile = ?`
		_, err = o.Raw(sql, total, v.Mobile).Exec()
		fmt.Println("处理用户", v.Mobile)
		if err != nil {
			return
		}
	}
	fmt.Println("user_end")
	return
}

// UpdateActivitySpecialSignupNumMulti 批量修改个人参会数量
func UpdateCygxActivityMeetDetailLogMobileNumMulti(items []*CygxActivityMeetDetailLogCountResp) (err error) {
	o := orm.NewOrm()
	p, err := o.Raw("UPDATE cygx_activity_meet_detail_log SET user_meet_num = ? WHERE mobile = ?").Prepare()
	if err != nil {
		return
	}
	defer func() {
		_ = p.Close()
	}()
	for _, v := range items {
		_, err = p.Exec(v.Count, v.Mobile)
		if err != nil {
			return
		}
	}
	return
}

// UpdateActivitySpecialSignupNumMulti 批量修改机构参会数量
func UpdateCygxActivityMeetDetailLogCompanyNumMulti(items []*CygxActivityMeetDetailLogCountResp) (err error) {
	o := orm.NewOrm()
	p, err := o.Raw("UPDATE cygx_activity_meet_detail_log SET company_meet_num = ? WHERE company_id = ?").Prepare()
	if err != nil {
		return
	}
	defer func() {
		_ = p.Close()
	}()
	for _, v := range items {
		_, err = p.Exec(v.Count, v.CompanyId)
		if err != nil {
			return
		}
	}
	return
}
