package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

func onSubscribe(in InWechatMsg) {
	openID := in.header.FromUserName
	//check whether we have his own record in the CRM system
	info, found, err := crmFindOpenID(openID)

	if err != nil {
		log.Println(err)
		return
	}

	//existing user
	if found {
		sendGreeting4ExistingUser(in, info)
	} else { //new user
		//get user info from wechat
		info := WechatUserInfo{}
		info.getUserInfo(openID, "zh_CN")
		info.registerNewUserWithInfo(in)
		in.askUserFillupBasicInfo()
	}
	//some error happened

}

//WechatUserInfo response for wechat user info.
type WechatUserInfo struct {
	Subscribe     int32   `json:"subscribe"`
	OpenID        string  `json:"openid"`
	NickName      string  `json:"nickname"`
	Sex           int32   `json:"sex"` //0 未知 1 男 2 女
	Language      string  `json:"language"`
	City          string  `json:"city"`
	Province      string  `json:"province"`
	Country       string  `json:"country"`
	Avatar        string  `json:"headimgurl"`
	SubscribeTime int32   `json:"subscribe_time"`
	UnionID       string  `json:"unionid"`
	Remark        string  `json:"remark"`
	GroupID       int32   `json:"groupid"`
	TagIDList     []int32 `json:"tagid_list"`
}

func (m *WechatUserInfo) getUserInfo(openID string, lang string) (err error) {
	url := m.getURL(openID, lang)
	resp, err := http.Get(url)
	if err != nil {
		*m = WechatUserInfo{}
		return err
	}
	b, err := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(b, m)
	return nil
}

//lang 返回国家地区语言版本，zh_CN 简体，zh_TW 繁体，en 英语
func (m *WechatUserInfo) getURL(openID, lang string) string {
	if lang != "zh_CN" && lang != "zh_TW" && lang != "en" {
		log.Printf("WechatUserInfo/getURL: Unknow Lang %s, change to zh_CN", lang)
		lang = "zh_CN"
	}
	atk, _ := GetAccessToken()
	u := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=%s", atk, openID, lang)
	return u
}

func (m *WechatUserInfo) save2CRM() {

}

func (in *InWechatMsg) askUserFillupBasicInfo() {
	first := "欢迎加入海外学子之家，这里凝聚着哈工大人在澳洲的，勤奋，努力和奋斗"
	url := "http://wechat.hitxy.org.au/profile_newly_register"
	remark := "您是首次加入本社区，请点击详情完善您的个人资料"
	communityName := "哈工大澳洲校友会"
	joinDate := time.Now().Format("2006-Jan-02")
	templateSendJoinCommunity(in.header.FromUserName, url, first, remark, communityName, joinDate)
}

func sendGreeting4ExistingUser(in InWechatMsg, info crmLeadInfo) {

	first := "欢迎" + info.Name + "返回澳洲校友会"
	url := "http://wechat.hitxy.org.au/profile_newly_register"
	remark := ""
	communityName := "哈工大澳洲校友会"
	joinDate := info.getCreatedAt().Format("2006-Jan-02")
	templateSendJoinCommunity(in.header.FromUserName, url, first, remark, communityName, joinDate)

}

func (m *WechatUserInfo) registerNewUserWithInfo(in InWechatMsg) {
	u := crmLeadInfo{}
	u.FirstName = "\u0020"
	u.LastName = m.NickName
	u.Password = "password"
	u.WechatHitxyID = in.header.FromUserName
	u.Status = "New"

	data, _ := json.Marshal(u)
	url := "https://c.hitxy.org.au/api/v1/Lead"
	headers := crmPrepareLeadUploadHTTPHeader()
	resp, err := postRAW(data, url, headers)
	log.Println(resp)
	log.Println(err)
}
