package com.cyl.h5.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cyl.external.WechatUtil;
import com.cyl.h5.pojo.response.H5LoginResponse;
import com.cyl.h5.pojo.vo.form.WechatLoginForm;
import com.cyl.h5.service.H5MemberService;
import com.cyl.manager.staff.domain.Staff;
import com.cyl.manager.staff.service.IStaffService;
import com.cyl.manager.staff.service.IStaffWechatService;
import com.cyl.manager.staff.service.impl.StaffServiceImpl;
import com.cyl.manager.ums.domain.Member;
import com.cyl.manager.ums.service.MemberWechatService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * h5/微信
 */
@RestController
@RequestMapping("")
//@Api("微信公众号认证相关")
@Slf4j
public class WechatController2 {
    @Autowired
    private MemberWechatService memberWechatService;

    @Autowired
    private H5MemberService h5MemberService;

    @Autowired
    private IStaffService staffService;

    @Autowired
    private IStaffWechatService staffWechatService;

    /**
     * 微信公众号服务器认证
     * @return
     */
    //@ApiOperation("微信公众号服务器认证")
    @GetMapping("/no-auth/wechat-server-auth")
    public String getHomeConfig(HttpServletRequest request) {
        String signature = request.getParameter("signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        String echostr = request.getParameter("echostr");
        if (WechatUtil.validParam(signature, "BLU9Jo7vo", timestamp, nonce)) {
            return echostr;
        }
        return "err";
    }
    /**
     * 微信公众号服务器认证
     * @return
     */
    //@ApiOperation("H5登陆")
    @PostMapping("/no-auth/wechat/h5-login")
    public ResponseEntity<String> h5Login(@RequestBody WechatLoginForm form) {
        String token = memberWechatService.login(form);
        return ResponseEntity.ok("{\"data\": \"" + token + "\"}");
    }


    //@ApiOperation("获取SessionId")
    @GetMapping("/no-auth/wechat/getSessionId")
    public AjaxResult getSessionId(String code) {
        JSONObject object = memberWechatService.getSessionId(code);
        if (object != null) {
            String openId = object.getString("openid");
            String sessionId = object.getString("session_key");
            Map map = new HashMap();
            map.put("openId", openId);
            //map.put("sessionId", sessionId);
            //return AjaxResult.successData(Base64Utils.encodeToString(JSON.toJSONString(map).getBytes()));
            return AjaxResult.successData(JSON.toJSONString(map));
        }
        return AjaxResult.success(null);
    }

    //@ApiOperation("获取OpenId")
    @GetMapping("/no-auth/wechat/getOpenId")
    public AjaxResult getOpenId(HttpServletRequest request) {
        String code = request.getParameter("code");
        String sourceType = request.getParameter("sourceType");

        if (StringUtils.isNotEmpty(sourceType) && "1".equals(sourceType)) {
            //伴宠师app

            JSONObject object = staffWechatService.getSessionId(code);
            if (object != null) {
                String openId = object.getString("openid");
                String sessionId = object.getString("session_key");
                Map map = new HashMap();
                map.put("openId", openId);
                // todo 判断openId 是否注册
                Staff staff = staffWechatService.isRegister(openId);
                if(ObjectUtil.isNull(staff)){
                    map.put("token", null);
                }else{
                    H5LoginResponse h5LoginResponse =  staffService.getLoginResponse(staff.getId());
                    //生成token
                    map.put("token", h5LoginResponse.getToken());
                }
                //map.put("sessionId", sessionId);
                //return AjaxResult.successData(Base64Utils.encodeToString(JSON.toJSONString(map).getBytes()));
                return AjaxResult.successData(JSON.toJSONString(map));
            }

        }else {
            JSONObject object = memberWechatService.getSessionId(code);
            if (object != null) {
                String openId = object.getString("openid");
                String sessionId = object.getString("session_key");
                Map map = new HashMap();
                map.put("openId", openId);
                // todo 判断openId 是否注册
                Member member = memberWechatService.isRegister(openId);
                if(ObjectUtil.isNull(member)){
                    map.put("token", null);
                }else{
                    H5LoginResponse h5LoginResponse =  h5MemberService.getLoginResponse(member.getId());
                    //生成token
                    map.put("token", h5LoginResponse.getToken());
                }
                //map.put("sessionId", sessionId);
                //return AjaxResult.successData(Base64Utils.encodeToString(JSON.toJSONString(map).getBytes()));
                return AjaxResult.successData(JSON.toJSONString(map));
            }
        }

        return AjaxResult.success(null);
    }

    @PostMapping("/no-auth/wechat/getPhoneNumber")
    public AjaxResult getPhoneNumber(@RequestBody Map<String,Object> data)
    {
        log.info("=============登录信息:{}===============", JSON.toJSONString(data));
        String code = data.get("code").toString();
        String openId = data.get("openId").toString();
        H5LoginResponse h5LoginResponse = new H5LoginResponse();
        if (data.get("sourceType") != null && "1".equals(data.get("sourceType").toString())) {
            //员工登录
            Staff staff = staffService.getPhoneAndRegister(code, openId);
            h5LoginResponse = staffService.getLoginResponse(staff.getId());
        }else {
            //用户登录
            Member member = memberWechatService.getPhoneAndRegister(code, openId);
            h5LoginResponse = h5MemberService.getLoginResponse(member.getId());
        }



        Map map = new HashMap();
        map.put("token", h5LoginResponse.getToken());

        return AjaxResult.successData(map);
    }
}
