package models

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

type CygxActivitySignupDetail struct {
	Id                    int       `orm:"column(id);pk"`
	ActivityId            int       `description:"活动ID"`
	UserId                int       `description:"用户ID"`
	CreateTime            time.Time `description:"创建时间"`
	Mobile                string    `description:"手机号"`
	Email                 string    `description:"邮箱"`
	CompanyId             int       `description:"公司id"`
	CompanyName           string    `description:"公司名称"`
	FailType              int       `description:"失败原因，0，未失败，1总人数已满，2单机构超限制，3，爽约次数超限"`
	SignupType            int       `description:"报名方式，1预约外呼，2自主拨入，3我要报名"`
	DoFailType            int       `description:"失败原因，0，未失败，1总人数已满，2单机构超限制，3，爽约次数超限"`
	OutboundMobile        string    `description:"外呼手机号"`
	CountryCode           string    `description:"手机国家区号"`
	RealName              string    `description:"用户实际名称"`
	SellerName            string    `description:"所属销售"`
	FirstMeetingTime      string    `description:"首次入会时间"`
	LastMeetingTime       string    `description:"最后退出时间"`
	Duration              string    `description:"参会时长"`
	MeetingTypeStr        string    `description:"参会方式"`
	MeetingAuthentication string    `description:"参会权鉴"`
	MeetingStatusStr      string    `description:"参会状态"`
	Position              string    `description:"职位"`
	IsMeeting             int       `description:"是否到会，1到会，0未到会"`
	UseridEntity          int       `description:"参会者身份. 1:主讲人, 2:主持人, 3:嘉宾, 4:普通参会者, 5:联席主讲人, 6:会议助理"`
	ActivityTime          string    `description:"活动时间"`
	CrmCompanyMapStatusId int       `description:"转换后的对应状态信息：1=正式客户, 2=曾使用客户, 3=其他"`
}

// 获取当天已结束的活动
func GetActivitySattusToComplete() (items []*CygxActivity, err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("修改活动状态至已结束"+err.Error(), 2)
		}
	}()
	o := orm.NewOrm()
	//resultTime_30 := time.Now().Add(-time.Minute * 30).Format(utils.FormatDateTime)
	//resultTime_60 := time.Now().Add(-time.Minute * 60).Format(utils.FormatDateTime)
	startTime := time.Now().Format(utils.FormatDate)
	var condition string
	condition += `  AND  activity_time > '` + startTime + `'`
	//condition += ` AND (activity_type_id IN ( 1, 2, 3, 7 ) AND  activity_time < '` + resultTime_30 + `')`
	//condition += ` OR(activity_type_id IN ( 4, 5, 6 ) AND  activity_time < '` + resultTime_60 + `')`
	//condition += ` OR(activity_type_id IN ( 4, 5, 6 ) AND  activity_time < '` + resultTime_60 + `'  AND  activity_time > '` + startTime + `')`
	sql := " SELECT * FROM cygx_activity   WHERE 1 = 1  AND active_state = 3 " + condition
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取今天报名的用户信息，存入到参会记录表中
func GetSignupDetailBySignup(condition string, pars []interface{}) (list []*CygxActivitySignupDetail, err error) {
	sql := `SELECT * FROM cygx_activity_signup  WHERE  1= 1 `
	if condition != "" {
		sql += condition
	}
	_, err = orm.NewOrm().Raw(sql, pars).QueryRows(&list)
	return
}

type CygxActivitySignupDetailServreBill struct {
	Id                  int    `orm:"column(id);pk"`
	ActivityId          int    `description:"活动ID"`
	ActivityName        string `description:"活动名称"`
	UserId              int    `description:"用户ID"`
	RealName            string `description:"用户实际名称"`
	Mobile              string `description:"手机号"`
	Email               string `description:"邮箱"`
	CompanyId           int    `description:"公司id"`
	CompanyName         string `description:"公司名称"`
	ActivityTime        string `description:"活动时间"`
	ActivityType        int    `description:"1线上，其余线下"`
	ChartPermissionId   int    `description:"行业id"`
	ChartPermissionName string `description:"行业名称"`
}

// 获取今天报名的用户信息，存入到参会记录表中
func GetSignupDetailBySignupjoinactivity(condition string, pars []interface{}) (list []*CygxActivitySignupDetailServreBill, err error) {
	sql := `SELECT
			art.activity_id,
			art.user_id,
			art.real_name,
			art.mobile,
			art.email,
			art.company_id,
			art.company_name,
			a.activity_time,
			a.activity_name,
			a.chart_permission_id,
			a.chart_permission_name,
			t.activity_type 
		FROM
			cygx_activity_signup_detail AS art
			INNER JOIN cygx_activity AS a ON a.activity_id = art.activity_id
			INNER JOIN cygx_activity_type AS t ON t.activity_type_id = a.activity_type_id 
		WHERE
			1 = 1  `
	if condition != "" {
		sql += condition
	}
	_, err = orm.NewOrm().Raw(sql, pars).QueryRows(&list)
	return
}

