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 := crmFindLeadByOpenID(openID)

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

	//existing user
	if found {
		crmLeadSetStatusNew(info.ID)
		sendGreeting4ExistingUser(in, info)
	} else { //new user
		//get user info from wechat
		crmCreateLeadByOpenID(openID)
		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 crmdLead) {

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

}

func (m *WechatUserInfo) registerNewLeadWithInfo(openID string) (newuser crmdLead, err error) {

	u := crmdLead{}
	u.FirstName = "\u0020" //a visible space
	if m.NickName == "" {
		u.LastName = time.Now().Format(getCrmTimeLayout())
	} else {
		u.LastName = m.NickName
	}
	u.Password = "password"
	u.WechatHitxyID = openID
	u.Status = "New"
	u.AvatarID, _ = m.uploadAvatar()

	data, _ := json.Marshal(u)
	entity, err := crmCreateEntity("Lead", data)
	if err == nil {
		newuser = entity.(crmdLead)
	}
	return
}

func (m *WechatUserInfo) uploadAvatar() (avatarID string, err error) {
	tmpfile, _, err := saveURL(m.Avatar)
	if err != nil {
		return
	}
	attach, err := crmCreateAttachment(tmpfile)
	if err != nil {
		return
	}
	avatarID = attach.ID
	return
}

//when user left
func onUnSubscribe(in *InWechatMsg) {
	info, found, err := crmFindLeadByOpenID(in.header.FromUserName)

	if err != nil {
		log.Printf("Error happened when trying to unsubscribe a user %s", in.header.FromUserName)
		log.Println(err)
	}
	if found == false {
		log.Printf("not found openid %s", in.header.FromUserName)
		return
	}
	//mark status
	newStatus := crmdLead{}
	newStatus.ID = info.ID
	newStatus.Status = "Dead"
	crmPatchLeadInfo(newStatus)
}
