package cygx

import (
	"errors"
	"fmt"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"strconv"
	"time"
)

// 获取公司剩余点数
func GetCygxActivityPointsCompanyByCompanyId(companyId int) (points string) {
	var err error
	points = "0" // 默认都展示 0
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("获取公司剩余点数失败："+err.Error(), 2)
		}
	}()
	pointsCompany, e := cygx.GetCygxActivityPointsCompanyByCompanyId(companyId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivityPointsCompanyByCompanyId，Err" + e.Error())
		return
	}
	if pointsCompany == nil {
		return
	}
	//转字符串
	points = fmt.Sprint(pointsCompany.Points)
	return
}

// CheckActivityPointsSet 校验研选扣点内容
func CheckActivityPointsSet(pointsSet *cygx.CygxActivityPointsSetRsq, activityId int) (errMsg string, itemResp *cygx.CygxActivityPointsSet, err error) {
	//校验研选扣点内容
	if pointsSet == nil {
		return
	}
	switch pointsSet.PointsObject {
	case "":
		errMsg = "请选择扣点对象"
	case "1":
		if pointsSet.UserPointsNum == "" {
			errMsg = "参会人扣点数量不能为空"
		}
	case "2":
		if pointsSet.CompanyPointsNum == "" {
			errMsg = "办会人扣点数量不能为空"
		}
		if pointsSet.CompanyId == 0 {
			errMsg = "请选择对应公司"
		}
	case "3":
		if pointsSet.UserPointsNum == "" {
			errMsg = "参会人扣点数量不能为空"
		}
		if pointsSet.CompanyPointsNum == "" {
			errMsg = "办会人扣点数量不能为空"
		}
		if pointsSet.CompanyId == 0 {
			errMsg = "请选择对应公司"
		}
	}

	companyId := pointsSet.CompanyId
	if companyId > 0 {
		pointsCompany, e := cygx.GetCygxActivityPointsCompanyByCompanyId(companyId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCygxActivityPointsCompanyByCompanyId，Err" + e.Error())
			return
		}
		if pointsCompany == nil {
			errMsg = "公司剩余点数不足"
			return
		}
		companyPointsNum, _ := strconv.ParseFloat(pointsSet.CompanyPointsNum, 2)
		if companyPointsNum == 0 {
			errMsg = "办会人扣点数量设置有误" + pointsSet.CompanyPointsNum
		}
		if activityId == 0 {
			if companyPointsNum > pointsCompany.Points {
				errMsg = "公司剩余点数不足"
			}
		} else {
			pointsSetDetail, e := cygx.GetCygxActivityPointsSetDetail(activityId)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetCygxActivityPointsSetDetail, Err: " + e.Error())
				return
			}
			if pointsSetDetail != nil {
				if pointsSetDetail.CompanyId != companyId {
					if companyPointsNum > pointsCompany.Points {
						errMsg = "公司剩余点数不足"
					}
				} else {
					//查询最新的一条针对这个公司的扣点记录
					var condition string
					var pars []interface{}
					condition += ` AND activity_id = ? AND company_id = ? AND mobile = ''   ORDER BY id DESC LIMIT 1  `
					pars = append(pars, activityId, companyId)
					activityPointsBillDetail, e := cygx.GetCygxActivityPointsBillDetailByCondition(condition, pars)
					if e != nil && e.Error() != utils.ErrNoRow() {
						err = errors.New("GetCompanyPoints, Err: " + e.Error())
						return
					}
					if activityPointsBillDetail != nil {
						CompanyPointsNumOld, _ := strconv.ParseFloat(pointsSetDetail.CompanyPointsNum, 2)
						if pointsCompany.Points-companyPointsNum+CompanyPointsNumOld < 0 {
							errMsg = "公司剩余点数不足"
						}
					}
				}
			} else {
				if companyPointsNum > pointsCompany.Points {
					errMsg = "公司剩余点数不足"
				}
			}
		}
	}

	if errMsg != "" {
		return
	}
	item := new(cygx.CygxActivityPointsSet)
	item.PointsObject = pointsSet.PointsObject
	item.CompanyId = pointsSet.CompanyId
	item.CompanyName = pointsSet.CompanyName
	item.UserPointsNum = pointsSet.UserPointsNum
	item.PointsType = pointsSet.PointsType
	item.CompanyPointsNum = pointsSet.CompanyPointsNum
	item.CancelDeadlineType = pointsSet.CancelDeadlineType
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	itemResp = item
	return
}

