package cygx

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"time"
)

// 活动添加、修改入参
type ActivitySpecialRep struct {
	ActivityId              int    `description:"活动ID 等于0新增活动，大于0修改活动"`
	DoType                  int    `description:"操作类型 0，保存 、1，发布"`
	PermissionName          string `description:"行业名称"`
	ResearchTheme           string `description:"调研主题"`
	ActivityTimeText        string `description:"活动预期时间带文字"`
	IndustrialManagementIdS string `description:"产业ID，多个ID用 , 隔开"`
	IndustrialSubjectIdS    string `description:"标的ID，多个ID用 , 隔开"`
	CustomerTypeIds         string `description:"活动可见的客户类型，多个ID用 , 隔开"`
	TemporaryLabel          string `description:"临时标签"`
	TemporarySubject        string `description:"临时标的"`
	Scale                   string `description:"管理规模，空不填，1：:50亿以下，2：50~100亿，3：100亿以上。多个用, 隔开"`
	TripImgLink             string `description:"行程图片链接"`
	SpecialType             int    `description:"调研形式、 1 线上 ， 2 线下"`
	City                    string `description:"调研城市"`
	IsShowSubjectName       int    `description:"小程序内是否展示标的名称 1是 ，0 否 默认0 "`
}

// 活动添加、修改入参
type ActivitySpecialDateRep struct {
	ActivityId              int            `description:"活动ID"`
	PermissionName          string         `description:"行业名称"`
	ResearchTheme           string         `description:"调研主题"`
	ActivityTimeText        string         `description:"活动预期时间带文字"`
	IndustrialManagementIdS string         `description:"产业ID，多个ID用 , 隔开"`
	IndustrialSubjectIdS    string         `description:"标的ID，多个ID用 , 隔开"`
	CustomerTypeIds         string         `description:"活动可见的客户类型，多个ID用 , 隔开"`
	TemporaryLabel          string         `description:"临时标签"`
	TemporarySubject        string         `description:"临时标的"`
	Scale                   string         `description:"管理规模，空不填，1：:50亿以下，2：50~100亿，3：100亿以上。多个用, 隔开"`
	TripImgLink             string         `description:"行程图片链接"`
	SpecialType             int            `description:"调研形式、 1 线上 ， 2 线下"`
	City                    string         `description:"调研城市"`
	IsShowSubjectName       int            `description:"小程序内是否展示标的名称 1是 ，0 否 默认0 "`
	DateYmdList             []*DateYmdList `description:"时间年月日"`
	Days                    int            `description:"调研天数"`
	Host                    string         `description:"主持人"`
	PersonInCharge          string         `description:"纪要负责人"`
	LimitPeopleNum          int            `description:"限制人数数量"`
	TripImgLinkFix          string         `description:"确定行程之后的图片链接"`
	ActivityTimeTextByDay   string         `description:"活动预期时间带文字"`
}

type DateYmdList struct {
	DateYmd     string         `description:"时间年月日"`
	DateHmsList []*DateHmsList `description:"时间时分秒"`
}

type DateHmsList struct {
	DateHms []string `description:"时间时分秒"`
}

// 活动详情
type ActivitySpecialDetail struct {
	ActivityId            int    `orm:"column(activity_id);pk";description:"活动ID 等于0新增活动，大于0修改活动"`
	ChartPermissionId     int    `description:"行业id"`
	ChartPermissionName   string `description:"行业名称"`
	CustomerTypeIds       string `description:"活动可见的客户类型，多个ID用 , 隔开"`
	PublishStatus         int    `description:"发布状态 1已发布，0未发布"`
	ResearchTheme         string `description:"调研主题"`
	ActivityTimeText      string `description:"活动预期时间带文字"`
	TemporaryLabel        string `description:"临时标签"`
	TemporarySubject      string `description:"临时标的"`
	Scale                 string `description:"管理规模，空不填，1：:50亿以下，2：50~100亿，3：100亿以上。多个用, 隔开"`
	TripImgLink           string `description:"行程图片链接"`
	IndustrialName        string `description:"产业名称"`
	IndustrialSubjectName string `description:"标的名称（相关公司）"`
	Label                 string `description:"标签"`
	CustomerName          string `description:"活动可见—套餐类型"`
	SpecialType           int    `description:"调研形式、 1 线上 ， 2 线下"`
	City                  string `description:"调研城市"`
	IsShowSubjectName     int    `description:"小程序内是否展示标的名称 1是 ，0 否 默认0 "`
	AdminId               int    `description:"销售/管理员ID"`
	AdminName             string `description:"销售/管理员姓名"`
	ListIndustrial        []*IndustrialActivityGroupManagementRep
	ListSubject           []*SubjectActivityGroupManagementRep
	Days                  int            `description:"调研天数"`
	Host                  string         `description:"主持人"`
	PersonInCharge        string         `description:"纪要负责人"`
	LimitPeopleNum        int            `description:"限制人数数量"`
	TripImgLinkFix        string         `description:"确定行程之后的图片链接"`
	ActivityTimeTextByDay string         `description:"活动预期时间带周日"`
	ActivityTime          string         `description:"活动预期时间"`
	IsOffline             int            `description:"是否下线，1已下线，0未下线"`
	DateYmdList           []*DateYmdList `description:"时间年月日"`
	IsSubmitMeeting       int            `description:"是否提交过到会信息 ，1是，0否"`
	LastUpdatedTime       time.Time      `description:"更新时间"`
	PublishDate           string         `description:"发布时间"`
}

