package cygx

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// 处理产业与标签
func HandleIndustrialLabel(temporaryLabel, industrialManagementIdS, industrialSubjectIdS string, activityId int) (industrialActivityItems []*cygx.CygxIndustrialActivityGroupManagement, subjectActivityItems []*cygx.CygxIndustrialActivityGroupSubject, err error, industrialNames, industrialSubjectNames string) {
	//如果临时标签是空的话，就去关联产业跟标的
	var temporarySubject string
	if temporaryLabel == "" {
		if industrialManagementIdS == "" {
			return
		}
		industrialManagementList := strings.Split(industrialManagementIdS, ",")
		for _, v := range industrialManagementList {
			industrialActivityItem := new(cygx.CygxIndustrialActivityGroupManagement)
			industrialManagementId, e := strconv.Atoi(v)
			if e != nil {
				err = errors.New("获取微路演音视频列表失败, Err: " + e.Error())
				return
			}
			industrialActivityItem.CreateTime = time.Now()
			industrialActivityItem.IndustrialManagementId = industrialManagementId
			industrialActivityItem.ActivityId = activityId
			industrialActivityItem.Source = 2
			industrialActivityItems = append(industrialActivityItems, industrialActivityItem)
		}
		if industrialSubjectIdS != "" {
			industrialSubjectIdList := strings.Split(industrialSubjectIdS, ",")
			for _, v := range industrialSubjectIdList {
				subjectActivityItem := new(cygx.CygxIndustrialActivityGroupSubject)
				industrialSubjectId, e := strconv.Atoi(v)
				if e != nil {
					err = errors.New("标的ID不规范，Err:" + e.Error() + industrialManagementIdS)
					return
				}
				subjectActivityItem.CreateTime = time.Now()
				subjectActivityItem.IndustrialSubjectId = industrialSubjectId
				subjectActivityItem.ActivityId = activityId
				subjectActivityItem.Source = 2
				subjectActivityItems = append(subjectActivityItems, subjectActivityItem)
			}
		}
		//产业名称
		if industrialManagementIdS != "" {
			industrialNames, err = cygx.GetindustrialManagementNames(industrialManagementIdS)
			if err != nil {
				return
			}
		}
		//标的名称
		if industrialSubjectIdS != "" {
			industrialSubjectNames, err = cygx.GetindustrialSubjectNames(industrialSubjectIdS)
			if err != nil {
				return
			}
			if temporarySubject != "" {
				industrialSubjectNames += "/" + strings.Replace(temporarySubject, ",", "/", -1)
			}
		} else {
			industrialSubjectNames = ""
			if temporarySubject != "" {
				industrialSubjectNames = strings.Replace(temporarySubject, ",", "/", -1)
			}
		}
	} else {
		industrialActivityItems = make([]*cygx.CygxIndustrialActivityGroupManagement, 0)
		subjectActivityItems = make([]*cygx.CygxIndustrialActivityGroupSubject, 0)
	}
	return
}

// HandleDateYmdList 处理时间
func HandleDateYmdList(dateYmdList []*cygx.DateYmdList) (activityTimeTextByDay, activityTime, activityTimeEnd string, dateList []string, err error) {
	var timeStr string
	timeInit := time.Now()
	for k, v := range dateYmdList {
		for k2, v2 := range v.DateHmsList {
			for k3, v3 := range v2.DateHms {
				timeStr = v.DateYmd + " " + v3 + ":00"
				resultTime := utils.StrTimeToTime(timeStr) //时间字符串格式转时间格式
				timeStrYmd := resultTime.Format(utils.FormatDate)
				timeYmd := utils.StrTimeToTime(timeStrYmd + " 12:00:00") //拼接当天中午12点的时间
				var amOrPm string
				if resultTime.After(timeYmd) {
					amOrPm = " PM"
				} else {
					amOrPm = " AM"
				}
				week := utils.StrDateTimeToWeek(timeStr)
				if k == 0 && k2 == 0 && k3 == 0 {
					activityTimeTextByDay = timeStrYmd + "（" + week + "）" + v3 + amOrPm
					activityTime = timeStr
				}
				//下一个时间段必须晚于上一个时间段
				res := timeInit.After(resultTime)
				if res {
					err = errors.New("下一个时间段必须晚于上一个时间段！" + timeStr)
					return
				} else {
					timeInit = resultTime
				}
				dateList = append(dateList, timeStr)

			}
		}
	}
	if len(dateList) > 0 {
		activityTimeEnd = dateList[len(dateList)-1]
	}
	if len(dateList)%2 != 0 {
		err = errors.New("缺少开始时间或结束时间！")
		return
	}
	return
}

