package ink.wgink.module.wechat.officialaccount.service.impl;

import ink.wgink.module.wechat.officialaccount.result.OfficialAccountEventResult;
import ink.wgink.module.wechat.officialaccount.service.BaseOfficialAccountService;
import ink.wgink.module.wechat.officialaccount.service.IOfficialAccountTextService;
import ink.wgink.module.wechat.officialaccount.service.IOfficialAccountUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: OfficialAccountTextServiceImpl
 * @Description: 自动回复
 * @Author: wanggeng
 * @Date: 2021/5/2 10:54 上午
 * @Version: 1.0
 */
@Service
public class OfficialAccountTextServiceImpl extends BaseOfficialAccountService implements IOfficialAccountTextService {

    public static String[] KEYWORD_ARRAY = {"验证码"};
    @Autowired
    private IOfficialAccountUserService officialAccountUserService;

    @Override
    public void getReplay(OfficialAccountEventResult officialAccountEventResult, AsyncContext asyncContext, HttpServletResponse response) throws IOException {
        String content = officialAccountEventResult.getContent().replaceAll("\\s+", "");
        if (content.contains(KEYWORD_ARRAY[0])) {
            String userCode = officialAccountUserService.getUserCodeByOpenId(officialAccountEventResult.getFromUserName());
            write(asyncContext, response, responseXML(officialAccountEventResult.getFromUserName(),
                    officialAccountEventResult.getToUserName(), "您的验证码为：" + userCode));
            return;
        }
        write(asyncContext, response, "");
    }

    private String responseXML(String toUser, String fromUserName, String replay) {
        return "<xml><ToUserName><![CDATA[" +
                toUser +
                "]]></ToUserName><FromUserName><![CDATA[" +
                fromUserName +
                "]]></FromUserName><CreateTime>" +
                System.currentTimeMillis()
                + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" +
                replay
                + "]]></Content></xml>";
    }
}
