package com.house365.web;

import com.google.common.base.Strings;
import com.house365.common.util.RestTemplateBean;
import com.house365.config.HgsProp;
import com.house365.config.WeChatProperties;
import com.house365.service.interfaces.WechatClient;
import com.house365.util.AesException;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Date: 2017/1/9</p>
 *
 * @author XN
 * @version 1.0
 */
@Controller
@EnableAutoConfiguration
@RequestMapping("user")
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    WechatClient wechatClient;
    @Autowired
    private HgsProp hgsProp;
    @Autowired
    private WeChatProperties weChatProperties;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(HttpServletRequest request, Model model) {
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        List<NameValuePair> params = new ArrayList<>();

        params.add(new BasicNameValuePair("serviceCode", "Hgs"));
        params.add(new BasicNameValuePair("serviceName", "users"));

        try {
            String result = RestTemplateBean.doGet("http://localhost:8080/house365-hgs-web/rest/interface", params);

            if (StringUtils.isNoneBlank(result)) {
                JSONObject users = JSONObject.fromObject(result).getJSONObject("data");
                model.addAttribute("list", users.getJSONArray("list"));
                model.addAttribute("records", users.getJSONArray("list").size());
            }
        } catch (URISyntaxException e) {
            logger.error(e.getMessage(), e);
        }
        return "config/user";
    }

    @RequestMapping(value = "evaluateUser", method = RequestMethod.GET)
    public String evaluateUser(HttpServletRequest request, String projectName, String projectId,
                               String seeDate, String customerName, String channel, Model model) {
        model.addAttribute("projectName", projectName);
        model.addAttribute("projectId", projectId);
        model.addAttribute("seeDate", seeDate);
        model.addAttribute("customerName", customerName);
        model.addAttribute("channel", channel);

        String requestUrl = request.getScheme() //当前链接使用的协议
                + "://" + request.getServerName()//服务器地址
                + request.getContextPath() //应用名称，如果应用名称为
                + request.getServletPath() //请求的相对url
                + "?" + request.getQueryString(); //请求参数

        model.addAttribute("requestUrl", requestUrl);

        List<NameValuePair> params = getParams("getUserInfo", request);
        String result = null;
        try {
            result = RestTemplateBean.doGet(hgsProp.getHgsUrl(), params);
            logger.info(result);
            JSONObject obj = getData(result);
            model.addAttribute("user", obj.get("entity"));
        } catch (URISyntaxException e) {
            logger.error(e.getMessage());
        }
        return "wechat/evaluateUser";
    }

    @RequestMapping(value = "evaluateUserProjectSelect", method = RequestMethod.GET)
    public String evaluateUserProjectSelect(HttpServletRequest request, String projectName, String projectId,
                                            String seeDate, String customerName, Model model) {
        model.addAttribute("projectName", projectName);
        model.addAttribute("projectId", projectId);
        model.addAttribute("seeDate", seeDate);
        model.addAttribute("customerName", customerName);

        List<NameValuePair> params = getParams("getUserInfo", request);
        String result = null;
        try {
            result = RestTemplateBean.doGet(hgsProp.getHgsUrl(), params);
            logger.info(result);
            JSONObject obj = getData(result);
            model.addAttribute("user", obj.get("entity"));
        } catch (URISyntaxException e) {
            logger.error(e.getMessage());
        }
        return "wechat/evaluateUserProjectSelect";
    }

    /**
     * 获取分享链接
     *
     * @param projectId    项目id
     * @param projectName  项目名称
     * @param seeDate      带看日期
     * @param customerName 客户称呼
     * @return
     */
    @RequestMapping(value = "/getShareUrl", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getShareUrl(HttpServletRequest request, String projectId, String projectName,
                              String seeDate, String customerName, String requestUrl, String userId, String userName, String channel) {
        //获取jsapi ticket
//        String jsapiTicket = wechatClient.getJsapiTicket(weChatProperties.getCorpId(),
//                weChatProperties.getSecret());
        JSONObject result = new JSONObject();
        try {
//            String nonceStr = "Wm3WZYTPz0wzccnW";
//            String timestamp = String.valueOf(System.currentTimeMillis()).substring(0, 10);
            //获取评论记录id
            String evaluateLogId = "0";

            List<NameValuePair> params = getParams("addEvaluateLog", request);
            params.add(new BasicNameValuePair("projectId", projectId));
            params.add(new BasicNameValuePair("projectName", projectName));
            params.add(new BasicNameValuePair("seeDate", seeDate));
            params.add(new BasicNameValuePair("customerName", customerName));
            params.add(new BasicNameValuePair("channel", channel));

            try {
                String evaluateLogResult = RestTemplateBean.doGet(hgsProp.getHgsUrl(), params);

                if (StringUtils.isNoneBlank(evaluateLogResult)) {
                    JSONObject evaluate = JSONObject.fromObject(evaluateLogResult).getJSONObject("data").getJSONObject("entity");
                    evaluateLogId = evaluate.getString("id");
                }
            } catch (URISyntaxException e) {
                logger.error(e.getMessage(), e);
            }

            //获取分享 jsapi签名
//            String signature = this.getSHA1(jsapiTicket, nonceStr, String.valueOf(timestamp), requestUrl);

            String link = hgsProp.getUrlPrefix() + "/house365-hgs-web/evaluateusercustomerlog/evaluate/" + evaluateLogId;
            result.put("appId", weChatProperties.getCorpId());
            result.put("link", link);
//            result.put("jsapiTicket", jsapiTicket);
//            result.put("requestUrl", requestUrl);
//            result.put("nonceStr", nonceStr);
//            result.put("signature", signature);
//            result.put("timestamp", timestamp);
            result.put("title", "安家顾问-" + userName + " 邀请您进行带看评价");
            result.put("desc", "安家顾问-" + userName + " 邀请您进行带看评价");
            result.put("imgUrl", "http://img31.house365.com/M03/61/CB/rBEBYFpyyr6Ae7lrAAAZEtSIlpk668.png");


        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result.toString();
    }

    private List<NameValuePair> getParams(String serviceName, HttpServletRequest request) {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("serviceCode", "Wechat"));
        params.add(new BasicNameValuePair("serviceName", serviceName));
        params.add(new BasicNameValuePair("phone", getPhoneFromCookie(request)));
        return params;
    }

    private JSONObject getData(String json) {
        if (Strings.isNullOrEmpty(json)) {
            return new JSONObject();
        }

        JSONObject data = null;
        JSONObject jsonObject = JSONObject.fromObject(json);
        if ("1".equalsIgnoreCase(String.valueOf(jsonObject.get("result")))) {
            data = (JSONObject) jsonObject.get("data");
        } else {
            data = jsonObject;
        }
        return data;
    }

    /**
     * 用SHA1算法生成安全签名
     *
     * @param jsapiTicket 票据
     * @param nonceStr    随机字符串
     * @param timestamp   时间戳
     * @param url         密文
     * @return 安全签名
     * @throws AesException
     */
    public String getSHA1(String jsapiTicket, String nonceStr, String timestamp, String url) throws AesException {
        try {
            StringBuffer sb = new StringBuffer();

            sb.append("jsapi_ticket=" + jsapiTicket);
            sb.append("&noncestr=" + nonceStr);
            sb.append("&timestamp=" + timestamp);
            sb.append("&url=" + url);

            String str = sb.toString();
            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.ComputeSignatureError);
        }
    }

    /**
     * 从cookie获取用户phone
     *
     * @param request
     * @return
     */
    private String getPhoneFromCookie(HttpServletRequest request) {
        logger.debug("====getPhoneFromCookie:currentUrl:{}======", request.getServletPath());
        String phone = "";
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equals("phone")) {
                phone = cookie.getValue();
            }
        }
        return phone;
    }
}
