package cygx

import (
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

// 获取所有关注了该产业大套餐客户的openid
func GetCygxBigTypeUserIndustryFllowOpneidByActivityIds(activityId int) (items []*cygx.OpenIdList, err error) {
	companyIds, e := cygx.GetCygxIndustryFollowCompanyIdsByActivityId(activityId)
	if e != nil {
		err = e
		return
	}

	permissionList, e := cygx.GetCompanyPermissionByUsersZhengShi(*companyIds)
	if e != nil {
		err = e
		return
	}
	permissionListMap := make(map[int]string, 0)
	for _, item := range permissionList {
		if permission, ok := permissionListMap[item.CompanyId]; !ok {
			permissionListMap[item.CompanyId] = item.Permission
		} else {
			permissionListMap[item.CompanyId] = permission + "," + item.Permission
		}
	}
	var companyIdslice []string
	for k, v := range permissionListMap {
		permissionZhengShiStr := v
		if strings.Count(permissionZhengShiStr, "医药") == 2 && strings.Count(permissionZhengShiStr, "消费") == 2 && strings.Count(permissionZhengShiStr, "科技") == 2 && strings.Count(permissionZhengShiStr, "智造") == 2 {
			companyIdslice = append(companyIdslice, strconv.Itoa(k))
		}
	}

	finalIds := strings.Join(companyIdslice, ",")
	if finalIds != "" {
		var conditionuiUser string
		var parsUser []interface{}

		conditionuiUser = ` AND company_id IN (` + finalIds + `)`
		listUser, e := models.GetWxUserList(conditionuiUser, parsUser)
		if e != nil {
			err = e
			return
		}

		mapMobileUser := make(map[string]string)
		for _, v := range listUser {
			mapMobileUser[v.Mobile] = v.Mobile
		}

		var mobiles []string
		listFllow, e := cygx.GetCygxForeverUserIndustryFllowOpneidByActivityIds(activityId)
		if e != nil {
			err = e
			return
		}
		for _, v := range listFllow {
			if mapMobileUser[v.Mobile] != "" {
				mobiles = append(mobiles, v.Mobile)
			}
		}

		items, e = cygx.GetUserRecordListByMobileArr(mobiles)
		//items, e = models.GetCygxUserIndustryFllowOpneidByActivityIdAndCompanyIds(activityId, finalIds)
		if e != nil {
			err = e
			return
		}
	}
	return
}

// 获取所有关注了该产业行业套餐客户的openid
func GetCygxIndustryPackageUserIndustryFllowOpneidByActivityIds(activityId int) (items []*cygx.OpenIdList, err error) {
	companyIds, e := cygx.GetCygxIndustryFollowCompanyIdsByActivityId(activityId)
	if e != nil {
		err = e
		return
	}

	permissionList, e := cygx.GetCompanyPermissionByUsersZhengShi(*companyIds)
	if e != nil {
		err = e
		return
	}
	activityInfo, errInfo := cygx.GetAddActivityInfoById(activityId)
	if errInfo != nil {
		err = errInfo
		return
	}

	permissionListMap := make(map[int]string, 0)
	for _, item := range permissionList {
		if permission, ok := permissionListMap[item.CompanyId]; !ok {
			permissionListMap[item.CompanyId] = item.Permission
		} else {
			permissionListMap[item.CompanyId] = permission + "," + item.Permission
		}
	}
	var companyIdslice []string
	for k, v := range permissionListMap {
		permissionZhengShiStr := v
		if strings.Count(permissionZhengShiStr, "医药") == 2 && strings.Count(permissionZhengShiStr, "消费") == 2 && strings.Count(permissionZhengShiStr, "科技") == 2 && strings.Count(permissionZhengShiStr, "智造") == 2 {
			continue
		} else if strings.Contains(permissionZhengShiStr, activityInfo.ChartPermissionName) {
			companyIdslice = append(companyIdslice, strconv.Itoa(k))
		}
	}

	finalIds := strings.Join(companyIdslice, ",")
	if finalIds != "" {
		var conditionuiUser string
		var parsUser []interface{}

		conditionuiUser = ` AND company_id IN (` + finalIds + `)`
		listUser, e := models.GetWxUserList(conditionuiUser, parsUser)
		if e != nil {
			err = e
			return
		}

		mapMobileUser := make(map[string]string)
		for _, v := range listUser {
			mapMobileUser[v.Mobile] = v.Mobile
		}

		var mobiles []string
		listFllow, e := cygx.GetCygxForeverUserIndustryFllowOpneidByActivityIds(activityId)
		if e != nil {
			err = e
			return
		}
		for _, v := range listFllow {
			if mapMobileUser[v.Mobile] != "" {
				mobiles = append(mobiles, v.Mobile)
			}
		}

		items, e = cygx.GetUserRecordListByMobileArr(mobiles)
		//items, e = models.GetCygxUserIndustryFllowOpneidByActivityIdAndCompanyIds(activityId, finalIds)
		if e != nil {
			err = e
			return
		}
	}
	return
}

// 获取所有关注了该产业其他行业套餐客户的openid
func GetCygxOtherIndustryPackageUserIndustryFllowOpneidByActivityIds(activityId int) (items []*cygx.OpenIdList, err error) {
	companyIds, e := cygx.GetCygxIndustryFollowCompanyIdsByActivityId(activityId)
	if e != nil {
		err = e
		return
	}

	permissionList, e := cygx.GetCompanyPermissionByUsersZhengShi(*companyIds)
	if e != nil {
		err = e
		return
	}
	activityInfo, errInfo := cygx.GetAddActivityInfoById(activityId)
	if errInfo != nil {
		err = errInfo
		return
	}

	permissionListMap := make(map[int]string, 0)
	for _, item := range permissionList {
		if permission, ok := permissionListMap[item.CompanyId]; !ok {
			permissionListMap[item.CompanyId] = item.Permission
		} else {
			permissionListMap[item.CompanyId] = permission + "," + item.Permission
		}
	}
	var companyIdslice []string
	for k, v := range permissionListMap {
		permissionZhengShiStr := v
		if strings.Count(permissionZhengShiStr, "医药") == 2 && strings.Count(permissionZhengShiStr, "消费") == 2 && strings.Count(permissionZhengShiStr, "科技") == 2 && strings.Count(permissionZhengShiStr, "智造") == 2 {
			continue
		} else if !strings.Contains(permissionZhengShiStr, activityInfo.ChartPermissionName) {
			companyIdslice = append(companyIdslice, strconv.Itoa(k))
		}
	}

	finalIds := strings.Join(companyIdslice, ",")
	if finalIds != "" {
		//items, e = models.GetCygxUserIndustryFllowOpneidByActivityIdAndCompanyIds(activityId, finalIds)

		var conditionuiUser string
		var parsUser []interface{}

		conditionuiUser = ` AND company_id IN (` + finalIds + `)`
		listUser, e := models.GetWxUserList(conditionuiUser, parsUser)
		if e != nil {
			err = e
			return
		}

		mapMobileUser := make(map[string]string)
		for _, v := range listUser {
			mapMobileUser[v.Mobile] = v.Mobile
		}

		var mobiles []string
		listFllow, e := cygx.GetCygxForeverUserIndustryFllowOpneidByActivityIds(activityId)
		if e != nil {
			err = e
			return
		}
		for _, v := range listFllow {
			if mapMobileUser[v.Mobile] != "" {
				mobiles = append(mobiles, v.Mobile)
			}
		}

		items, e = cygx.GetUserRecordListByMobileArr(mobiles)
		if e != nil {
			err = e
			return
		}
	}
	return
}

// 获取所有关注了该产业其他行业套餐客户的openid
func GetCygxInteractiveUserOpneidByActivityIds(activityId int) (items []*cygx.OpenIdList, err error) {
	userIds, e := models.GetCygxInteractiveUserByActivityId(activityId)
	if e != nil {
		err = e
		return
	}

	var idSlice []string
	for _, id := range userIds {
		idSlice = append(idSlice, strconv.Itoa(*id))
	}

	ids := strings.Join(idSlice, ",")

	if ids != "" {
		var conditionuiUser string
		var parsUser []interface{}

		conditionuiUser = ` AND user_id IN (` + ids + `)`
		listUser, e := models.GetWxUserList(conditionuiUser, parsUser)
		if e != nil {
			err = e
			return
		}

		mapMobileUser := make(map[string]string)
		for _, v := range listUser {
			mapMobileUser[v.Mobile] = v.Mobile
		}

		var mobiles []string
		listFllow, e := cygx.GetCygxForeverUserIndustryFllowOpneidByActivityIds(activityId)
		if e != nil {
			err = e
			return
		}
		for _, v := range listFllow {
			if mapMobileUser[v.Mobile] != "" {
				mobiles = append(mobiles, v.Mobile)
			}
		}

		items, e = cygx.GetUserRecordListByMobileArr(mobiles)
		//items, e = models.GetCygxUserOpneidByUserIds(ids)
		if e != nil {
			err = e
			return
		}
	}
	return
}

// ReturnBodyRule 微信返回通过结果集
type ReturnBodyRule struct {
	ErrorCode    int    `json:"errcode,omitempty"`
	ErrorMessage string `json:"errmsg,omitempty"`
}

func init232() {
	MakeActivitySigninImg(2161)
}

// MakeActivitySigninImg 生成活动签到图片
func MakeActivitySigninImg12(activityId int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("扫码签到日志记录，失败,活动ID："+strconv.Itoa(activityId)+err.Error()+";msg:"+msg, 3)
		}
	}()
	itemToken, err := models.GetWxToken(utils.WxCygxAppId, utils.WxCygxAppSecret)
	if err != nil {
		return
	}
	if itemToken.AccessToken == "" {
		msg = "accessToken is empty"
		return
	}
	var envVersion string
	var resourceUrl string
	if utils.RunMode == "release" {
		envVersion = "release"
	} else {
		envVersion = "develop"
	}
	url := "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + itemToken.AccessToken
	method := "POST"
	payload := strings.NewReader(`{
		"page":"` + utils.WX_MSG_PATH_ACTIVITY_SIGNIN + `",
		"scene":"` + strconv.Itoa(activityId) + `",
		"env_version":"` + envVersion + `",
		"check_path":false,
		"auto_color":true
				}`)
	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)
	if err != nil {
		msg = "获取微信二维码失败,Err:" + err.Error()
		return
	}
	req.Header.Add("Content-Type", "application/json")
	postBody, err := client.Do(req)
	if err != nil {
		msg = "获取微信二维码失败,Err:" + err.Error()
		return
	}
	defer postBody.Body.Close()
	uploadDir := "static/img/share/"
	uuid := utils.GetRandStringNoSpecialChar(28)
	if !utils.FileIsExist(uploadDir) {
		err = os.MkdirAll(uploadDir, 0755)
		if err != nil {
			msg = "生成文件夹失败,Err:" + err.Error()
			return
		}
	}
	imagePath := uploadDir + uuid + ".jpg"
	switch header := postBody.Header.Get("Content-Type"); {
	case strings.HasPrefix(header, "application/json"):
		tokenResp := ReturnBodyRule{}
		decoder := json.NewDecoder(postBody.Body)
		if decodeErr := decoder.Decode(&tokenResp); decodeErr != nil {
			msg = "获取微信二维码失败,Err:" + decodeErr.Error()
			return
		}
	case strings.HasPrefix(header, "image"):
		reply, e := ioutil.ReadAll(postBody.Body)
		if e != nil {
			err = e
			msg = "获取微信二维码失败,Err:" + err.Error()
			return
		}
		imageContent, e := os.Create(imagePath)
		if e != nil {
			err = e
			msg = "获取微信二维码失败,Err:" + err.Error()
			return
		}
		writeStringRes, e := io.WriteString(imageContent, string(reply))
		if e != nil {
			err = e
			fmt.Println(writeStringRes)
			return
		}
		closeErr := imageContent.Close()
		if closeErr != nil {
			err = closeErr
			return
		}
		randStr := utils.GetRandStringNoSpecialChar(28)
		fileName := randStr + ".jpg"
		savePath := uploadDir + time.Now().Format("200601/20060102/")
		savePath += fileName
		//上传到阿里云
		err = services.UploadFileToAliyun(fileName, imagePath, savePath)
		if err != nil {
			fmt.Println("文件上传失败，Err:" + err.Error())
			return
		}
		fileHost := "https://hzstatic.hzinsights.com/"
		resourceUrl = fileHost + savePath
		defer func() {
			os.Remove(imagePath)
		}()
	default:
		msg = "生成二维码失败"
		return
	}
	fmt.Println(resourceUrl)
	return
}

