package cygx

import (
	"hongze/hz_crm_api/utils"

	//"hongze/hz_crm_api/models"
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"time"
)

// 活动详情
type CygxMeetList struct {
	ActivityId                int    `orm:"column(activity_id);pk";description:"活动ID 等于0新增活动，大于0修改活动"`
	ActivityName              string `description:"活动名称"`
	ActivityTypeName          string `description:"活动类型名称"`
	ActivityTypeId            int    `description:"活动类型ID"`
	ChartPermissionName       string `description:"行业名称"`
	ChartPermissionNames      string `description:"行业名称"`
	ActivityTime              string `description:"活动时间"`
	ActivityTimeText          string `description:"活动时间带文字"`
	SignupPeopleNum           int    `description:"报名人数/预约外呼人数"`
	MeetPeopleNum             int    `description:"实际参会人数"`
	PotentialPeopleNum        int    `description:"潜在参会人数"`
	OmeetPeopleNum            int    `description:"实际参会人数(辅助字段不使用)"`
	IsSubmitMeeting           int    `description:"是否提交过到会信息 ，1是，0否"`
	OperationStyle            int    `description:"操作方式，1提交到会情况/上传参会表格，2修改到会详情/重新上传"`
	UpdateTime                string `description:"更新时间"`
	IsCClassMeeting           bool   `description:"是否是c类电话会"`
	SubmitMeetingType         int    `description:"操作展示类型 ，1修改到会详情"`
	IsShowAttendanceDetails   bool   `description:"是否展示到会详情"`
	IsShowHandMovement        bool   `description:"是否展示手动匹配"`
	IsShowSubmitMeeting       bool   `description:"是否展示提交到会情况"`
	IsShowUpdateMeeting       bool   `description:"是否展示修改到会情况"`
	YidongActivityId          string `description:"易董的活动ID"`
	ActivityJoinType          string `description:"易董活动入会类型01报名审核后可入会 02预约即可入会 03仅定向邀请人员可入会"`
	IsYidongConduct           int    `description:"是否属于易董办会 1：是 、0：否"`
	IsShowSigninButton        bool   `description:"是否展示签到码按钮"`
	SigninImg                 string `description:"签到码图片"`
	ChartPermissionNameDeputy string `description:"副行业名称"`
}

type GetCygxMeetListRep struct {
	Paging *paging.PagingItem `description:"分页数据"`
	List   []*CygxMeetList
}

// 获取数量
func GetCygxMeetCount(condition string, pars []interface{}) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_activity as a WHERE 1= 1  `
	if condition != "" {
		sqlCount += condition
	}
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

// 列表
func GetCygxMeetListAll(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxMeetList, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT 
		( SELECT COUNT( 1 ) FROM cygx_activity_signup AS s    WHERE s.activity_id = a.activity_id AND s.is_cancel = 0 AND s.do_fail_type = 0 AND  s.company_id != 16 ) AS signup_people_num,
		( SELECT COUNT( 1 ) FROM cygx_activity_signin AS s   WHERE s.activity_id = a.activity_id AND s.company_id <= 1  ) AS potential_people_num,
	    ( SELECT COUNT( DISTINCT d.mobile  ) FROM cygx_activity_attendance_detail  AS d  WHERE d.activity_id = a.activity_id  AND( is_meeting_str = 1 or d.company_id <= 1) ) AS meet_people_num,
	    ( SELECT COUNT( 1 ) FROM cygx_activity_offline_meeting_detail AS o WHERE o.activity_id = a.activity_id AND is_meeting = 1  ) AS omeet_people_num,
		a.*
		FROM cygx_activity as a
		WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += `   LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

type CygxActivityMeet struct {
	Id          int       `orm:"column(id);pk"description:"ID"`
	UserId      int       `description:"用户id,多个用,隔开"`
	ActivityId  int       `description:"活动ID"`
	CreateTime  time.Time `description:"创建时间"`
	Mobile      string    `description:"手机号"`
	Email       string    `description:"邮箱号"`
	CompanyId   int       `description:"公司ID"`
	CompanyName string    `description:"公司名称"`
	Source      int       `description:"来源，1小程序，2后台添加"`
}

