package org.mp.api.custservice.multicustservice;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.mp.api.core.common.JSONHelper;
import org.mp.api.core.common.WxstoreUtils;
import org.mp.api.custservice.multicustservice.model.ChatRecord;
import org.mp.api.custservice.multicustservice.model.CustService;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 客户服务- 多客户
 * 
 * @author caojm
 */
public class JwMultiCustomerAPI {

    //转发多客户端类型
    private final static String TRANSFER_CUSTOMER_SERVICE = "transfer_customer_service";
    
    // 获取在线客服接待信息
    private static String GET_ONLINE_CUSTSEVICE_URL = "https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=ACCESS_TOKEN";
    
    //获取客服记录列表
    private static String GET_CUSTSEVICE_ROCORD_LIST_URL = "https://api.weixin.qq.com/cgi-bin/customservice/getrecord?access_token=ACCESS_TOKEN";

    //获取客服基础信息列表
    public static String GET_CUSTSERVICE_INFO_LIST_URL = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=ACCESS_TOKEN";

    //添加客服账号
    public static String ADD_CUSTSERVICE_ACCOUNT_URL = "https://api.weixin.qq.com/customservice/kfaccount/add?access_token=ACCESS_TOKEN";

    //设置客服信息
    public static String UPDATE_CUSTSERVICE_INFO_URL = "https://api.weixin.qq.com/customservice/kfaccount/update?access_token=ACCESS_TOKEN";

    //上传客服头像
    public static String UPLOAD_HANDAVATAR_URL = "https://api.weixin.qq.com/customservice/kfaccount/uploadheadimg?access_token=ACCESS_TOKEN&kf_account=KFACCOUNT";

    //删除客服账号
    public static String DEL_CUSTSERVICE_INFO_URL = "https://api.weixin.qq.com/customservice/kfaccount/del?access_token=ACCESS_TOKEN&kf_account=KFACCOUNT";

    //创建客服会话
    public static String CREATE_CUSTSERVICE_SESSION_URL = "https://api.weixin.qq.com/customservice/kfsession/create?access_token=ACCESS_TOKEN";

    //关闭客户会话
    public static String CLOSE_CUSTSERVICE_SESSION_URL = "https://api.weixin.qq.com/customservice/kfsession/close?access_token=ACCESS_TOKEN";

    //获取客户会话状态
    public static String GET_CUSTSERVCIE_SESSIONSTATUS_URL = "https://api.weixin.qq.com/customservice/kfsession/getsession?access_token=ACCESS_TOKEN&openid=OPENID";

    //获取客户会话列表
    public static String GET_CUSTSERVCIE_SESSION_LIST_URL = "https://api.weixin.qq.com/customservice/kfsession/getsessionlist?access_token=ACCESS_TOKEN&kf_account=KFACCOUNT";

    //获取未接入会话列表
    public static String GET_NOACCESS_SESSION_LIST_URL = "https://api.weixin.qq.com/customservice/kfsession/getwaitcase?access_token=ACCESS_TOKEN";

    /**
     * 获取转发多客服的响应消息
     * @param toUserName
     * @param fromUserName
     * @return
     */
    public String getMultiCustServcieMessage(String toUserName, String fromUserName) {
        StringBuilder custServiceMessage = new StringBuilder();  
        custServiceMessage.append("<xml>");  
        custServiceMessage.append("<ToUserName><![CDATA["+toUserName+"]]></ToUserName>");  
        custServiceMessage.append("<FromUserName><![CDATA["+fromUserName+"]]></FromUserName>");  
        custServiceMessage.append("<CreateTime>"+new Date().getTime()+"</CreateTime>");  
        custServiceMessage.append("<MsgType><![CDATA["+TRANSFER_CUSTOMER_SERVICE+"]]></MsgType>"); 
        custServiceMessage.append("</xml>");  
        return custServiceMessage.toString(); 
    }
    
