// util
package util

import (
	"fmt"
	"io/ioutil"
	"math/rand"
	"os"
	"qfw/util"
	"regexp"
	"strconv"
	"strings"
	"time"

	//"unicode/utf8"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

var regNum *regexp.Regexp

func init() {
	regNum, _ = regexp.Compile("(\\d+)")
}

func Getrand(num int) int {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	return r.Intn(num)
}

func GetConfigIndexLen(key string) (int, string) {
	indexArr := regNum.FindAllStringSubmatch(key, -1)
	if len(indexArr) > 0 {
		return len(indexArr[0][0]), indexArr[0][0]
	} else {
		return 0, ""
	}
}

func ObjToFloat(data interface{}, position int) interface{} {
	tmp, err := strconv.ParseFloat(fmt.Sprint(data), 64)
	if err != nil {
		return 0
	} else {
		tmp, err = strconv.ParseFloat(strconv.FormatFloat(tmp, 'f', position, 64), 64)
		if err != nil {
			return 0
		} else {
			return tmp
		}
	}
}

var (
	numberReg = regexp.MustCompile("[一二三四五六七八九十0-9]+")
)

//
func ToNumber(value string, defaultNum int) int {
	value = numberReg.FindString(value)
	if value == "" {
		return defaultNum
	}
	v := ChineseNumberToInt(value)
	if v < 1 {
		v, _ = strconv.Atoi(value)
	}
	if v > 0 {
		return v
	}
	return defaultNum
}

//中文数字转换
func ChineseNumberToInt(value string) int {
	result, temp, count := 0, 1, 0
	cnArr := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
	chArr := []string{"十", "百", "千", "万", "亿"}
	for i, v := range []rune(value) {
		b := true //判断是否是chArr
		c := string(v)
		for j, cv := range cnArr { //非单位，即数字
			if c == cv {
				if 0 != count { //添加下一个单位之前，先把上一个单位值添加到结果中
					result += temp
					temp = 1
					count = 0
				}
				// 下标+1，就是对应的值
				temp = j + 1
				b = false
				break
			}
		}
		if b { //单位{'十','百','千','万','亿'}
			for j, cv := range chArr {
				if c == cv {
					b = false
					switch j {
					case 0:
						temp *= 10
						break
					case 1:
						temp *= 100
						break
					case 2:
						temp *= 1000
						break
					case 3:
						temp *= 10000
						break
					case 4:
						temp *= 100000000
						break
					default:
						break
					}
					count++
				}
			}
		}
		if b {
			return -1
		}
		if i == len([]rune(value))-1 { //遍历到最后一个字符
			result += temp
		}
	}
	return result
}

const (
	conStr = "([\\s\u3000\u2003\u00a0]+|\\\\t)" //所有空格
)

var (
	ALLReg          = regexp.MustCompile(conStr)
	ConvertIntReg_1 = regexp.MustCompile("^[一二三四五六七八九十0-9]+$")
	ConvertIntReg_2 = regexp.MustCompile("^[a-zA-Z0-9\\-]+$")
	ConvertIntReg_3 = regexp.MustCompile("^[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]+$")
	ConvertIntReg_4 = regexp.MustCompile("^[①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳]$")
	//标段号，包号转换
	FindPkgNumReg = regexp.MustCompile("([一二三四五六七八九十0-9A-Za-zⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳\\-]+)|(设计|施工|监理|验收)")
)

func PackageNumberConvert(val string) string {
	result := val
	weight := 0
	for _, value := range strings.Split(val, "/") {
		if weight == 0 {
			result = value
		}
		value = ALLReg.ReplaceAllString(value, "")
		value = strings.TrimLeft(value, "0")
		value = FindPkgNumReg.FindString(value)
		if ConvertIntReg_1.MatchString(value) {
			result = value
			if v := ChineseNumberToInt(value); v != -1 {
				result = strconv.Itoa(v)
				break
			}
		} else if ConvertIntReg_2.MatchString(value) {
			if weight == 0 {
				result = strings.ToUpper(value)
				weight = -1
			}
		} else if ConvertIntReg_3.MatchString(value) {
			if v := romeNumberToInt(value); v != -1 {
				result = strconv.Itoa(v)
				break
			}
		} else if ConvertIntReg_4.MatchString(value) {
			if v := circleNumberToInt(value); v != -1 {
				result = strconv.Itoa(v)
				break
			}
		}
	}
	return result
}

//罗马数字转换
func romeNumberToInt(value string) int {
	for k, v := range []rune("ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ") {
		if value == string(v) {
			return k + 1
		}
	}
	return -1
}

//带圆圈的数字换行
func circleNumberToInt(value string) int {
	for k, v := range []rune("①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳") {
		if value == string(v) {
			return k + 1
		}
	}
	return -1
}

//oss
var (
	ossEndpoint        = "oss-cn-beijing-internal.aliyuncs.com" //正式环境用：oss-cn-beijing-internal.aliyuncs.com 测试：oss-cn-beijing.aliyuncs.com
	ossAccessKeyId     = "LTAI4G5x9aoZx8dDamQ7vfZi"
	ossAccessKeySecret = "Bk98FsbPYXcJe72n1bG3Ssf73acuNh"
	ossBucketName      = "topjy"
	ossclient          *oss.Client
)

func InitOss() {
	client, err := oss.New(ossEndpoint, ossAccessKeyId, ossAccessKeySecret)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	ossclient = client
}

func OssGetObject(objectName string) string {
	util.Catch()
	// 获取存储空间。
	bucket, err := ossclient.Bucket(ossBucketName)
	if err != nil {
		fmt.Println("Error:", err)
		return ""
	}

	// 下载文件到流。
	body, err := bucket.GetObject(objectName)
	if err != nil {
		fmt.Println("Error:", err)
		return ""
	}
	defer body.Close()
	data, err := ioutil.ReadAll(body)
	if err != nil {
		fmt.Println("Error:", err)
		return ""
	}
	return string(data)
}

func GetFileText(tmp map[string]interface{}) (filetext string) {
	fn_url := map[string]string{}
	if projectinfo, ok := tmp["projectinfo"].(map[string]interface{}); ok && projectinfo != nil {
		if attachments, ok := projectinfo["attachments"].(map[string]interface{}); ok && attachments != nil {
			for _, info := range attachments {
				if infoMap, ok := info.(map[string]interface{}); ok && infoMap != nil {
					filename := util.ObjToString(infoMap["filename"])
					org_url := util.ObjToString(infoMap["org_url"])
					fn_url[filename] = org_url
				}
			}
		}
	}

	if len(fn_url) > 0 {
		index := 1
		if attchMap, ok := tmp["attach_text"].(map[string]interface{}); attchMap != nil && ok {
			for fn, url := range fn_url {
				href := fmt.Sprint(index) + ".<a href=" + url + " target='_blank'>" + fn + "</a>\n<br/>"
				onetext := ""
				for _, tmpData1 := range attchMap {
					if tmpData2, ok := tmpData1.(map[string]interface{}); tmpData2 != nil && ok {
						for _, result := range tmpData2 {
							if resultMap, ok := result.(map[string]interface{}); resultMap != nil && ok {
								file_name := util.ObjToString(resultMap["file_name"])
								if fn == file_name { //找到对应的附件
									if attach_url := util.ObjToString(resultMap["attach_url"]); attach_url != "" {
										onetext = OssGetObject(attach_url) + "\n<br/>" //oss读数据
										goto L
									}
								}
							}
						}
					}
				}
			L:
				filetext += href + onetext
				index++
			}
		}
	}
	/**
	if attchMap, ok := tmp["attach_text"].(map[string]interface{}); attchMap != nil && ok {
		for _, tmpData1 := range attchMap {
			if tmpData2, ok := tmpData1.(map[string]interface{}); tmpData2 != nil && ok {
				for _, result := range tmpData2 {
					if resultMap, ok := result.(map[string]interface{}); resultMap != nil && ok {
						if attach_url := util.ObjToString(resultMap["attach_url"]); attach_url != "" {
							bs := OssGetObject(attach_url) //oss读数据
							if utf8.RuneCountInString(filetext+bs) < 50000 {
								filetext += bs + "\n"
							} else {
								break
							}
						}
					}
				}
			}
		}
	}
	*/
	return
}
