package redis_data

import (
	"encoding/base64"
	"encoding/json"
	"github.com/gomodule/redigo/redis"
	"miads/adslib/ads_redis"
	"miads/adslib/graylog"
	"miads/adslib/utils"
	"strings"
)

type AdOrderInfo struct {
	BeginTime       int64  `json:"begin_time"`
	Channel         string `json:"channel"`
	City            string `json:"city"`
	ClickKpi        int64  `json:"click_kpi"`
	ClickURL        string `json:"click_url"`
	EndTime         int64  `json:"end_time"`
	ImeiReplaceFlag int64  `json:"imei_replace_flag"`
	JsOrderID       int64  `json:"js_order_id"`
	Level           int64  `json:"level"`
	LineType        int64  `json:"line_type"`
	NewRegionFlag   string `json:"new_region_flag"`
	NoCity          string `json:"no_city"`
	NoProvince      string `json:"no_province"`
	OrderID         int64  `json:"order_id"`
	OrderType       int64  `json:"order_type"`
	Province        string `json:"province"`
	RegionFlag      int64  `json:"region_flag"`
	RegionInfo      string `json:"region_info"`
	ShowKpi         int64  `json:"show_kpi"`
	ShowURL         string `json:"show_url"`
	TargetURL       string `json:"target_url"`
	Title           string `json:"title"`
}

func getOrderIds() ([]string, error) {
	conn := ads_redis.RedisConn.Get()
	defer conn.Close()

	rsp, err := conn.Do("SMEMBERS", "order_key")
	if err != nil {
		return []string{}, err
	}

	if rsp == nil {
		return []string{}, err
	}

	orderIds, _ := redis.Strings(rsp, err)
	return orderIds, nil
}

func getOrderInfo(id string) (*AdOrderInfo, error) {
	conn := ads_redis.RedisConn.Get()
	defer conn.Close()

	rsp, err := conn.Do("GET", id)
	if err != nil {
		return nil, err
	}

	if rsp == nil {
		return nil, err
	}

	orderBase64Str, _ := redis.String(rsp, err)
	orderByte, err := base64.StdEncoding.DecodeString(orderBase64Str)
	if err != nil {
		return nil, err
	}

	a := AdOrderInfo{}
	err = json.Unmarshal(orderByte, &a)
	if err != nil {
		return nil, err
	}
	return &a, nil
}

func GetOrderInfos(dsp *utils.DspParam, fixFlag int) ([]AdOrderInfo, error) {
	orderIds, err := getOrderIds()
	if err != nil {
		return []AdOrderInfo{}, err
	}

	orders := make([]AdOrderInfo, 0, 50)
	for _, id := range orderIds {
		order, err := getOrderInfo(id)
		if err != nil {
			continue
		}

		if order == nil {
			continue
		}

		needInsert := true
		areaFlag := 0 // 0 通投 1 定投

		if dsp != nil {
			// 判断是否要做渠道剔除
			channelStr := order.Channel
			if channelStr != "" {
				channelArr := strings.Split(channelStr, ",")
				isValidChannel := false
				for _, channel := range channelArr {
					if dsp.ReqSource == channel {
						isValidChannel = true
					}
				}
				if !isValidChannel {
					continue
				}
			}

			newRegionFlagStr := order.NewRegionFlag
			newRegionFlagArr := strings.Split(newRegionFlagStr, ",")
			for _, regionFlag := range newRegionFlagArr {
				if regionFlag == "1" {
					// 对省定投
					if strings.Index(order.Province, dsp.Province) == -1 {
						needInsert = false
						break
					}
				} else if regionFlag == "2" {
					// 对市定投
					if strings.Index(order.City, dsp.City) == -1 {
						needInsert = false
						break
					}
				} else if regionFlag == "3" {
					// 对省禁投
					if order.NoProvince != "" && strings.Index(order.NoProvince, dsp.Province) != -1 {
						needInsert = false
						break
					}
				} else if regionFlag == "4" {
					// 对市禁投
					if order.NoCity != "" && strings.Index(order.NoCity, dsp.City) != -1 {
						needInsert = false
						break
					}
				} else {
					continue
				}

				areaFlag = 1
			}
		}

		if !needInsert {
			return []AdOrderInfo{}, nil
		}

		if dsp != nil {
			grayLogData := struct {
				Ip              string
				ShortMessage    string `json:"short_message"`
				ReqSource       string `json:"req_source"`
				Province        string
				City            string
				OrderId         int64  `json:"order_id"`
				orderProvince   string `json:"order_province"`
				orderCity       string `json:"order_city"`
				orderNoProvince string `json:"order_no_province"`
				orderNoCity     string `json:"order_no_city"`
			}{
				Ip:              dsp.Ip,
				ShortMessage:    "area_result_v2",
				ReqSource:       dsp.ReqSource,
				Province:        dsp.Province,
				City:            dsp.City,
				OrderId:         order.OrderID,
				orderProvince:   order.Province,
				orderCity:       order.City,
				orderNoProvince: order.NoProvince,
				orderNoCity:     order.NoCity,
			}
			graylog.Log(grayLogData)
		}

		if fixFlag == 0 && areaFlag == 0 {
			orders = append(orders, *order)
		} else if fixFlag == 1 && areaFlag == 1 {
			orders = append(orders, *order)
		} else if fixFlag == -1 {
			orders = append(orders, *order)
		}
	}

	return orders, nil
}