package utils

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"encoding/json"
	"fmt"
	extConfig "go-admin/config"
	"io/ioutil"
	"math/rand"
	"net/http"
	"strings"
	"time"
)

type Send struct {
	Phone      string `json:"phone" description:"手机号"`
	Content    string `json:"content" description:"发送的内容、注意需要携带短信签名 【】"`
	AreaCode   string `json:"area_code" description:"区号"`
	Source     int    `json:"source" description:"来源 1:谛宝多多 2:谛宝医生 3:收银台 4:谛宠有品 5:CRM 6:谛赋"`
	SourceName string `json:"source_name" description:"业务子系统名称 业务系统自定义"`
}

type SendReply struct {
	Status  int64       `json:"Status" description:"状态码"`
	Message string      `json:"Message" description:"信息"`
	Data    interface{} `json:"Data" description:"数据"`
}

//生成随机6位数字
func CreateCaptcha() string {
	return fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
}

func SendMobileMsg(phone string, smsText string) *SendReply {
	var tModel Send

	tModel.AreaCode = "86"
	tModel.Phone = phone
	tModel.Content = extConfig.ExtConfig.Sms.Sign + smsText
	tModel.Source = extConfig.ExtConfig.Sms.Source
	tModel.SourceName = extConfig.ExtConfig.Sms.Sourcename

	b, _ := json.Marshal(tModel)

	sign, _ := MsgAesEncrypt(b, []byte("dbc2021888000000"))

	url := extConfig.ExtConfig.Sms.Url
	client := &http.Client{}
	reqSms, err := http.NewRequest("POST", url, bytes.NewReader(b))
	if err != nil {
		panic(err)
	}

	reqSms.Header.Set("Content-Type", "application/json")
	reqSms.Header.Set("sign", sign)

	resp, err := client.Do(reqSms)
	if err != nil {
		panic(err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	fmt.Println("body: ", string(body))

	reply := new(SendReply)
	UnserislizeJson(string(body), reply)
	return reply
}

//Aes 对称加密
func MsgAesEncrypt(origData, key []byte) (string, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	blockSize := block.BlockSize()
	origData = MsgPKCS7Padding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	result := base64.StdEncoding.EncodeToString(crypted)
	return result, nil
}

//Aes 对称解密
func MsgAesDecrypt(crypted, key []byte) (string, error) {

	ciphertext := strings.Replace(string(crypted), " ", "", -1)
	cryptedOri, err := base64.StdEncoding.DecodeString(ciphertext)

	if err != nil {
		return "", err
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData := make([]byte, len(cryptedOri))
	blockMode.CryptBlocks(origData, cryptedOri)
	origData = MsgPKCS7UnPadding(origData)
	return string(origData), nil
}

func MsgPKCS7Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func MsgPKCS7UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
