package com.younike.store;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.younike.store.common.security.IAuthService;
import com.younike.common.annotation.RestAuth;
import com.younike.common.bean.APIResult;
import com.younike.common.bean.ResultGenerator;
import com.younike.common.constant.Constants;
import com.younike.common.core.controller.BaseController;
import com.younike.common.core.dto.AjaxResult;
import com.younike.common.redis.ICached;
import com.younike.common.utils.encrypt.Base64;
import com.younike.common.utils.network.HttpUtils;
import com.younike.common.utils.string.StringUtils;
import com.younike.service.params.api.LoginParam;
import com.younike.service.pojo.TAppUser;
import com.younike.service.service.ITAppUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.apache.commons.collections.CollectionUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController()
@RequestMapping("/login-api")
@Api(tags = "登录注册")
public class AppLoginController extends BaseController {

    @Resource
    private IAuthService authService;

    @Resource
    private ITAppUserService appUserService;

    @Resource
    private ICached cached;

    @Resource
    private RedissonClient redissonClient;

    @Value("${spring.application.name}")
    private String appid;


    /**
     * 手机登录
     *
     * @param param 参数
     * @return {@link APIResult}
     */
    @PostMapping("phoneLogin")
    @RestAuth(isPublic = true)
    @ApiOperation("手机号登录")
    public APIResult phoneLogin(@RequestBody LoginParam param) {
        if(StringUtils.isBlank(param.getPhoneNumber()) || param.getPhoneNumber().length() != 11){
            return ResultGenerator.getFailResult("请输入正确的手机号");
        }
        if(StringUtils.isBlank(param.getCode())){
            return ResultGenerator.getFailResult("验证码不能为空");
        }
//        Object pop = cached.pop(Constants.SMS_LOGIN_CODE, param.getPhoneNumber());
//        if(pop == null || !StringUtils.equals(param.getCode(), pop.toString())){
//            return ResultGenerator.getFailResult("验证码错误");
//        }
        HashMap<String, Object> map = new HashMap<>(2);
        TAppUser one = appUserService.lambdaQuery().eq(TAppUser::getPhone, param.getPhoneNumber()).one();
        if(one == null){
            TAppUser tAppUser = new TAppUser();
            tAppUser.setPhone(param.getPhoneNumber());
            if(!appUserService.addUser(tAppUser)){
                return ResultGenerator.getFailResult();
            }
            one = appUserService.lambdaQuery().eq(TAppUser::getPhone, param.getPhoneNumber()).one();
            String token = authService.setAuthInfo(one.getId());
            map.put("token",token);
            map.put("user",one);
            map.put("openId",one.getOpenId());
            return ResultGenerator.getSuccessResult(map);
        }
        String token = authService.setAuthInfo(one.getId());
        map.put("token",token);
        map.put("user",one);
        map.put("openId",one.getOpenId());
        return ResultGenerator.getSuccessResult(map);
    }

    /**
     * 发送短信
     *
     * @return {@link AjaxResult}
     */
    @GetMapping("sendLoginSMS")
    @RestAuth(isPublic = true)
    @ApiOperation("发送短信")
    public APIResult sendLoginSMS(@RequestParam("phoneNumber") String phoneNumber) {
        cached.put(Constants.SMS_LOGIN_CODE,phoneNumber,"666666",5);
        return ResultGenerator.getSuccessResult();

    }

    /**
     * 发送注册短信
     *
     * @return {@link AjaxResult}
     */
    @GetMapping("sendRegisterSMS")
    @RestAuth(isPublic = true)
    @ApiOperation("发送注册短信")
    public APIResult sendRegisterSMS(@RequestParam("phoneNumber") String phoneNumber) {

        List<TAppUser> list = appUserService.lambdaQuery().eq(TAppUser::getPhone, phoneNumber).list();
        if(CollectionUtils.isNotEmpty(list) && list.size() > 0){
            return ResultGenerator.getFailResult("手机号已注册");
        }
        cached.put(Constants.SMS_REGISTER_CODE,phoneNumber,"666666",5);
        return ResultGenerator.getSuccessResult();
    }

