package com.usky.iot.controller.web;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.HttpUtils;
import com.usky.common.redis.core.RedisHelper;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.iot.constant.constant;
import com.usky.iot.domain.MceMbuser;
import com.usky.iot.service.MceMbuserService;
import com.usky.iot.service.vo.SendWeChatMessageRequestVO;
import com.usky.iot.service.vo.SignUpRequestVO;
import com.usky.iot.service.vo.TemplateData;
import com.usky.iot.service.vo.TemplateMsgEntityVO;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.impl.util.StringUtil;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.enums.WxMpApiUrl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ExitCodeEvent;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.view.RedirectView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/weChat")
@Slf4j
public class WeChatController {
    @Autowired
    private WxMpService wxMpService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;
    @Autowired
    private MceMbuserService mceMbuserService;
    @Autowired
    private RedisHelper redisHelper;

    private static final Logger LOGGER = LoggerFactory.getLogger(WeChatController.class);

    /**
     * 调用的第一个接口，获取微信公众号CODE，获取openid
     */
    @GetMapping("/getFirst1")
    public void getFirst1() throws UnsupportedEncodingException {
        String http = "https://";
        String code = request.getParameter("code");
        String userAgent = request.getHeader("User-Agent");

        System.out.println("userAgent:  "+userAgent);

        if(StringUtils.isBlank(code)){
            String temp = http+constant.call_back_domain+"/prod-api/service-iot"+request.getRequestURI();
            String url = URLDecoder.decode(temp, "UTF-8");
            String sendUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+constant.WE_CHAT_APP_ID+"&redirect_uri="+url+"&response_type=code&scope=snsapi_base&state=abc123#wechat_redirect";
            try{
                System.out.println("sendUrl: "+sendUrl);
                response.sendRedirect(sendUrl);
            }catch (IOException e){
                throw new BusinessException(e.getMessage());
            }
        }else{
            System.out.println("code:  "+code);
            try {
                WxOAuth2AccessToken wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);

                String openid = wxOAuth2AccessToken.getOpenId();
                String access_token = wxOAuth2AccessToken.getAccessToken();
                System.out.println("openid:  "+openid);
//                request.getSession().setAttribute("openid",openid);
//                LambdaQueryWrapper<MceMbuser> queryWrapper = Wrappers.lambdaQuery();
//                queryWrapper.select(MceMbuser::getPhone)
//                        .eq(MceMbuser::getOpenid,openid);
//                MceMbuser one = mceMbuserService.getOne(queryWrapper);
//                if(one != null){
//                    request.getSession().setAttribute("phone",one.getPhone());
//                }

                String sendUrl = http+constant.call_back_domain+constant.WE_CHAT_LOGIN+"?openId="+openid;
                response.sendRedirect(URLDecoder.decode(sendUrl, "UTF-8"));
            } catch (Exception e) {
                throw new BusinessException(e.getMessage());
            }
        }
    }

    /**
     * 跳转首页权限
     */
    @GetMapping("/getPageAuthorization")
    public ApiResult<MceMbuser> getPageAuthorization(@RequestParam(value = "openId") String openId)  {
        String http = "https://";
        String code = request.getParameter("code");
        LOGGER.info("String openId:  "+openId);

        if((openId != null) && (openId != "")){
                LambdaQueryWrapper<MceMbuser> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq(MceMbuser::getOpenid,openId).last("LIMIT 1");
                MceMbuser one = mceMbuserService.getOne(queryWrapper);
                if(one != null){
                    String access_key = "login_openid:"+openId;
                    if(redisHelper.hasKey(access_key)){
                        String accessToken = redisHelper.get(access_key).toString();
                        one.setAccessToken(accessToken);
                    }else{
                        one.setAccessToken("");
                    }

                }

                return ApiResult.success(one);
//            try{
//                LambdaQueryWrapper<MceMbuser> queryWrapper = Wrappers.lambdaQuery();
//                queryWrapper.eq(MceMbuser::getOpenid,openId).last("LIMIT 1");
//                MceMbuser one = mceMbuserService.getOne(queryWrapper);
//                if(one != null){
//                    //String sendUrl = http+constant.call_back_domain+constant.WE_CHAT_INDEX+"?openId="+one.getOpenid();
//                    String sendUrl = http+constant.call_back_domain+constant.WE_CHAT_INDEX+"?flag=true";
//                    response.sendRedirect(URLDecoder.decode(sendUrl, "UTF-8"));
//                }else{
//                    //String sendUrl = http+constant.call_back_domain+constant.WE_CHAT_LOGIN+"?openId="+openId;
//                    String sendUrl = http+constant.call_back_domain+constant.WE_CHAT_LOGIN+"?flag=true";
//                    response.sendRedirect(URLDecoder.decode(sendUrl, "UTF-8"));
//                }
//            }catch (IOException e){
//                throw new BusinessException(e.getMessage());
//            }

        }else{
            throw new BusinessException("openId null");
//            try{
//                String sendUrl = http+constant.call_back_domain+constant.WE_CHAT_LOGIN+"?flag=true";
//                response.sendRedirect(URLDecoder.decode(sendUrl, "UTF-8"));
//            }catch (IOException e){
//                throw new BusinessException(e.getMessage());
//            }
//            if(StringUtils.isBlank(code)){
//                String temp = http+constant.call_back_domain+"/prod-api/service-iot"+request.getRequestURI();
//                String url = URLDecoder.decode(temp, "UTF-8");
//                String sendUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+constant.WE_CHAT_APP_ID+"&redirect_uri="+url+"&response_type=code&scope=snsapi_base&state=abc123#wechat_redirect";
//                try{
//                    System.out.println("sendUrl: "+sendUrl);
//                    LOGGER.info("sendUrl: "+sendUrl);
//                    response.sendRedirect(sendUrl);
//                }catch (IOException e){
//                    throw new BusinessException(e.getMessage());
//                }
//            }else{
//                System.out.println("code:  "+code);
//                LOGGER.info("code:  "+code);
//                try {
//                    WxOAuth2AccessToken wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
//
//                    String openid = wxOAuth2AccessToken.getOpenId();
//                    String access_token = wxOAuth2AccessToken.getAccessToken();
//                    System.out.println("openid:  "+openid);
//                    LOGGER.info("openid:  "+openid);
//                    LambdaQueryWrapper<MceMbuser> queryWrapper = Wrappers.lambdaQuery();
//                    queryWrapper.eq(MceMbuser::getOpenid,openid).last("LIMIT 1");
//                    MceMbuser one = mceMbuserService.getOne(queryWrapper);
//                    if(one != null){
//                        //String sendUrl = http+constant.call_back_domain+constant.WE_CHAT_INDEX+"?openId="+one.getOpenid();
//                        String sendUrl = http+constant.call_back_domain+constant.WE_CHAT_INDEX;
//                        response.sendRedirect(URLDecoder.decode(sendUrl, "UTF-8"));
//                    }else{
//                        //String sendUrl = http+constant.call_back_domain+constant.WE_CHAT_LOGIN+"?openId="+openid;
//                        String sendUrl = http+constant.call_back_domain+constant.WE_CHAT_LOGIN;
//                        response.sendRedirect(URLDecoder.decode(sendUrl, "UTF-8"));
//                    }
//
//
//                } catch (Exception e) {
//                    throw new BusinessException(e.getMessage());
//                }
//            }

        }

    }

    /**
     * 登录并注册
     */
    @PostMapping("/signUp")
    public Map<String,Object> signUp(@RequestBody SignUpRequestVO requestVO){
        String phone = requestVO.getPhone();
        String verify = requestVO.getVerify();
        Map<String,Object> map = new HashMap<>();

        //手机验证码登录
        if (StringUtils.isBlank(phone)) {
            throw new BusinessException("手机号不能为空");
        }
        if (StringUtils.isBlank(verify)) {
            throw new BusinessException("验证码不能为空");
        }
        if (!verify.equals(redisHelper.get(phone))) {
            throw new BusinessException("验证码错误");
        }

        LambdaQueryWrapper<MceMbuser> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(MceMbuser::getPhone,phone);
        List<MceMbuser> list = mceMbuserService.list(queryWrapper);
        if(CollectionUtils.isEmpty(list)){
            MceMbuser one = new MceMbuser();
            one.setPhone(phone);
            if(request.getSession().getAttribute("type") == "app"){
                one.setOpenid(request.getSession().getAttribute("app_token").toString());
            }else{
                one.setOpenid(request.getSession().getAttribute("openid").toString());
            }
            one.setCreateBy(SecurityUtils.getUsername());
            one.setUserId(SecurityUtils.getUserId());
            one.setCreateTime(LocalDateTime.now());

            if(mceMbuserService.save(one)){

            }else{
                map.put("msg","注册失败，请重新注册");
                map.put("flag",true);
                return map;
            }
        }else {
            request.getSession().setAttribute("openid",list.get(0).getOpenid());
        }

        request.getSession().setAttribute("phone",phone);

        map.put("msg","验证成功，正在登录");
        map.put("flag",true);
        return map;
    }


}