// 处理日期的插入
func AddActivitySpecial(dateList []string, activityId int) (err error) {
	if len(dateList) == 0 {
		return
	}
	var items []*cygx.CygxActivitySpecialDay
	for _, v := range dateList {
		item := new(cygx.CygxActivitySpecialDay)
		item.ActivityId = activityId
		item.DayTime = v
		item.CreateTime = time.Now()
		items = append(items, item)
	}
	_, err = cygx.AddCygxActivitySpecialDay(items, activityId)
	return
}

// GetCygxActivitySpecialDay 处理日程编辑的回显日期格式
func GetCygxActivitySpecialDay(activityId int) (items []*cygx.DateYmdList, err error) {
	list, e := cygx.GetCygxActivitySpecialDayByActivityId(activityId)
	if e != nil {
		err = e
		return
	}
	mapYmd := make(map[string]string)
	for _, v := range list {
		if _, ok := mapYmd[v.DayTime.Format(utils.FormatDate)]; !ok {
			mapYmd[v.DayTime.Format(utils.FormatDate)] = v.DayTime.Format(utils.FormatDate)
			var itemYmd = new(cygx.DateYmdList)
			itemYmd.DateYmd = v.DayTime.Format(utils.FormatDate)
			items = append(items, itemYmd)
		}
	}
	var itemHms = new(cygx.DateHmsList)
	for k, v := range list {
		for kI, vI := range items {
			if v.DayTime.Format(utils.FormatDate) == vI.DateYmd {
				itemHms.DateHms = append(itemHms.DateHms, v.DayTime.Format(utils.FormatTimeHm))
				if k%2 == 1 {
					items[kI].DateHmsList = append(items[kI].DateHmsList, itemHms)
					itemHms = new(cygx.DateHmsList)
				}
			}
		}
	}
	return
}

func HandleActivityListSpecial(list []*cygx.CygxActivitySpecialList, isTrip bool) (items []*cygx.CygxActivitySpecialList) {
	for k, v := range list {
		if list[k].IsDetermineTravel > 0 {
			list[k].IsDetermineTravel = 1
		}
		if !isTrip {
			if v.IsOffline > 0 {
				list[k].PublishStatus = 3
			}
			if v.IsDetermineTravel > 0 {
				list[k].PublishStatus = 4
			}
		}
		if v.Days > 0 {
			resultTime := utils.StrTimeToTime(v.ActivityTime) //时间字符串格式转时间格式
			res := time.Now().Before(resultTime)
			if !res && v.IsSubmitMeeting == 0 {
				list[k].IsShowSubmitMeeting = true
			}
			if !res && v.IsSubmitMeeting == 1 {
				list[k].IsShowAttendanceDetails = true
				list[k].IsShowUpdateMeeting = true
			}
		}
	}
	items = list
	return
}

//func init() {
//	specialSurplus, _ := GetSpecialSurplusByCompany(9892)
//	fmt.Println(specialSurplus)
//}

