package models

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

type CygxActivityAttendanceDetail 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"`
	SellerName            string    `description:"销售姓名"`
	FirstMeetingTime      string    `description:"首次入会时间"`
	LastMeetingTime       string    `description:"最后退出时间"`
	Duration              string    `description:"参会时长"`
	MeetingTypeStr        string    `description:"参会方式"`
	MeetingAuthentication string    `description:"参会权鉴"`
	MeetingStatusStr      string    `description:"参会状态"`
	CreateTime            time.Time `description:"创建时间"`
	Position              string    `description:"职位"`
	IsMeetingStr          int       `description:"是否到会，1到会，0未到会"`
	UseridEntity          int       `description:"参会者身份. 1:主讲人, 2:主持人, 3:嘉宾, 4:普通参会者, 5:联席主讲人, 6:会议助理"`
	ActivityTime          string    `description:"活动时间"`
	CrmCompanyMapStatusId int       `description:"转换后的对应状态信息：1=正式客户, 2=曾使用客户, 3=其他"`
}

// 添加会议提醒信息
func AddCygxActivityAttendanceDetail(item *CygxActivityAttendanceDetail) (lastId int64, err error) {
	o, err := orm.NewOrm().Begin()
	defer func() {
		fmt.Println(err)
		if err == nil {
			o.Commit()
		} else {
			o.Rollback()
		}
	}()
	var count int
	var countMySchedule int
	sql := `SELECT COUNT(1) AS count FROM cygx_my_schedule WHERE user_id=? AND activity_id=? `
	err = o.Raw(sql, item, item.ActivityId).QueryRow(&countMySchedule)
	if err != nil {
		return
	}
	if countMySchedule == 0 {
		itemMy := new(CygxMySchedule)
		itemMy.ActivityId = item.ActivityId
		itemMy.CreateTime = time.Now()
		itemMy.Mobile = item.Mobile

		itemMy.CompanyId = item.CompanyId
		itemMy.CompanyName = item.CompanyName
		lastId, err = o.Insert(itemMy)
		if err != nil {
			return
		}
	}
	sql = `SELECT COUNT(1) AS count FROM cygx_activity_meeting_reminder WHERE user_id=? AND activity_id=? `
	err = o.Raw(sql, item, item.ActivityId).QueryRow(&count)
	if err != nil {
		return
	}
	if count > 0 {
		sql := `UPDATE cygx_activity_meeting_reminder SET is_cancel = 0  WHERE user_id=?  AND activity_id=? `
		_, err = o.Raw(sql, item, item.ActivityId).Exec()
	} else {
		lastId, err = o.Insert(item)
	}
	itemLog := new(CygxActivityMeetingReminderLog)
	//itemLog.UserId = item.UserId
	itemLog.ActivityId = item.ActivityId
	itemLog.CreateTime = time.Now()
	itemLog.Mobile = item.Mobile
	//itemLog.Email = item.Email
	itemLog.CompanyId = item.CompanyId
	itemLog.CompanyName = item.CompanyName
	itemLog.Type = 1
	lastId, err = o.Insert(itemLog)
	return
}

func AddAttendancDetail(items []*CygxActivityAttendanceDetail, activityId int, mobileStr string) (err error) {
	if len(items) == 0 {
		return
	}
	o := orm.NewOrm()
	//修改活动是否上传到会信息字段
	sql := `UPDATE cygx_activity SET  is_submit_meeting=1   WHERE activity_id=? `
	_, err = o.Raw(sql, activityId).Exec()
	if err != nil {
		return
	}
	//修改单个报名信息是否到会
	sql = `UPDATE cygx_activity_signup SET  is_meeting=0   WHERE activity_id=? `
	_, err = o.Raw(sql, activityId).Exec()
	if err != nil {
		return
	}
	sql = `UPDATE cygx_activity_signup SET  is_meeting=1   WHERE  activity_id=? AND ( outbound_mobile IN (` + mobileStr + `)  OR mobile IN (` + mobileStr + `) )`
	_, err = o.Raw(sql, activityId).Exec()
	if err != nil {
		return
	}
	//二次上传时删除原有数据
	sql = ` DELETE FROM cygx_activity_attendance_detail WHERE activity_id = ?`
	_, err = o.Raw(sql, activityId).Exec()
	if err != nil {
		return
	}

	//
	////插入提交信息
	//for _, v := range items {
	//	_, err = o.Insert(v)
	//	if err != nil {
	//		return
	//	}
	//}
	_, err = o.InsertMulti(len(items), items)
	return
}

// 获取用户参会列表
func GetRoadshowDataList(title, findStartDate, findEndDate string) (list []*RoadshowData, err error) {
	o := orm.NewOrmUsingDB("comein_data")
	sql := `SELECT * FROM roadshow_data WHERE roadshow_title LIKE '%` + title + `%' AND  roadshow_begin_time >= '` + findStartDate + `' AND roadshow_begin_time <= '` + findEndDate + `'`
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

// 获取这个时段内的进门财经参会活动
func GetRoadshowDataListByDateTime(findStartDate, findEndDate string) (list []*RoadshowData, err error) {
	o := orm.NewOrmUsingDB("comein_data")
	sql := `SELECT * FROM roadshow_data WHERE   roadshow_begin_time >= '` + findStartDate + `' AND roadshow_begin_time <= '` + findEndDate + `'   GROUP BY roadshow_title `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

type WxUserOutboundMobile struct {
	RealName       string `description:"姓名"`
	Mobile         string `description:"手机号"`
	OutboundMobile string `description:"外呼手机号"`
	CompanyId      int    `description:"公司ID"`
	CompanyName    string `description:"公司名称"`
	SellerName     string `description:"所属销售"`
}

func GetWxUserOutboundMobile(mobileStr string) (item []*WxUserOutboundMobile, err error) {
	o := orm.NewOrmUsingDB("weekly_report")
	sql := `SELECT u.real_name,u.mobile,u.outbound_mobile,u.company_id,p.company_name ,GROUP_CONCAT( DISTINCT p.seller_name SEPARATOR '/' ) AS seller_name
			FROM wx_user as u 
			INNER JOIN company_product AS p ON p.company_id = u.company_id 
			WHERE outbound_mobile IN (` + mobileStr + `) OR mobile IN (` + mobileStr + `)  GROUP BY u.user_id`
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

// 我的日程列表
func GetActivityAttendanceDetailList(activityIds string) (items []*CygxActivityAttendanceDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_activity_attendance_detail WHERE activity_id IN (` + activityIds + `) `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 我的日程列表
func GetActivityAttendanceDetailListAll() (items []*CygxActivityAttendanceDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_activity_attendance_detail WHERE  activity_id >= 1000 ORDER BY activity_id  ASC  `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

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

func AddAttendancDetailNew(items []*CygxActivityAttendanceDetail, activityIds []int) (err error) {
	if len(items) == 0 {
		return
	}
	o := orm.NewOrm()
	//修改活动是否上传到会信息字段
	sql := `UPDATE cygx_activity SET  is_submit_meeting=1   WHERE activity_id IN  (` + utils.GetOrmInReplace(len(activityIds)) + `)  `
	_, err = o.Raw(sql, activityIds).Exec()
	if err != nil {
		return
	}
	_, err = o.InsertMulti(len(items), items)
	return
}
