package cn.sh.stc.sict.theme.hphy.controller.mp;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.HttpRequest;
import cn.sh.stc.sict.cloud.common.core.util.R;
import cn.sh.stc.sict.cloud.common.security.util.SecurityUtils;
import cn.sh.stc.sict.cloud.upms.dto.CurrentUser;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author F_xh
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api(tags = "[C]智能问答")
@RequestMapping("/c/intelligent/qa")
public class IntelligentQAController {
    private final static String CONTENT = "Content";

    @ApiOperation("智能问答")
    @PostMapping
    public R qa(String question) {
        CurrentUser current = SecurityUtils.getCurrentUser();
        String from = null != current ? (StrUtil.isNotBlank(current.getOpenId()) ? current.getOpenId() : current.getId().toString()) : IdWorker.getIdStr();

        String xml = "<xml>\n" +
                "  <ToUserName><![CDATA[gh_fe5b36b12c61]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + from + "]]></FromUserName>\n" +
                "  <CreateTime>" + DateUtil.now() + "</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + question + "]]></Content>\n" +
                "  <MsgId>" + IdWorker.getId() + "</MsgId>\n" +
                "</xml>";

        String body = HttpRequest.post("http://www.365jqr.com/jqrsvr.ashx?Command=talk_162")
                .body(xml)
                .execute()
                .body();

        Map<String, Object> result = XmlUtil.xmlToMap(body);
        if(result.containsKey(CONTENT)){
            return new R(result.get(CONTENT));
        }

        return new R();
    }


}