// UpdateYanXuanActivityPointsBillOldComapny 活动内容编辑的时候对原有的公司进行返点
func UpdateYanXuanActivityPointsBillOldComapny(activityInfo *cygx.ActivityDetail, adminId int, pointsSet *cygx.CygxActivityPointsSet, pointsSetOld *cygx.CygxActivityPointsSetRsq) (errMsg string, itemResp *cygx.CygxActivityPointsSet, err error) {
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("获取公司剩余点数失败："+err.Error(), 2)
		}
	}()
	activityId := activityInfo.ActivityId
	var companyIdNew int
	var companyIdOld int
	if pointsSetOld == nil {
		return
	}
	companyIdOld = pointsSetOld.CompanyId
	if pointsSet != nil {
		companyIdNew = pointsSet.CompanyId
	}
	if companyIdNew == companyIdOld && companyIdNew > 0 {
		go YanXuanActivityPointsBillActivityEdit(activityId, adminId) //活动编辑处理研选扣点
	}
	//如果新老机构一样或者非办会人扣点，那么不做任何处理
	if companyIdNew == companyIdOld || companyIdOld == 0 {
		return
	}
	comapny, e := company.GetCompanyDetailById(companyIdOld)
	if e != nil {
		err = errors.New("GetCompanyDetailById" + e.Error())
		return
	}
	companyPointsNumOld, _ := strconv.ParseFloat(pointsSetOld.CompanyPointsNum, 2)
	var items []*cygx.CygxActivityPointsBill
	item := new(cygx.CygxActivityPointsBill)
	var itemCompanys []*cygx.CygxActivityPointsCompany
	itemCompany := new(cygx.CygxActivityPointsCompany)

	// 获取用户所在公司剩余的点
	companyPointsNum, e := cygx.GetCompanyPoints(companyIdOld)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyPoints, Err: " + e.Error())
		return
	}
	item.ActivityId = activityId
	item.CreateTime = time.Now()
	item.CompanyId = comapny.CompanyId
	item.CompanyName = comapny.CompanyName
	item.BillDetailed = companyPointsNumOld
	item.RegisterPlatform = 0
	item.AdminId = int64(adminId)
	item.Source = 2
	item.ChartPermissionId = activityInfo.ChartPermissionId
	item.DoType = 2
	item.Content = activityInfo.ActivityName + "--取消办会"
	item.Points = companyPointsNum + companyPointsNumOld
	items = append(items, item)

	//更新对应机构的剩余点数
	itemCompany.CompanyId = comapny.CompanyId
	itemCompany.Points = item.Points
	itemCompany.ModifyTime = time.Now()
	itemCompanys = append(itemCompanys, itemCompany)

	//fmt.Println("更换公司处理返点")
	e = cygx.AddCygxActivityPointsBillMulti(items, itemCompanys)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("AddCygxActivityPointsBillMulti, Err: " + e.Error())
		return
	}
	return
}

// 1用户报名添加到处理研选扣点
func YanXuanActivityPointsBillSignupAdd(activityId, uid, adminId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("activityId:", activityId, "userId:", uid)
			go alarm_msg.SendAlarmMsg("用户报名添加到处理研选扣点，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	//SourceType int       `description:"1：报名、 2：取消报名、3：活动编辑、4：活动发布，取消发布、5：活动到会。"`
	log := &cygx.YanXuanActivityPointsRedis{UserId: uid, ActivityId: activityId, SourceType: 1, AdminId: adminId, Source: 2, CreateTime: time.Now()}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.CYGX_YANXUAN_POINTS_KEY, log)
		if err != nil {
			fmt.Println("YanXuanActivityPointsRedis LPush Err:" + err.Error())
		}
	}
	return
}

