package com.cftech.mp.qrcode.web;

import com.cftech.core.util.MpTokenUtil;
import com.cftech.mp.qrcode.model.QrCode;
import com.cftech.mp.qrcode.service.QrCodeService;
import com.cftech.mp.qrcode.utils.WxQrcodeAPIUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * Created by Strive on 2017/4/25.
 */
@RestController
@RequestMapping(value = "/mobile/qrcode")
public class MobileQrcodeController {

    @Autowired
    private MpTokenUtil tokenUtils;

    @Autowired
    private WxQrcodeAPIUtils wxQrcodeAPIUtils;

    @Autowired
    private QrCodeService qrCodeService;

    /**
     * 创建二维码
     * @param accountId
     * @param scene 场景值
     * @param expire_seconds 失效时间 >0 表示临时二维码，反之永久二维码
     * @param replyType 回复消息类型
     * @param contentSource 回复消息内容
     * @return
     */
    @RequestMapping(value = "/createWachatQrcode",
                    method = RequestMethod.POST,
                    produces = {"application/xml; application/json; charset=UTF-8"})
    public String createWachatQrcode(@RequestParam Long accountId,
                                     @RequestParam String scene,
                                     @RequestParam(required = false) long expire_seconds,
                                     @RequestParam(required = false) String replyType,
                                     @RequestParam(required = false) String contentSource) {
        JSONObject retObj = new JSONObject();

        String token = tokenUtils.getToken(accountId);
        //获取微信返回结果
        JSONObject result = wxQrcodeAPIUtils.createQrcodeTicket(token, scene, expire_seconds);
        if (result != null) {
            String ticket = result.getString("ticket");
            long es_endtime = Long.parseLong(result.getString("expire_seconds"));
            String url = result.getString("url");

            //设置临时二维码提前半天过期
            Date tmpTime = new Date(new Date().getTime() + es_endtime * 1000 - 43200000);

            System.out.printf("时间="+ tmpTime);

            QrCode qrCode = qrCodeService.bySceneFindQrcode(scene);
            if (qrCode == null) {
                //新建二维码
                qrCode = new QrCode();
                qrCode.setAccountsId(accountId);
                qrCode.setTicket(ticket);
                qrCode.setSence(scene);
                qrCode.setShortUrl(jointQrcodeLink(ticket));
                qrCode.setAction_name(expire_seconds>0? wxQrcodeAPIUtils.QR_SCENE:wxQrcodeAPIUtils.QR_LIMIT_STR_SCENE);
                qrCode.setExpire_seconds(expire_seconds);
                qrCode.setEsEndtime(tmpTime);
                qrCode.setReply_type(replyType);
                qrCode.setContent_source(contentSource);
                qrCodeService.save(qrCode);
            } else {
                qrCode.setShortUrl(jointQrcodeLink(ticket));
                qrCode.setEsEndtime(tmpTime);
                qrCode.setExpire_seconds(expire_seconds);
                qrCode.setReply_type(replyType);
                qrCode.setContent_source(contentSource);
                qrCodeService.update(qrCode);
            }

            retObj.put("errcode", 0);
            retObj.put("url", url);
            return String.valueOf(retObj);
        }
        retObj.put("errcode", 1);
        return String.valueOf(retObj);
    }

    /**
     * 通过ticket获取二维码
     * @param accountId
     * @param ticket
     * @return
     */
    @RequestMapping(value = "/byTicketFindQRcode",
            method = RequestMethod.GET,
            produces = {"application/xml; application/json; charset=UTF-8"})
    public String byTicketFindQRcode(@RequestParam Long accountId,
                                     @RequestParam String ticket) {
        JSONObject retObj = new JSONObject();
        if (StringUtils.isBlank(ticket)) {
            retObj.put("errcode", 1);
            retObj.put("errmsg", "ticket is null!");
            return String.valueOf(retObj);
        }
        return String.valueOf(wxQrcodeAPIUtils.ByTicketFindQrcode(ticket));
    }

    /**
     * 通过场景值id获取二维码
     * @param scene
     * @return
     */
    @RequestMapping(value = "/bySenceFindQrcode",
            method = RequestMethod.GET,
            produces = {"application/xml; application/json; charset=UTF-8"})
    public String bySenceFindQrcode(@RequestParam String scene) {
        JSONObject retObj = new JSONObject();
        if (StringUtils.isBlank(scene)) {
            retObj.put("errcode", 1);
            retObj.put("errmsg", "scene is null!");
            return String.valueOf(retObj);
        }
        QrCode qrCode = qrCodeService.bySceneFindQrcode(scene);
        retObj.put("errcode", 0);
        retObj.put("url", qrCode.getShortUrl());
        return String.valueOf(retObj);
    }

    public String jointQrcodeLink(String ticket) {
        return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
    }
}

