package com.template.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.template.annotation.DESRespondSecret;
import com.template.annotation.PassToken;
import com.template.api.WxGzhControllerAPI;
import com.template.common.utils.*;
import com.template.model.pojo.SmartCodeOpenId;
import com.template.model.pojo.SmartUser;
import com.template.model.pojo.SmsCode;
import com.template.model.result.CommonResult;
import com.template.model.weixin.HttpParame;
import com.template.services.SmartCodeOpenIdService;
import com.template.services.SmartUserService;
import com.template.services.SmsCodeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
//返回参数加密注解
@DESRespondSecret
public class WxGzhController implements WxGzhControllerAPI {
    private static Logger logger = LoggerFactory.getLogger(WxGzhController.class);

    //    公众号的唯一标识
    private static String appid = "wxa46ef222053a1047";
    //    公众号的appsecret
    private static String secret = "16f74a1265c314fd79fdf90670173467";

    @Autowired
    SmartUserService smartUserService;

    @Autowired
    SmartCodeOpenIdService smartCodeOpenIdService;

    @Autowired
    SmsCodeService smsCodeService;

    @Override
    @PassToken
    @DESRespondSecret(validated = true)
    public CommonResult getWxGzhOpenid(String code) throws Exception {

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
        logger.info("url = " + url);

        String s = HttpsClient.httpsRequestReturnString(url, "GET", "");

        JSONObject jsonObject = JSONObject.parseObject(s);

        if (!jsonObject.containsKey("openid")) {
            return CommonResult.fail("code有误");
        }
        String openid = jsonObject.getString("openid");

//        判断openid是否已经存在
        LambdaQueryWrapper<SmartUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SmartUser::getGzhOpenId, openid);
        SmartUser smartUser = smartUserService.getOne(wrapper);
        JSONObject jsonObject1 = new JSONObject();

        if (ObjectUtils.isNotEmpty(smartUser)) {
            jsonObject1.put("phone", smartUser.getPhone());
            return CommonResult.ok(jsonObject1);
        }
        SmartCodeOpenId smartCodeOpenId = new SmartCodeOpenId();
        smartCodeOpenId.setCode(code);
        smartCodeOpenId.setOpenId(openid);

        smartCodeOpenIdService.save(smartCodeOpenId);

        logger.info("openid = " + openid);

        jsonObject1.put("phone", "");
        return CommonResult.ok(jsonObject1);
    }

    @Override
    @PassToken
    @DESRespondSecret(validated = true)
    public CommonResult vertifyMessage(String phone, String code, String wxGzhCode) {
        QueryWrapper<SmsCode> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.eq("is_verify", 0);
        queryWrapper1.eq("phone_number", phone);
        queryWrapper1.eq("code", code);
        queryWrapper1.ge("expiration_time", new Date());
        List<SmsCode> listc = smsCodeService.getSmsCodeByKey(queryWrapper1);
        if (listc.isEmpty()) {
            return CommonResult.fail("验证码已失效");
        }

        for (SmsCode smsCode : listc) {
            smsCode.setIsVerify("1");
            smsCodeService.updateSmsCode(smsCode);
        }


        QueryWrapper<SmartUser> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("deleted", 0);
        queryWrapper2.eq("phone", phone);
        SmartUser user = smartUserService.getOne(queryWrapper2);
        if (ObjectUtils.isEmpty(user)) {
            return CommonResult.fail("该用户不存在");
        }

        LambdaQueryWrapper<SmartCodeOpenId> wrapperCode = new LambdaQueryWrapper<>();
        wrapperCode.eq(SmartCodeOpenId::getCode, wxGzhCode);
        SmartCodeOpenId smartCodeOpenId = smartCodeOpenIdService.getOne(wrapperCode);

        if (ObjectUtils.isNotEmpty(smartCodeOpenId)) {
            user.setGzhOpenId(smartCodeOpenId.getOpenId());
            smartUserService.updateSmartUser(user);
        }

        return CommonResult.ok();
    }

    @Override
    @PassToken
    @DESRespondSecret(validated = true)
    public CommonResult unbinding(String phone) {
        if (ObjectUtils.isEmpty(phone)) {
            return CommonResult.fail("参数异常");
        }

        QueryWrapper<SmartUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("phone", phone);
        SmartUser user = smartUserService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(user)) {
            return CommonResult.fail("该用户不存在");
        }
        user.setGzhOpenId("");

        smartUserService.updateById(user);

        return CommonResult.ok();
    }


}