// TODO:GetSpecialSurplusByCompany 获取公司专项调研剩余次数
func GetSpecialSurplusByCompany(companyId int) (specialSurplus string, err error) {
	companyDetail, e := cygx.GetCompanyDetailByIdGroup(companyId)
	if e != nil {
		err = errors.New("GetCompanyDetailByIdGroup, Err: " + e.Error())
	}
	if companyDetail == nil {
		return
	}
	if companyDetail.Status != "永续" && companyDetail.Status != "正式" {
		return
	}
	if companyDetail.Status == "永续" {
		specialSurplus = "不限次数"
	}

	if companyDetail.Status == "正式" {
		userType, packageType, _, _, _ := GetUserType(companyId)
		var airborneTota int
		if userType == 2 {
			var condition string
			var pars []interface{}

			condition += ` AND company_id = ? `
			pars = append(pars, companyId)

			//到会空降的也加入流水记录表，这里不在做单独计算 2023-07-10
			//airborneTota, e = cygx.GetActivitySpecialTripAirborneCountByActivitySpecial(condition, pars)
			//if e != nil {
			//	err = errors.New("GetActivitySpecialTripAirborneCountByActivitySpecial, Err: " + e.Error())
			//	return
			//}
			//condition += ` AND is_valid = 1 `
			//查询当年的数据
			condition += ` AND create_time >= ?  `
			pars = append(pars, time.Now().Format(utils.FormatYearDate)+"-01-01")
			listTripBill, e := cygx.GetCygxActivitySpecialTripBill(condition, pars)
			if e != nil {
				err = errors.New("GetActivitySpecialTripCountByActivitySpecial, Err: " + e.Error())
				return
			}
			var TripBillNum int
			for _, v := range listTripBill {
				TripBillNum += v.BillDetailed
			}
			// CRM13.2 70w客户有16次专项调研, 45w有10次
			packageTypeMap := map[int]int{1: 16, 2: 10}
			totalTrip := packageTypeMap[packageType]

			tripRemaining := totalTrip - airborneTota + TripBillNum
			if tripRemaining < 0 {
				tripRemaining = 0
			}
			specialSurplus = strconv.Itoa(tripRemaining) + "次"
			//tripRemaining = 12 - tripTota
		} else {
			list, e := company.GetCompanyReportPermissionUpgrade(companyId, 2)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = errors.New("GetCompanyReportPermissionUpgrade, Err: " + e.Error())
			}
			if len(list) == 0 {
				return
			}
			var chartPermissionIdSlice []string
			mapChartName := make(map[string]int)
			mapPermissionNameTrip := make(map[string]int)
			//mapPermissionName := make(map[int]string)
			for _, v := range list {
				chartPermissionIdSlice = append(chartPermissionIdSlice, strconv.Itoa(v.ChartPermissionId))

			}
			chartList, e := models.GetChartPermissionByIds(chartPermissionIdSlice)
			if e != nil {
				err = errors.New("获取品种信息失败, Err:" + e.Error())
				return
			}
			if len(chartList) == 0 {
				return
			}
			//到会空降的也加入流水记录表，这里不在做单独计算 2023-07-10
			//airborneList, e := cygx.GetCygxActivitySpecialTripAirborneListByComapnyId(companyId)
			//if e != nil {
			//	err = errors.New("获取品种信息失败, Err:" + e.Error())
			//	return
			//}
			//for _, v := range airborneList {
			//	mapPermissionNameTrip[v.ChartPermissionName] += 1
			//}

			var condition string
			var pars []interface{}

			condition += ` AND company_id = ? `
			pars = append(pars, companyId)

			//查询当年的数据
			condition += ` AND b.create_time >= ?  `
			pars = append(pars, time.Now().Format(utils.FormatYearDate)+"-01-01")
			listTripBill, e := cygx.GetCygxActivitySpecialTripBillList(condition, pars)
			if e != nil {
				err = errors.New("GetActivitySpecialTripCountByActivitySpecial, Err: " + e.Error())
				return
			}
			//var TripBillNum int
			for _, v := range listTripBill {
				mapPermissionNameTrip[v.ChartPermissionName] += v.BillDetailed
			}
			for _, v := range chartList {
				mapChartName[v.PermissionName] = 5 + mapPermissionNameTrip[v.ChartPermissionName]
			}
			for k, v := range mapChartName {
				if v > 0 {
					specialSurplus += k + strconv.Itoa(v) + "次+"
				}
			}
			specialSurplus = strings.TrimRight(specialSurplus, "+")
		}
	}
	return
}

// GetSpecialUserType 获取专项产业调研的用户身份类型
func GetSpecialUserType(user *models.WxUser) (userType int, err error) {
	companyId := user.CompanyId
	companyDetail, e := cygx.GetCompanyDetailByIdGroup(companyId)
	if e != nil {
		err = errors.New("GetCompanyDetailByIdGroup, Err: " + e.Error())
	}
	if companyId <= 1 {
		userType = 0
	} else {
		if companyDetail.Status == "永续" {
			userType = 1
		} else {
			if companyDetail.Status == "正式" {
				list, e := company.GetCompanyReportPermissionUpgrade(companyId, 2)
				if e != nil && e.Error() != utils.ErrNoRow() {
					err = errors.New("GetCompanyReportPermissionUpgrade, Err: " + e.Error())
				}
				if len(list) == 0 {
					return
				}
				if len(list) == 4 {
					totalName, e := company.GetCompanyPermissionNameCheck(companyId, 2, "策略")
					if e != nil {
						err = errors.New("获取品种信息失败, Err:" + e.Error())
						return
					}
					if totalName > 0 {
						userType = 2
					} else {
						userType = 8
					}
				} else {
					userType = 8
				}
			}
		}
	}
	return
}

// CheckActivitySpecialUpdatePower 校验专项调研活动后台管理员、销售是否有修改权限
func CheckActivitySpecialUpdatePower(adminId int, activityInfo *cygx.ActivitySpecialDetail) (havePower bool, popupMsg string, err error) {
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("校验活动后台管理员、销售是否有修改权限失败，Err："+err.Error(), 3)
		}
	}()
	adminInfo, e := system.GetSysUserById(adminId)
	if e != nil {
		err = errors.New("获取管理员身份失败，GetSysUserById" + e.Error())
		return
	}
	//如果这个活动不是自己建的会议，那么就对权益销售跟权益组长做身份限制判断
	if activityInfo.AdminId > 0 && activityInfo.AdminId != adminId && (adminInfo.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || adminInfo.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP) {
		popupMsg = "只有建会销售可修改。"
		return
	}
	havePower = true
	return
}