type ActivityDetailSpecialRep struct {
	Detail         *ActivityDetail
	ListIndustrial []*IndustrialActivityGroupManagementRep
	ListSubject    []*SubjectActivityGroupManagementRep
}

// 活动详情
type CygxActivitySpecial struct {
	ActivityId            int       `orm:"column(activity_id);pk";description:"活动ID 等于0新增活动，大于0修改活动"`
	ChartPermissionId     int       `description:"行业id"`
	ChartPermissionName   string    `description:"行业名称"`
	CustomerTypeIds       string    `description:"活动可见的客户类型，多个ID用 , 隔开"`
	PublishStatus         int       `description:"发布状态 1已发布，0未发布"`
	ResearchTheme         string    `description:"调研主题"`
	ActivityTimeText      string    `description:"活动预期时间带文字"`
	Label                 string    `description:"标签"`
	TemporaryLabel        string    `description:"临时标签"`
	TemporarySubject      string    `description:"临时标的"`
	Scale                 string    `description:"管理规模，空不填，1：:50亿以下，2：50~100亿，3：100亿以上。多个用, 隔开"`
	TripImgLink           string    `description:"行程图片链接"`
	IndustrialName        string    `description:"产业名称"`
	IndustrialSubjectName string    `description:"标的名称"`
	LastUpdatedTime       time.Time `description:"更新时间"`
	CreateTime            time.Time `description:"创建时间"`
	SpecialType           int       `description:"调研形式、 1 线上 ， 2 线下"`
	City                  string    `description:"调研城市"`
	IsShowSubjectName     int       `description:"小程序内是否展示标的名称 1是 ，0否 默认0 "`
	AdminId               int       `description:"销售/管理员ID"`
	AdminName             string    `description:"销售/管理员姓名"`
	Days                  int       `description:"调研天数"`
	Host                  string    `description:"主持人"`
	PersonInCharge        string    `description:"纪要负责人"`
	LimitPeopleNum        int       `description:"限制人数数量"`
	TripImgLinkFix        string    `description:"确定行程之后的图片链接"`
	ActivityTimeTextByDay string    `description:"活动预期时间带周日"`
	ActivityTime          string    `description:"活动预期时间"`
	PublishDate           string    `description:"活动发布时间"`
	ActivityTimeEnd       string    `description:"活动预期结束时间"`
	IsOffline             int       `description:"是否下线，1已下线，0未下线"`
}

// 添加活动
func AddActivitySpecial(item *CygxActivitySpecial, industrialActivityItems []*CygxIndustrialActivityGroupManagement, subjectActivityItems []*CygxIndustrialActivityGroupSubject) (newId int64, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	newId, err = to.Insert(item)
	if err != nil {
		return
	}
	//添加关联的产业
	if len(industrialActivityItems) > 0 {
		for _, v := range industrialActivityItems {
			v.ActivityId = int(newId)
			_, err = to.Insert(v)
			if err != nil {
				return
			}
		}
	}
	//添加关联的标的
	if len(subjectActivityItems) > 0 {
		for _, v := range subjectActivityItems {
			v.ActivityId = int(newId)
			_, err = to.Insert(v)
			if err != nil {
				return
			}
		}
	}
	return
}

// 通过纪要ID获取活动详情
func GetAddActivityInfoSpecialById(ActivityId int) (item *ActivitySpecialDetail, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_activity_special  WHERE activity_id=?`
	err = o.Raw(sql, ActivityId).QueryRow(&item)
	return
}

// 通过纪要ID获取活动详情
func GetCustomerName(ids string) (name string, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT GROUP_CONCAT( DISTINCT c.customer_name SEPARATOR '、' ) AS name 
			FROM cygx_customer_type AS c WHERE c.customer_type_id IN (` + ids + `)`
	err = o.Raw(sql).QueryRow(&name)
	return
}