// 报名信息Excel下载
type MeetExportRep struct {
	Mobile      string `description:"手机号"`
	CompanyName string `description:"公司名称"`
	RealName    string `description:"姓名"`
	CountryCode string `description:"区号"`
}

type MeetingDoRep struct {
	Ids        string `description:"报名ID，多个ID用 , 隔开"`
	ActivityId int    `description:"活动ID"`
}

type SignUpRestrictUid struct {
	UserId int `description:"用户ID"`
}

// 到会操作
func MeetingDo(meetingUids, noMeetingUids string, ActivityId int, items []*CygxActivityOfflineMeetingDetail) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	//修改报名表的参会记录
	sql := `UPDATE cygx_activity_signup SET is_meeting = 0  WHERE activity_id =? `
	_, err = to.Raw(sql, ActivityId).Exec()
	if err != nil {
		return
	}
	sql = `UPDATE cygx_activity_signup SET is_meeting = 1  WHERE activity_id =? AND  user_id IN  (` + meetingUids + `)`
	_, err = to.Raw(sql, ActivityId).Exec()
	if err != nil {
		return
	}
	sql = `UPDATE cygx_activity SET is_submit_meeting = 1 , submit_meeting_type = 1 WHERE activity_id = ? `
	_, err = to.Raw(sql, ActivityId).Exec()
	if err != nil {
		return
	}
	//删除老的记录并插入新的记录
	sql = `DELETE FROM cygx_activity_offline_meeting_detail   WHERE activity_id = ? `
	_, err = to.Raw(sql, ActivityId).Exec()
	if err != nil {
		return
	}
	if len(items) > 0 {
		//批量添加记录
		_, err = to.InsertMulti(len(items), items)
		if err != nil {
			return
		}
	}

	if len(noMeetingUids) > 0 {
		sql = `UPDATE cygx_activity_offline_meeting_detail SET is_meeting = 0  WHERE activity_id =? AND user_id IN (` + noMeetingUids + `)`
		_, err = to.Raw(sql, ActivityId).Exec()
		if err != nil {
			return
		}
	}
	//添加记录表的到会信息
	sql = `UPDATE cygx_activity_signup_detail SET is_meeting = 1  WHERE activity_id =? AND  user_id IN  (` + meetingUids + `)`
	_, err = to.Raw(sql, ActivityId).Exec()
	if err != nil {
		return
	}
	return
}

// 获取数量
func GetCygxBreakAppointmentCount(condition string, pars []interface{}) (count int, err error) {
	sqlCount := ` SELECT COUNT(1)  count FROM ( SELECT s.user_id 
				FROM
				cygx_activity_signup_break AS s
				INNER JOIN cygx_activity AS a ON a.activity_id = s.activity_id
				 WHERE 1 = 1 ` + condition + ` GROUP BY s.user_id) AS c  `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

// 爽约记录列表
type CygxBreakAppointmentList struct {
	UserId              int    `description:"用户ID"`
	CompanyId           int    `description:"公司ID"`
	RealName            string `description:"姓名"`
	Mobile              string `description:"手机号"`
	CompanyName         string `description:"公司名称"`
	SellerName          string `description:"销售姓名"`
	BreakAppointmentNum int    `description:"爽约次数"`
	IsRestrict          int    `description:"是否被限制报名"`
	Operation           bool   `description:"是否被限制报名操作，true限制，false不限制"`
}

type GetCygxBreakAppointmentListRep struct {
	Paging *paging.PagingItem `description:"分页数据"`
	List   []*CygxBreakAppointmentList
}

func GetCygxBreakAppointmentList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxBreakAppointmentList, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			( SELECT COUNT( 1 ) FROM cygx_activity_restrict_signup AS sig WHERE sig.is_restrict = 1 ) AS is_restrict,
			(
			SELECT
				COUNT( 1 ) count 
			FROM
				cygx_activity_signup_break AS s
				INNER JOIN cygx_activity AS a ON a.activity_id = s.activity_id
				WHERE
				s.user_id = cs.user_id 
			) AS break_appointment_num,
			s.real_name,
			s.mobile,
			s.user_id,
			s.company_id,
			s.company_name,
			s.activity_id
		FROM
			cygx_activity_signup_break AS s
			INNER JOIN cygx_activity AS a ON a.activity_id = s.activity_id
			INNER JOIN cygx_activity_signup AS cs ON cs.activity_id = s.activity_id 
		WHERE
			1 = 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY s.user_id ORDER BY break_appointment_num DESC,a.activity_time DESC LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// 获取爽约次数数量
func GetCygxBreakAppointmentUserCount(uid int) (count int, err error) {
	sqlCount := ` SELECT  COUNT(1) count
				FROM
				cygx_activity_signup AS s
				LEFT JOIN cygx_activity AS a ON a.activity_id = s.activity_id
				WHERE
				s.activity_id = a.activity_id 
				AND s.is_meeting = 0 
				AND a.is_submit_meeting = 1 
				AND s.user_id = ? `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, uid).QueryRow(&count)
	return
}