// 获取参会记录表列表
func GetSignupDetailList(condition string, pars []interface{}) (list []*CygxActivitySignupDetail, err error) {
	sql := `SELECT * FROM cygx_activity_signup_detail  WHERE  1= 1 `
	if condition != "" {
		sql += condition
	}
	_, err = orm.NewOrm().Raw(sql, pars).QueryRows(&list)
	return
}

// 添加
func AddCygxActivitySignupDetail(items []*CygxActivitySignupDetail) (err error) {
	o, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}
	defer func() {
		if err == nil {
			o.Commit()
		} else {
			o.Rollback()
		}
	}()
	if len(items) > 0 {
		//批量添加
		_, err = o.InsertMulti(len(items), items)
		if err != nil {
			return err
		}
	}
	return
}

// UpdateActivitySignupDetailMulti 批量修改用户报名信息且报名的人
func UpdateActivitySignupDetailMulti(items []*CygxActivitySignupDetail) (err error) {
	o := orm.NewOrm()
	p, err := o.Raw(` UPDATE cygx_activity_signup_detail SET 
							first_meeting_time = ?,
							last_meeting_time = ?,
							duration = ?,
							meeting_type_str = ?,
							meeting_authentication = ?,
							meeting_status_str = ?,
							position = ?,
							is_meeting = ?,
							userid_entity = ?,
							activity_time = ?,
							crm_company_map_status_id = ?
							WHERE mobile = ? AND activity_id = ? `).Prepare()
	if err != nil {
		return
	}
	defer func() {
		_ = p.Close() // 别忘记关闭 statement
	}()
	for _, v := range items {
		_, err = p.Exec(
			v.FirstMeetingTime,
			v.LastMeetingTime,
			v.Duration,
			v.MeetingTypeStr,
			v.MeetingAuthentication,
			v.MeetingStatusStr,
			v.Position,
			v.IsMeeting,
			v.UseridEntity,
			v.ActivityTime,
			v.CrmCompanyMapStatusId,
			v.Mobile, v.ActivityId)
		if err != nil {
			return
		}
	}
	return
}

// UpdateActivitySignupDetailMultiByYiDong 易董批量修改用户报名信息且报名的人
func UpdateActivitySignupDetailMultiByYiDong(items []*CygxActivitySignupDetail) (err error) {
	o := orm.NewOrm()
	p, err := o.Raw(` UPDATE cygx_activity_signup_detail SET 
							first_meeting_time = ?,
							last_meeting_time = ?,
							meeting_status_str = ?,
							position = ?,
							real_name = ?,
							duration = ?,
							is_meeting = ?
							WHERE mobile = ? AND activity_id = ? `).Prepare()
	if err != nil {
		return
	}
	defer func() {
		_ = p.Close() // 别忘记关闭 statement
	}()
	for _, v := range items {
		_, err = p.Exec(
			v.FirstMeetingTime,
			v.LastMeetingTime,
			v.MeetingStatusStr,
			v.Position,
			v.RealName,
			v.Duration,
			v.IsMeeting,
			v.Mobile, v.ActivityId)
		if err != nil {
			return
		}
	}
	return
}

// UpdateActivitySignupDetailMultiByYiDong 易董批量修改用户报名信息且报名的人
func UpdateActivitySignupDetailMultiMobileAndUserId(items []*CygxActivitySignupDetail) (err error) {
	o := orm.NewOrm()
	p, err := o.Raw(` UPDATE cygx_activity_signup_detail SET
							user_id = ?
							WHERE mobile = ? AND user_id = 0 `).Prepare()
	if err != nil {
		return
	}
	defer func() {
		_ = p.Close() // 别忘记关闭 statement
	}()
	for _, v := range items {
		fmt.Println(v.Mobile)
		_, err = p.Exec(
			v.UserId,
			v.Mobile)
		if err != nil {
			return
		}
	}
	return
}

// UpdateActivitySignupDetailMulti 批量修改用户报名信息且报名的人
func UpdateActivitySignupDetailMultiUserId(items []*CygxActivitySignupDetail) (err error) {
	o := orm.NewOrm()
	p, err := o.Raw(` UPDATE cygx_activity_signup_detail SET 
							user_id = ?
							WHERE mobile = ?  `).Prepare()
	if err != nil {
		return
	}
	defer func() {
		_ = p.Close() // 别忘记关闭 statement
	}()
	for _, v := range items {
		_, err = p.Exec(
			v.UserId,
			v.Mobile)
		if err != nil {
			return
		}
	}
	return
}