    @PostMapping("phoneRegister")
    @RestAuth(isPublic = true)
    @ApiOperation("手机号注册")
    public APIResult phoneRegister(@RequestBody LoginParam param) {
        if(StringUtils.isBlank(param.getPhoneNumber())){
            return ResultGenerator.getFailResult("手机号不能为空");
        }
        if(StringUtils.isBlank(param.getCode())){
            return ResultGenerator.getFailResult("验证码不能为空");
        }
        List<TAppUser> list = appUserService.lambdaQuery().eq(TAppUser::getPhone, param.getPhoneNumber()).list();
        if(CollectionUtils.isNotEmpty(list) && list.size() > 0){
            return ResultGenerator.getFailResult("手机号已注册");
        }
        TAppUser tAppUser = new TAppUser();
        tAppUser.setPhone(param.getPhoneNumber());
        if(!appUserService.addUser(tAppUser)){
            return ResultGenerator.getFailResult();
        }
        HashMap<String, Object> map = new HashMap<>(2);
        String token = authService.setAuthInfo(tAppUser.getId());
        map.put("token",token);
        map.put("user",tAppUser);
        return ResultGenerator.getSuccessResult();
    }

    /**
     * 小程序登录
     * */
    @GetMapping("/weChatAppLogin")
    @RestAuth(isPublic = true)
    @ApiOperation("小程序登录")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "请求成功"),
            @ApiResponse(responseCode = "400", description = "请求参数没填好"),
            @ApiResponse(responseCode = "404", description = "请求路径没有或页面跳转路径不对")
    })
    public APIResult<Map<String, Object>> sendCode(String encrypdata,
                              String ivdata, String code) {
        // 请求参数
        String params = "appid=" + "wx7cf132e84ed87dac" + "&secret=" + "176ae2b3adf10ac43f1c125392e551fb" + "&js_code=" + code + "&grant_type=authorization_code";

        String s = HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);

        String sessionkey = "";
        String openId = "";
        try {
            // 解析相应内容（转换成json对象）
            JSONObject json = JSON.parseObject(s);
            // 获取会话密钥（session_key）
            sessionkey = json.get("session_key").toString();
            //这里可以获取OpenId
            openId = json.get("openid").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        byte[] encrypData = Base64.decode(encrypdata);
        byte[] ivData = Base64.decode(ivdata);
        byte[] sessionKey = Base64.decode(sessionkey);
        String mobile="";
        Map<String, Object> map = new HashMap<>();
        try {
            mobile = decrypt(sessionKey,ivData,encrypData);
            JSONObject jsonObject = JSONObject.parseObject(mobile);
            mobile = jsonObject.get("phoneNumber").toString();

            TAppUser one = appUserService.lambdaQuery().eq(TAppUser::getPhone, mobile).one();
            if(one == null){
                TAppUser tAppUser = new TAppUser();
                tAppUser.setPhone(mobile);
                tAppUser.setOpenId(openId);

                if(!appUserService.addUser(tAppUser)){
                    return ResultGenerator.getFailResult();
                }
                one = appUserService.lambdaQuery().eq(TAppUser::getPhone, mobile).one();
                String token = authService.setAuthInfo(one.getId());
                map.put("token",token);
                map.put("user",one);
                map.put("openId",openId);

                return ResultGenerator.getSuccessResult(map);
            }
            String token = authService.setAuthInfo(one.getId());
            map.put("token",token);
            map.put("user",one);
            map.put("openId",openId);
        } catch (Exception e) {
            e.printStackTrace();

            return ResultGenerator.getFailResult();
        }
        return ResultGenerator.getSuccessResult(map);
    }

    /**
     * 小程序端修改用户
     */
    @PostMapping("/edit")
    @RestAuth(isPublic = true)
    @PutMapping
    @ApiOperation("修改用户")
    public AjaxResult edit(@RequestBody TAppUser tUser)
    {
        appUserService.updateById(tUser);
        return AjaxResult.success(appUserService.getById(tUser.getId()));
    }

    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        //解析解密后的字符串
        return new String(cipher.doFinal(encData),"UTF-8");
    }
}