// 修改
func EditActivitySpecial(updateParams map[string]interface{}, item *CygxActivitySpecial, industrialActivityItems []*CygxIndustrialActivityGroupManagement, subjectActivityItems []*CygxIndustrialActivityGroupSubject) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	activityId := item.ActivityId

	//修改活动信息
	ptrStructOrTableName := "cygx_activity_special"
	whereParam := map[string]interface{}{"activity_id": item.ActivityId}
	qs := to.QueryTable(ptrStructOrTableName)
	for expr, exprV := range whereParam {
		qs = qs.Filter(expr, exprV)
	}
	_, err = qs.Update(updateParams)

	//删除活动关联的产业
	sql := ` DELETE FROM cygx_industrial_activity_group_management WHERE activity_id = ? AND source =2`
	_, err = to.Raw(sql, activityId).Exec()
	if err != nil {
		return
	}
	//删除活动关联的标的
	sql = ` DELETE FROM cygx_industrial_activity_group_subject WHERE activity_id = ?  AND source =2`
	_, err = to.Raw(sql, activityId).Exec()
	if err != nil {
		return
	}
	//添加关联的产业
	if len(industrialActivityItems) > 0 {
		for _, v := range industrialActivityItems {
			_, err = to.Insert(v)
			if err != nil {
				return
			}
		}
	}
	//添加关联的标的
	if len(subjectActivityItems) > 0 {
		for _, v := range subjectActivityItems {
			_, err = to.Insert(v)
			if err != nil {
				return
			}
		}
	}
	return
}

// 修改
func EditActivitySpecialStatus(item *CygxActivitySpecial) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_activity_special SET publish_status=?, last_updated_time=NOW()  WHERE activity_id=?`
	_, err = o.Raw(sql, item.PublishStatus, item.ActivityId).Exec()
	return
}

// 修改
func UpdateActivitySpecial(updateParams map[string]interface{}, item *CygxActivitySpecial) (err error) {
	to := orm.NewOrmUsingDB("hz_cygx")
	//修改活动信息
	ptrStructOrTableName := "cygx_activity_special"
	whereParam := map[string]interface{}{"activity_id": item.ActivityId}
	qs := to.QueryTable(ptrStructOrTableName)
	for expr, exprV := range whereParam {
		qs = qs.Filter(expr, exprV)
	}
	_, err = qs.Update(updateParams)
	return
}

// 修改是否下线
func EditActivitySpecialIsOffline(item *CygxActivitySpecial) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_activity_special SET is_offline=?,publish_status=?, last_updated_time=NOW()   WHERE activity_id=?`
	_, err = o.Raw(sql, item.IsOffline, item.PublishStatus, item.ActivityId).Exec()
	return
}

// 活动详情
type CygxActivitySpecialList struct {
	ActivityId              int    `orm:"column(activity_id);pk";description:"活动ID 等于0新增活动，大于0修改活动"`
	ResearchTheme           string `description:"调研主题"`
	ChartPermissionName     string `description:"行业名称"`
	ActivityTimeText        string `description:"活动预期时间带文字"`
	ActivityTime            string `description:"活动预期时间"`
	ActivityTimeTextByDay   string `description:"活动预期时间带周几"`
	LastUpdatedTime         string `description:"更新时间"`
	InterestedNum           int    `description:"感兴趣人数"`
	SignupPeopleNum         int    `description:"报名人数"`
	PublishStatus           int    `description:"发布状态 1已发布，0未发布"`
	SpecialType             int    `description:"调研形式、 1 线上 ， 2 线下"`
	City                    string `description:"调研城市"`
	AdminId                 int    `description:"销售/管理员ID"`
	AdminName               string `description:"销售/管理员姓名"`
	IsOffline               int    `description:"是否下线，1已下线，0未下线"`
	Days                    int    `description:"调研天数"`
	IsDetermineTravel       int    `orm:"column(days)";description:"是否确定行程，1是，0否"`
	IsShowAttendanceDetails bool   `description:"是否展示到会详情"`
	IsShowUpdateMeeting     bool   `description:"是否展示修改到会情况"`
	IsShowSubmitMeeting     bool   `description:"是否展示提交到会情况"`
	IsSubmitMeeting         int    `description:"是否提交过到会信息 ，1是，0否"`
}

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

