package com.yizhi.application.wechat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yizhi.application.wechat.utils.WechatInfoService;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.site.application.feign.api.FunctionDisplayConfigApiClients;
import com.yizhi.system.application.system.remote.LoginLogClient;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.util.application.constant.GlobalConstant;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import com.yizhi.wechat.application.feign.WeChatUserClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 自定义项目定制接口
 *
 * @author lilingye
 * @since 2020-3-23 17:45:55
 */
@RestController
@Api(tags = "自定义项目的 接口")
@RequestMapping("/public/custom")
public class CustomProgramController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomProgramController.class);
    private final static String ZERO = "0";
    private final static String TWO = "2";
    @Autowired
    LoginLogClient loginLogClient;
    @Autowired
    WechatInfoService wechatInfoService;
    @Autowired
    FunctionDisplayConfigApiClients functionClient;
    @Autowired
    WeiXinController weiXinController;
    @Autowired
    WeChatUserClient weChatClient;

    @ApiOperation(value = "自定义项目新增接口")
    @GetMapping(value = "/get")
    public Response<String> queryUser(HttpServletResponse httpResponse,
                                      @ApiParam(name = "wechatUserId", value = "用户openid", required = true) @RequestParam(name = "wechatUserId", required = true) String wechatUserId,
                                      @ApiParam(name = "appid", value = "公众号的APPId或者是企业服务号的CorpId", required = true) @RequestParam(name = "appid",required = true) String appid,
                                      @ApiParam(name = "agentId", value = "机构Id", required = false) @RequestParam(name = "agentId",required = false) String agentId,
                                      @ApiParam(name = "orgId", value = "组织Id", required = false) @RequestParam(name = "orgId",required = false) Long orgId
                                      ) {

        LOGGER.info("参数weChatUserId:" + wechatUserId + "参数appId：" + appid);
        RequestContext context = ContextHolder.get();
        LOGGER.info("wechat 请求站点的上下文：{}", JSON.toJSON(context));

        Map<String, Object> retMap = weChatClient.getToken(wechatUserId, appid, agentId,orgId);
        LOGGER.info("返回的数据:{}", retMap);
        if (null != retMap) {
            String returnCode = retMap.get("returnCode").toString();
            if ((ZERO).equals(returnCode)) {
                return Response.fail(ReturnCode.NOT_SITE_CODE);
            }
            if ((TWO).equals(returnCode)) {
                return Response.fail("配置链接的公司站点编码和微信公众号配置的不一致！");
            }
            //生成token
            Object userInfo = retMap.get("userInfo");
            LOGGER.info("map中的用户信息2：{}", JSON.toJSON(userInfo));
            JSONObject jsonObject = (JSONObject) JSON.toJSON(userInfo);
            AccountVO accountVO = JSON.toJavaObject(jsonObject, AccountVO.class);
            LOGGER.info("accountVO中的用户信息2：{}", JSON.toJSON(accountVO));
            context.setAccountId(accountVO.getId());
            String token = weiXinController.generateToken(context.getCompanyCode(), context.getCompanyId(), context.getCompanyName(), accountVO, context.getSiteId());
            retMap.put(GlobalConstant.TOKEN_HEADER, token);
            httpResponse.addHeader(GlobalConstant.TOKEN_HEADER, token);
            ContextHolder.set(context);
            LOGGER.info("返回得到token结果：{}", retMap);
        } else {
            LOGGER.info("当前的微信号未关联系统账号");
            return Response.fail(ReturnCode.NOT_RELATE_ACCOUNT);
        }
        LOGGER.info("最后生成的结果：{}", retMap);
        return Response.ok(retMap);

    }

}