// 2用户取消报名添加到处理研选扣点
func YanXuanActivityPointsBillSignupCancel(activityId, uid, adminId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("activityId:", activityId, "userId:", uid)
			go alarm_msg.SendAlarmMsg("用户取消报名添加到处理研选扣点，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	//SourceType int       `description:"1：报名、 2：取消报名、3：活动编辑、4：活动发布，取消发布、5：活动到会。"`
	log := &cygx.YanXuanActivityPointsRedis{UserId: uid, ActivityId: activityId, SourceType: 2, AdminId: adminId, Source: 2, CreateTime: time.Now()}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.CYGX_YANXUAN_POINTS_KEY, log)
		if err != nil {
			fmt.Println("YanXuanActivityPointsRedis LPush Err:" + err.Error())
		}
	}
	return
}

// 3 活动编辑处理研选扣点
func YanXuanActivityPointsBillActivityEdit(activityId, adminId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("activityId:", activityId)
			go alarm_msg.SendAlarmMsg("活动编辑理研选扣点，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	//SourceType int       `description:"1：报名、 2：取消报名、3：活动编辑、4：活动发布，取消发布、5：活动到会。"`
	log := &cygx.YanXuanActivityPointsRedis{ActivityId: activityId, SourceType: 3, AdminId: adminId, Source: 2, CreateTime: time.Now()}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.CYGX_YANXUAN_POINTS_KEY, log)
		if err != nil {
			fmt.Println("YanXuanActivityPointsRedis LPush Err:" + err.Error())
		}
	}
	return
}

// 4 活动发布以及取消发布处理研选扣点
func YanXuanActivityPointsBillActivityPublishAndCancel(activityId, adminId, publishStatus int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("activityId:", activityId)
			go alarm_msg.SendAlarmMsg("活动发布以及取消发布处理研选扣点，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	//SourceType int       `description:"1：报名、 2：取消报名、3：活动编辑、4：活动发布，取消发布、5：活动到会。"`
	log := &cygx.YanXuanActivityPointsRedis{ActivityId: activityId, SourceType: 4, AdminId: adminId, Source: 2, PublishStatus: publishStatus, CreateTime: time.Now()}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.CYGX_YANXUAN_POINTS_KEY, log)
		if err != nil {
			fmt.Println("YanXuanActivityPointsRedis LPush Err:" + err.Error())
		}
	}
	return
}

// 5 活动到会研选扣点处理
func YanXuanActivityPointsBillSubmitMeeting(activityId, adminId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("activityId:", activityId)
			go alarm_msg.SendAlarmMsg("活动到会研选扣点处理，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	//SourceType int       `description:"1：报名、 2：取消报名、3：活动编辑、4：活动发布，取消发布、5：活动到会。6:研选审批通过的时候研选扣点更新、 7:正式专试用定时任务更新研选扣点"`
	log := &cygx.YanXuanActivityPointsRedis{ActivityId: activityId, SourceType: 5, AdminId: adminId, Source: 2, CreateTime: time.Now()}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.CYGX_YANXUAN_POINTS_KEY, log)
		if err != nil {
			fmt.Println("YanXuanActivityPointsRedis LPush Err:" + err.Error())
		}
	}
	return
}

// 6 研选审批通过的时候研选扣点更新
func YanXuanCompanyApproval(comapnyId, companyContractId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("comapnyId:", comapnyId)
			go alarm_msg.SendAlarmMsg("研选审批通过的时候研选扣点更新，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	//SourceType int       `description:"1：报名、 2：取消报名、3：活动编辑、4：活动发布，取消发布、5：活动到会。"`
	log := &cygx.YanXuanActivityPointsRedis{ComapnyId: comapnyId, CompanyContractId: companyContractId, SourceType: 6, Source: 2, CreateTime: time.Now()}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.CYGX_YANXUAN_POINTS_KEY, log)
		if err != nil {
			fmt.Println("YanXuanActivityPointsRedis LPush Err:" + err.Error())
		}
	}
	return
}