// 列表
func GetActivityListSpecialAll(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxActivitySpecialList, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT  (SELECT COUNT(1) FROM cygx_activity_special_signup AS h     WHERE h.activity_id=art.activity_id) AS interested_num ,
 (SELECT COUNT(1) FROM cygx_activity_special_trip AS h      WHERE h.activity_id=art.activity_id AND h.is_cancel =0 ) AS signup_people_num ,
			art.*  FROM cygx_activity_special as art WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

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

// 删除数据
func DeleteActivitySpecial(activityId int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` DELETE FROM cygx_activity_special WHERE activity_id = ?`
	_, err = o.Raw(sql, activityId).Exec()
	return
}

type CygxActivitySpecialSignup struct {
	Id          int    `orm:"column(id);pk"`
	ActivityId  int    `description:"活动ID"`
	UserId      int    `description:"用户ID"`
	CreateTime  string `description:"创建时间"`
	Mobile      string `description:"手机号"`
	CompanyName string `description:"公司名称"`
	CompanyId   int    `description:"公司ID"`
	RealName    string `description:"姓名"`
	SellerName  string `description:"销售姓名"`
}

type CygxActivitySpecialSignupListResp struct {
	List []*CygxActivitySpecialSignup
}

// 感兴趣列表
func GetCygxActivitySpecialSignupList(activityId int) (items []*CygxActivitySpecialSignup, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			s.*
		FROM
			cygx_activity_special_signup AS s
			LEFT JOIN cygx_activity_special AS a ON a.activity_id = s.activity_id
		WHERE
			a.activity_id = ?  
		GROUP BY
			s.user_id 
		ORDER BY
			s.id DESC`
	_, err = o.Raw(sql, activityId).QueryRows(&items)
	return
}

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

type CygxActivitySpecialSignupResp struct {
	Id                  int    `orm:"column(id);pk"`
	ActivityId          int    `description:"活动ID"`
	UserId              int    `description:"用户ID"`
	CreateTime          string `description:"创建时间"`
	Mobile              string `description:"手机号"`
	CompanyName         string `description:"公司名称"`
	CompanyId           int    `description:"公司ID"`
	RealName            string `description:"姓名"`
	SellerName          string `description:"销售姓名"`
	ResearchTheme       string `description:"调研主题"`
	Label               string `description:"标签"`
	ChartPermissionName string `description:"行业"`
	PublishDate         string `description:"发布时间"`
}

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

// 列表
func GetCygxActivitySpecialSignupListAll(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxActivitySpecialSignupResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			s.*,
			a.research_theme,
			a.label,
			a.chart_permission_name,
			a.create_time AS publish_date
		FROM
			cygx_activity_special_signup AS s
			INNER JOIN cygx_activity_special AS a ON a.activity_id = s.activity_id
		WHERE
			1 = 1 `
	if condition != "" {
		sql += condition
	}

	sql += `  LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

type AdminOpenIdList struct {
	OpenId    string `description:"OpenId"`
	UserId    int    `description:"UserId"`
	Mobile    string `description:"手机号"`
	CompanyId int    `description:"手机号"`
}

// GetAdminOpendidByCompany 通过用户公司ID获取对应销售的openid
func GetAdminMobileByCompany(condition string, pars []interface{}) (list []*AdminOpenIdList, err error) {
	sql := `SELECT
		a.mobile,p.company_id
		FROM
			company_product AS p
			INNER JOIN admin AS a ON a.admin_id = p.seller_id
		WHERE
			1 = 1 
			AND p.product_id = 2 ` + condition
	_, err = orm.NewOrm().Raw(sql, pars).QueryRows(&list)
	return
}

// 获取预约活动的用户的openID
func GeFollowSpecialOpenIdList() (items []*AdminOpenIdList, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT DISTINCT u.open_id,u.cygx_user_id as  user_id ,m.company_id
			FROM
			cygx_user_follow_special AS m
			INNER JOIN cygx_user_record AS u ON u.cygx_bind_account = m.mobile  `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

//func GetWxOpenIdBList(condition string, pars []interface{}) (items []*OpenIdList, err error) {
//	sql := `SELECT
//	cr.*,
//	u.user_id
//FROM
//	cygx_user_record AS cr
//	INNER JOIN user_record AS c ON c.union_id = cr.union_id
//	INNER JOIN wx_user AS u ON u.user_id = c.user_id
//WHERE
//	1 = 1
//	AND c.create_platform = 4 ` + condition + ` GROUP BY	cr.open_id `
//	_, err = orm.NewOrm().Raw(sql, pars).QueryRows(&items)
//	return
//}

// 通过产业名称获取关联的ID
func GetactivitySpecilIdsByLabel(name string) (activityIds string, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT
				GROUP_CONCAT( DISTINCT s.activity_id SEPARATOR ',' ) AS activityIds 
			FROM
				cygx_activity_special AS s 
			WHERE
				label LIKE  '%` + name + `%' `
	err = o.Raw(sql).QueryRow(&activityIds)
	return
}