    /**
     * 获取指定客服的响应消息
     * @param accessToken
     * @param toUserName
     * @param fromUserName
     * @param kfAccount
     * @return
     */
    public String getSpecCustServcie(String accessToken,String toUserName,String fromUserName,String kfAccount) {
        if(isOnlineCustServiceAvailable(accessToken,kfAccount)){
            StringBuilder custServiceMessage = new StringBuilder();  
            custServiceMessage.append("<xml>");  
            custServiceMessage.append("<ToUserName><![CDATA["+toUserName+"]]></ToUserName>");  
            custServiceMessage.append("<FromUserName><![CDATA["+fromUserName+"]]></FromUserName>");  
            custServiceMessage.append("<CreateTime>"+new Date().getTime()+"</CreateTime>");  
            custServiceMessage.append("<MsgType><![CDATA["+TRANSFER_CUSTOMER_SERVICE+"]]></MsgType>"); 
            custServiceMessage.append("<TransInfo>");  
            custServiceMessage.append("<KfAccount><![CDATA["+kfAccount+"]]></KfAccount>");
            custServiceMessage.append("</TransInfo>");  
            custServiceMessage.append("</xml>");  
            return custServiceMessage.toString();             
        }else{
            return null;
        }

    }
    
    /**
     * 判断指定客服是否在线可用
     * @param accessToken
     * @param kfAccount
     * @return
     */
    public boolean isOnlineCustServiceAvailable(String accessToken,String kfAccount) {
        List<CustService> custServices = null;
        if (accessToken != null) {
            String requestUrl = GET_ONLINE_CUSTSEVICE_URL.replace("ACCESS_TOKEN", accessToken);
            JSONObject result = WxstoreUtils.httpRequest(requestUrl, "GET", null);
            if(result != null){
                JSONArray info = result.getJSONArray("kf_online_list");
                custServices = JSONHelper.toList(info, CustService.class);
            }
        }
       
        if(custServices!=null&&!custServices.isEmpty()){
            for(Iterator<CustService> it = custServices.iterator();it.hasNext();){
                CustService custService = (CustService)it.next();
                //不在线、没有开启自动接入或者自动接入已满,都返回不可用
                if (custService != null && custService.getKfAccount().equals(kfAccount)
                        && custService.getAutoAccept() > 0
                        && custService.getAutoAccept()>custService.getAcceptedCase()){
                    return true;
                }
            }
        }

        return false;
        
    }

    /**
     * 获取客服聊天记录列表
     * @param accessToken
     * @param openId
     * @param startTime
     * @param endTime
     * @param pageSize
     * @param pageIndex
     * @return
     */
    public List<ChatRecord> getCustServiceRecordList(String accessToken,String openId,long startTime,long endTime,int pageSize,int pageIndex) {
        List<ChatRecord> chatRecods = null;
        if (accessToken != null && startTime >= 0 && endTime >=0 && pageSize>=0 && pageIndex>0 ) {
            String requestUrl = GET_CUSTSEVICE_ROCORD_LIST_URL.replace("ACCESS_TOKEN", accessToken);
            StringBuilder jsonStrBuilder = new StringBuilder(); 
            
            jsonStrBuilder.append("{");  
            jsonStrBuilder.append("\"starttime\":"+startTime+",");  
            jsonStrBuilder.append("\"endtime\":"+endTime+",");  
            if(openId!=null && !openId.equals("")){
                jsonStrBuilder.append("\"openid\":\""+openId+"\",");
            }
            jsonStrBuilder.append("\"pagesize\":"+pageSize+",");  
            jsonStrBuilder.append("\"pageindex\":"+pageIndex+",");  
            jsonStrBuilder.append("}");              
            
            JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", jsonStrBuilder.toString());
            if(result != null){
                JSONArray info = result.getJSONArray("recordlist");
                chatRecods = JSONHelper.toList(info, ChatRecord.class);
            }
            return chatRecods;
        }
        return null;
    }
}
