package main

import (
	"fmt"
	"log"
	"strings"
)

type procSearchMemberDef struct {
	chatProcedureID
}

var procSearchMember = procSearchMemberDef{}

func (m *procSearchMemberDef) init(ss *openIDSessionData) {
	ss.Procedure = m.getID()
	ss.refreshExpire(600)
}

func (m *procSearchMemberDef) clean(ss *openIDSessionData) {
	ss.Procedure = ""
}

func (m *procSearchMemberDef) start(ss *openIDSessionData, in *InWechatMsg) {

}

func (m *procSearchMemberDef) serve(ss *openIDSessionData, in *InWechatMsg) (processed bool) {
	switch msg := in.body.(type) {
	case TextMsg:
		msg.Content = strings.TrimSpace(msg.Content)
		if m.endingCommand(ss, msg.Content) {
			return
		}
		str, _ := BuildTextMsg(ss.OpenID, "搜索 "+msg.Content+"... ...")
		in.replyXML(str)
		m.displayUserInfo(ss, msg.Content)
		processed = true
	case PicMsg:
		//str := buildPicMsg(ss.OpenID, msg.MediaId)
		in.transfer2KF()
		kfSendPicByMediaID(ss.OpenID, msg.MediaId)
		kfSendTxt(ss.OpenID, "已转接校友会理事会，稍后答复您")
		processed = true
	case VoiceMsg:
		name := strings.TrimSuffix(msg.Recognition, "。")
		str, _ := BuildTextMsg(ss.OpenID, "搜索 "+name+"... ...")
		in.replyXML(str)
		m.displayUserInfo(ss, name)
		processed = true
	case EventMsg:
		processed = true
		if msg.Event == "LOCATION" {
			onLocation(in)
		}
		if msg.Event == "CLICK" {
			processed = false //we might need to process other menu command.
		}
	default:
		str := fmt.Sprintf("搜索功能结束")
		kfSendTxtAs(ss.OpenID, str, "孙鹏")
		processed = false
	}
	return
}
func (m *procSearchMemberDef) summary(ss *openIDSessionData) {

}

func (m *procSearchMemberDef) intro(ss *openIDSessionData, in *InWechatMsg) {
	msg := "请输入（读出）他/她的姓名或者照片"
	in.replyText("")
	kfSendTxtAs(ss.OpenID, msg, "孙鹏")
}

func (m *procSearchMemberDef) displayUserInfo(ss *openIDSessionData, name string) {
	total, list, err := crmFindEntityByAttr("Lead", "lastName", name)
	if total <= 0 || err != nil {
		kfSendTxtAs(ss.OpenID, "很抱歉，没有找到相关信息", "孙鹏")
		return
	}

	search, ok := list.([]crmdLead)
	if !ok {
		log.Printf("ERROR: 搜索 %s 结果异常, total=%d, ", name, total)
		kfSendTxt(ss.OpenID, "很抱歉，没有找到相关信息")
		return
	}
	for _, v := range search {
		articles := []sendNewsArticle{}
		//main photo
		articles = append(articles, v.getBasicUserInfoPhoto())
		//email
		articles = append(articles, v.getBasicUserInfoEmail())
		//phone
		articles = append(articles, v.getBasicUserInfoPhone())
		kfSendNews(ss.OpenID, "总标题", "总描述", articles)

		if v.Description != "" {
			msg := fmt.Sprintf("%s简介:%s\n", name, v.Description)
			kfSendTxtAs(ss.OpenID, msg, "孙鹏")
		}

	}
	ss.refreshExpire(600)
}

func (m *procSearchMemberDef) endingCommand(ss *openIDSessionData, cmd string) (stop bool) {
	stop = false

	if cmd == "结束" || cmd == "." || cmd == "。" {
		stop = true
		m.clean(ss)
		str := fmt.Sprintf("搜索功能结束")
		kfSendTxtAs(ss.OpenID, str, "孙鹏")
	}

	return
}