func GetCompanySellerName(companyId int) (sellerName string, err error) {
	sql := `SELECT
			GROUP_CONCAT( DISTINCT p.seller_name SEPARATOR '/' ) AS sellerName 
		FROM
			company_product AS p
		WHERE
			p.company_id = ?`
	o := orm.NewOrm()
	err = o.Raw(sql, companyId).QueryRow(&sellerName)
	return
}

//end

// 销售名称
type CygxSellerNameList struct {
	SellerName string `orm:"column(real_name);"description:"销售姓名"`
}
type GetCygxSellerNameListRep struct {
	List []*CygxSellerNameList
}

func GetCygxSellerNameList() (items []*CygxSellerNameList, err error) {
	o := orm.NewOrm()
	sql := `SELECT real_name FROM admin WHERE role = 'sales' `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

//end

// 活动详情
type CygxActivityBreakAppointment struct {
	ActivityName        string `description:"活动名称"`
	ActivityTypeName    string `description:"活动类型名称"`
	ChartPermissionName string `description:"行业名称"`
	ActivityTimeText    string `description:"活动时间带文字"`
}
type GetCygxActivityBreakAppointmentRep struct {
	List []*CygxActivityBreakAppointment
}

func GetCygxActivityBreakAppointmentList(mobile string) (items []*CygxActivityBreakAppointment, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT a.activity_name,a.activity_type_name,a.chart_permission_name,a.activity_time_text
   			FROM cygx_activity AS a
			INNER JOIN cygx_activity_signup_break AS s ON s.activity_id = a.activity_id 
			WHERE 1 = 1
			AND s.mobile = ? `
	_, err = o.Raw(sql, mobile).QueryRows(&items)
	return
} //end

// 报名限制
func AddSignUpRestrict(uid int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	var count int
	sql := `SELECT COUNT(1) AS count FROM cygx_activity_restrict_signup WHERE user_id=? `
	err = to.Raw(sql, uid).QueryRow(&count)
	if err != nil {
		return
	}
	sql = `UPDATE cygx_activity SET is_submit_meeting = 1  WHERE activity_id = ? `
	_, err = to.Raw(sql, uid).Exec()
	return
}

// 获取爽约次数
func GetUserBreakAppointmentCount(uid int) (count int, err error) {
	sqlCount := `SELECT COUNT(1)  count FROM (
				SELECT
				( SELECT COUNT( 1 ) FROM cygx_activity_signup AS s WHERE s.activity_id = a.activity_id AND s.is_meeting = 0 AND a.is_submit_meeting = 1 ) AS break_appointment_num 
				FROM
				cygx_activity_signup AS s
				INNER JOIN cygx_activity AS a ON a.activity_id = s.activity_id 
				WHERE
				1 = 1 
				AND s.is_meeting = 0 
				AND a.is_submit_meeting = 1 
				AND s.user_id = ? 
				GROUP BY
				s.user_id ) as cn `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, uid).QueryRow(&count)
	return
}

func GetCygxActivityRestrictSignupCount(uid int) (count int, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT COUNT(1) AS count FROM cygx_activity_restrict_signup WHERE user_id=? `
	err = o.Raw(sql, uid).QueryRow(&count)
	return
}

// 获取限制报名详情
func GetCygxActivityRestrictSignupInfo(uid int) (item *CygxActivityRestrictSignup, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_activity_restrict_signup  WHERE user_id=?`
	err = o.Raw(sql, uid).QueryRow(&item)
	return
}

// 修改报名限制状态
func UpdateCygxActivityRestrictSignup(newIsRestrict, uid int) (err error) {
	sql := `UPDATE cygx_activity_restrict_signup SET  is_restrict=?  WHERE user_id=? `
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Raw(sql, newIsRestrict, uid).Exec()
	return
}

type MeetingExportRep struct {
	CompanyName         string `description:"公司名称"`
	CompanyId           int    `description:"公司ID"`
	Status              string `description:"状态"`
	RealName            string `description:"姓名"`
	Mobile              string `description:"手机号"`
	PsellerName         string `description:"所属销售"`
	ActivityName        string `description:"活动名称"`
	ChartPermissionName string `description:"行业名称"`
	ActivityTypeName    string `description:"活动类型名称"`
	ActivityTimeText    string `description:"活动时间带文字"`
	Permission          string `description:"开通权限"`
}

// 获取报名了的用户IDs
func GetSignupUserIds(activityId int, uIds string) (signupUids string, err error) {
	sql := ` SELECT
			GROUP_CONCAT( DISTINCT s.user_id SEPARATOR ',' ) AS signupUids 
			FROM cygx_activity_signup AS s
            WHERE s.activity_id = ? AND s.do_fail_type = 0 AND s.user_id not IN (` + uIds + `)`
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sql, activityId).QueryRow(&signupUids)
	return
}

// 到会数据
func GetMeetingExportAll(condition string) (items []*MeetingExportRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			s.attendance_id,
			s.company_name,
			s.company_id,
			s.mobile,
			s.real_name,
			a.activity_name,
			a.chart_permission_name,
			a.activity_type_name,
			a.activity_time_text,
			s.seller_name
		FROM
			cygx_activity_meet_detail_log AS s
			INNER JOIN cygx_activity AS a ON a.activity_id = s.activity_id
		WHERE
			1 = 1
			AND s.company_name != ''
			AND a.active_state = 3   `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY s.attendance_id ORDER BY s.company_meet_num DESC, s.user_meet_num DESC, a.activity_time DESC   `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetCompanyAciviytyGroupDate() (item []*CreateTimesResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT date_format(activity_time,'%Y-%m') as create_times FROM cygx_activity WHERE 1=1  AND  activity_time <= NOW()  GROUP BY create_times ORDER BY create_times DESC `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

type CygxYidongActivityMeetingApiLog struct {
	Id               int    `orm:"column(id);pk"`
	Data             string `description:"返回结果数据"`
	YidongActivityId string `description:"易董活动ID"`
	CreateTime       string `description:"本地创建时间"`
}

// 获取限制报名详情
func GetCygxActivityYiDongUpdateTime(yidongActivityId string) (item *CygxYidongActivityMeetingApiLog, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_yidong_activity_meeting_api_log  WHERE yidong_activity_id = ? ORDER BY id DESC  LIMIT 1`
	err = o.Raw(sql, yidongActivityId).QueryRow(&item)
	return
}

type CygxAtivityIdMeetNum struct {
	ActivityId int `description:"活动ID"`
	Num        int `description:"数量"`
}

// GetCygxActivityYiDongMeetNum 根据活动ID获取到会数量的列表
func GetCygxActivityYiDongMeetNum(activityId []int) (items []*CygxAtivityIdMeetNum, err error) {
	lenactivityId := len(activityId)
	if lenactivityId == 0 {
		return
	}
	sql := `SELECT
			activity_id,
			( SELECT count( 1 ) FROM cygx_activity_signup AS s WHERE s.activity_id = a.activity_id AND is_meeting = 1  AND  yidong_examine_status = 1 ) AS num 
		FROM
			cygx_activity AS a 
		WHERE
			a.activity_id IN  (` + utils.GetOrmInReplace(lenactivityId) + `) `
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Raw(sql, activityId).QueryRows(&items)
	return
}

type GetSellerUserMobileResp struct {
	Mobile string `description:"手机号"`
	UserId int    `description:"用户ID"`
}

// 获取销售所能查看到的手机号
func GetSellerUserMobile(condition string) (items []*GetSellerUserMobileResp, err error) {
	o := orm.NewOrm()
	_, err = o.Raw(condition).QueryRows(&items)
	return
}