func init0703() {
	//2023.07.03剩余服务点数初始化
	path := "0703.xlsx"
	xlFile, err := xlsx.OpenFile(path)
	if err != nil {
		fmt.Println(err)
	}
	mapcompanyName := make(map[string]string)
	fmt.Println(xlFile)
	var items []*cygx.CygxActivityPointsCompany
	for _, sheet := range xlFile.Sheets {
		//遍历行读取
		maxRow := sheet.MaxRow
		for i := 0; i < maxRow; i++ {
			//fmt.Println(i)
			if i == 0 {
				continue
			}
			row := sheet.Row(i)
			cells := row.Cells
			var companyName string
			var points float64
			item := new(cygx.CygxActivityPointsCompany)
			for k, cell := range cells {
				if k == 0 {
					text := cell.String()
					companyName = text
				}
				if k == 3 {
					text := cell.String()
					points, _ = strconv.ParseFloat(text, 2)
					item.Points = points
				}
				itemDetail, err := company.CheckCompanyProductByName(companyName, 2)
				if err != nil {
					fmt.Println(err, companyName)
					return
				}
				item.CompanyName = itemDetail.CompanyName
				item.CompanyId = itemDetail.CompanyId
				item.CreateTime = time.Now()
				item.ModifyTime = time.Now()
				if mapcompanyName[itemDetail.CompanyName] != "" {
					continue
				}
				items = append(items, item)
				mapcompanyName[itemDetail.CompanyName] = itemDetail.CompanyName
			}
		}
	}
	var companyIds string
	var itemsBill []*cygx.CygxActivityPointsBill
	for _, v := range items {
		fmt.Println(v.CompanyName, v.Points)
		itemBill := new(cygx.CygxActivityPointsBill)
		itemBill.CreateTime = time.Now()
		itemBill.CompanyId = v.CompanyId
		itemBill.CompanyName = v.CompanyName
		itemBill.Source = 3
		itemBill.BillDetailed = v.Points
		itemBill.Points = v.Points
		itemBill.DoType = 2
		itemBill.Content = "2023.07.03剩余服务点数初始化"
		itemsBill = append(itemsBill, itemBill)
	}
	err = cygx.AddCygxActivityPointsBillAndCompanyMulti(itemsBill, items)
	fmt.Println(len(items))
	fmt.Println(len(itemsBill))
	utils.FileLog.Info(companyIds)
	fmt.Println(companyIds)
	fmt.Println(err)
}

func UpdateActivityVivoPointsSet(activityInfo *cygx.ActivityDetail, vivoPointsSet cygx.CygxActivityVivoPointsSetReq, itemPointsSet *cygx.CygxActivityPointsSet, sourceVivo string) (err error) {
	activityId := activityInfo.ActivityId
	if vivoPointsSet.IsPay == 0 {
		return
	}
	if sourceVivo == "" {
		return
	}
	total, e := cygx.GetCygxActivityVivoPointsSetCountByActivityId(activityId)
	if e != nil {
		err = errors.New("GetCygxActivityVivoPointsSetCountByActivityId, Err: " + e.Error())
		return
	}
	if vivoPointsSet.PointsNum == "" {
		vivoPointsSet.PointsNum = "0"
	}
	if vivoPointsSet.GoodsMoney == "" {
		vivoPointsSet.GoodsMoney = "0"
	}
	item := new(cygx.CygxActivityVivoPointsSet)
	item.ActivityId = activityId
	item.PointsObject = vivoPointsSet.PointsObject
	item.PointsNum = vivoPointsSet.PointsNum
	item.GoodsMoney = vivoPointsSet.GoodsMoney
	item.Source = sourceVivo
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	if total == 0 {
		e = cygx.AddCygxActivityVivoPointsSet(item)
		if e != nil {
			err = errors.New("AddCygxActivityVivoPointsSet, Err: " + e.Error())
			return
		}
	} else {
		e = cygx.EditCygxActivityVivoPointsSet(item)
		if e != nil {
			err = errors.New("AddCygxActivityVivoPointsSet, Err: " + e.Error())
			return
		}
	}

	return
}