// 校验报名截止时间
func CheckSiginupDeadline(activityInfo *cygx.ActivityDetail) (checkTime bool, popupMsg string) {
	checkTime = true
	if activityInfo.SiginupDeadline != utils.EmptyDateTimeStr && activityInfo.SiginupDeadline != "" {
		timeResp := utils.StrTimeToTime(activityInfo.SiginupDeadline)
		if timeResp.Before(time.Now()) {
			checkTime = false
			popupMsg = "该活动已截止报名"
		}
	}
	return
}

// 校验报名点数
func CheckActivityPoints(activityInfo *cygx.ActivityDetail, wxUser *models.WxUser) (checkPoints bool, popupMsg, companyPoints, activityPoints string, err error) {
	checkPoints = true
	if activityInfo.IsResearchPoints == 1 {
		//获取活动对用户要扣的点
		userPointsNum, e := cygx.GetCygxActivityPointsSetUserNum(activityInfo.ActivityId)
		if e != nil {
			err = errors.New("GetCygxActivityPointsSetUserNum, Err: " + e.Error())
			return
		}
		// 获取用户所在公司剩余的点
		companyPointsNum, e := cygx.GetCompanyPoints(wxUser.CompanyId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCompanyPoints, Err: " + e.Error())
			return
		}
		if companyPointsNum-userPointsNum < 0 {
			checkPoints = false
			popupMsg = "点数不足"
		}
		companyPoints = fmt.Sprint(companyPointsNum)
		activityPoints = fmt.Sprint(userPointsNum)
	}
	return
}

// 校验报名是否需要绑定邮箱
func CheckActivityUserEmail(activityInfo *cygx.ActivityDetail, wxUser *models.WxUser) (checkEmail bool, popupMsg string) {
	checkEmail = true
	if activityInfo.IsNeedEmail == 1 {
		if wxUser.Email == "" {
			checkEmail = false
			popupMsg = "应上市公司要求，该会议报名需\n提供邮箱，用户邮箱为空"
		}
	}
	return
}

// 校验报名顺序 截止时间>点数>邮箱
func CheckActivityUserAll(activityInfo *cygx.ActivityDetail, wxUser *models.WxUser) (popupMsg string, err error) {
	_, popupMsg = CheckSiginupDeadline(activityInfo)
	if popupMsg != "" {
		return
	}
	_, popupMsg, _, _, err = CheckActivityPoints(activityInfo, wxUser)
	if popupMsg != "" {
		return
	}
	_, popupMsg = CheckActivityUserEmail(activityInfo, wxUser)
	if popupMsg != "" {
		return
	}
	return
}
