package com.wechat.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.wechat.common.Constants;
import com.wechat.common.TwoDimensionCode;
import com.wechat.common.utils.MvcUtil;
import com.wechat.common.utils.StringsUtils;
import com.wechat.global.base.BaseController;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.responseDto.JsonResp;
import com.wechat.model.responseDto.QrCodeResp;
import com.wechat.service.WeiXinService;


/**
 * FAQ问答
 * 
 */
@Controller
@RequestMapping("qrCode")
public class QrCodeController extends BaseController {
	
	// 上传根路径
	@Value("#{configProperties['upload.base.path']}")
	private String updBaseUrl;
	
	// 二维码图片
	@Value("#{configProperties['upload.qrcode.path']}")
	private String updQrcodeUrl;
	
	// 访问根路径
	@Value("#{configProperties['url.base']}")
	private String baseUrl;
	
	// 图片根路径
	@Value("#{configProperties['url.img.base']}")
	private String baseImgUrl;
	
    @Resource
    private WeiXinService wxService;
     
    /**
     * 入口二维码生成
     * 
     */
    @RequestMapping(value = "getQrCode", method = RequestMethod.GET)
    public void getQrCode(HttpServletRequest request, HttpServletResponse response, @RequestParam String longUrl) throws Exception{
        JsonResp<QrCodeResp> ret = new JsonResp<QrCodeResp>();
        QrCodeResp qrResp = new QrCodeResp();
        //生成短链接
        String url = wxService.getShortUrl(URLDecoder.decode(longUrl, "utf-8"));
        if(StringsUtils.isEmpty(url))
        {
        	log.error("短链接生成异常");
	     	ret.setMsg(InfoMsg.ERROR_SYSTEM_ERROR);
        }
        else
        {
        	//二维码生成生成
        	String qrCodeName =  "qrCode" + StringsUtils.parseLong((new Date()).getTime()) + ".png";
            TwoDimensionCode.encoderQRCode(url, updBaseUrl + updQrcodeUrl + qrCodeName, "png", 5);
            
            //返回信息时装
            qrResp.setQrCodeImg(baseUrl + baseImgUrl + updQrcodeUrl + qrCodeName);
            qrResp.setShortUrl(url);
            
            ret.setInfo(qrResp);
        }

        String json = JSON.toJSONString(ret, true);
        try {
            MvcUtil.writeJson(request, response, json);
        } catch (IOException e) {
           log.error(e);
        } 
    }
    
}
