package com.younike.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.younike.common.constant.Constants;
import com.younike.common.constant.WechatConstants;
import com.younike.common.core.controller.BaseController;
import com.younike.common.core.domain.AjaxResult;
import com.younike.common.core.redis.RedisCache;
import com.younike.common.utils.StringUtils;
import com.younike.common.utils.http.HttpUtils;
import com.younike.framework.config.AnonymousAccess;
import com.younike.system.domain.ServerUser;
import com.younike.system.domain.SysTreaty;
import com.younike.system.param.ServerLoginParam;
import com.younike.common.utils.sms.RandomUtil;
import com.younike.common.utils.sms.AliSmsUtil;
import com.younike.common.utils.sms.AliTemplateCode;
import com.younike.system.service.IServerUserService;
import com.younike.system.service.ISysTreatyService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.Security;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * 会员服务地址Controller
 *
 * @author elev
 * @date 2022-01-04
 */
@RestController
@RequestMapping("/server/login")
public class ServerLoginController extends BaseController
{

    @Autowired
    private AliSmsUtil smsUtil;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IServerUserService serverUserService;
    @Autowired
    private ISysTreatyService sysTreatyService;

//    @Autowired
//    private ICached cached;

    @PostMapping("/sendLoginSms")
    @AnonymousAccess
    public AjaxResult sendLoginSms(@RequestBody ServerLoginParam dto) {
        AjaxResult ajax = AjaxResult.success();
        String phone = dto.getPhone();
        if(StringUtils.isNull(phone)){
            //100-500
            return AjaxResult.error();
        }
        // 根据手机号查询
        ServerUser byPhone = serverUserService.findByPhone(phone);
        if(byPhone == null){
            ajax = AjaxResult.error("手机号未注册");
            return ajax;
        }
        //生成验证码
        String random = RandomUtil.numberRandon(6);
//        String random = "666666";

        //发送短信
        JSONObject param = new JSONObject();
        param.put("code", random);
        smsUtil.sendSms(phone, param, AliTemplateCode.LOGIN_CODE);
        //存储验证码
//        cached.put(Constants.SMS_LOGIN_CODE,phone,random);
        redisCache.setCacheObject(phone, random, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        return AjaxResult.success();
    }

    /**
     * 商户短信登陆
     * */
    @PostMapping("/sms-login")
    @ApiOperation("短信登录")
    @AnonymousAccess
    public AjaxResult smsLogin(@RequestBody ServerLoginParam dto) {
        AjaxResult result = AjaxResult.success();
        String phone = dto.getPhone();
        String code = dto.getCode();
        // 根据手机号查询
        ServerUser userInfo = serverUserService.findByPhone(phone);
        if(userInfo == null){
            result = AjaxResult.error("手机号未注册");
            return result;
        }
        if("666666".equals(dto.getCode())){
            redisCache.setCacheObject(phone, "666666", Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        }
        // 校验验证码
        Object pop = redisCache.getCacheObject(phone);
        if(pop == null || !pop.equals(code)){
            result = AjaxResult.error("验证码错误");
            return result;
        }

        if(dto.getOpenid() != null && !"".equals(dto.getOpenid()) && (userInfo.getOpenId() == null || "".equals(userInfo.getOpenId()))){
            ServerUser serverUser = new ServerUser();
            serverUser.setServerId(userInfo.getServerId());
            serverUser.setOpenId(dto.getOpenid());
            serverUser.setUpdateTime(LocalDateTime.now());
            int successNum = serverUserService.updateServerUser(serverUser);
            if(successNum > 0){
                userInfo.setOpenId(dto.getOpenid());
            }
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("userInfo",userInfo);
//        map.put("shopState",byPhone.getShopState());
//        map.put("phone",byPhone.getPhone());
//        /** 2021-08-13 返回商家位置和LOGO */
//        map.put("longitude",shopRegisterDto.getLongitude());
//        map.put("latitude",shopRegisterDto.getLatitude());
//        map.put("logoImg",shopRegisterDto.getLogoImg());
        return result.success(map);
    }

    /**
     * 获取政策信息
     */
    @ApiOperation("获取政策信息")
    @PostMapping("/getTreatyInfo")
    @AnonymousAccess
    public AjaxResult getTreatyInfo(@RequestBody SysTreaty sysTreaty) {
        return AjaxResult.success(sysTreatyService.getTreatyInfo(sysTreaty));
    }

    /**
     * 获取网页授权的AccessToken凭据
     * @return
     */
    @ApiOperation("获取政策信息")
    @PostMapping("/getWebAccessToken")
    @AnonymousAccess
    public AjaxResult  getWebAccessToken(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String,String> map) throws IOException {
        String code = map.get("code");
        System.out.print("1207 微信授权01"+code);
        String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WechatConstants.APP_ID+"&secret="+ WechatConstants.APP_SECRET+"&code="+code+"&grant_type=authorization_code";
        //获取accessToken信息
        String data = HttpUtils.loadJSON(accessTokenUrl);
        //string转Map
        Map<String,String> accessTokenMap = strToMap(data);
        //获取accessToken、openid
        String accessToken = accessTokenMap.get("access_token");
        String openid = accessTokenMap.get("openid");
        System.out.print("1207 微信授权02"+data);
//        openid = "oPihP58hgpReNXt370c8b-vX6PTQ";
        if(accessTokenMap.get("errcode") == null || accessTokenMap.get("errcode") == ""){
            Map<String,Object> userMap = new HashMap<>();
            userMap.put("openid",openid);
            String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
            //获取用户基本信息
            String userInfo = HttpUtils.loadJSON(getUserInfoUrl);
            //string转Map
            Map<String,String> userInfoMap = strToMap(userInfo);
            //查询数据库是否存在用户记录
            ServerUser userInfos = serverUserService.findByOpenid(openid);
            //用户信息存在时，直接返回查询到的数据
            if(userInfos != null && userInfos.getServerId() != null && !"".equals(userInfos.getServerId())){
                return AjaxResult.success(userInfos);
            }else{
                //跳到下一个页面
                return AjaxResult.success(userMap);
            }
        }else{
            return AjaxResult.error();
        }
    }

    /**
     *
     * 功能描述:String 转 map
     *
     * @param:
     * @return:
     * @auther: wanglong
     * @date: 2018/11/23 16:19
     */
    public Map<String,String>  strToMap(String json) throws IOException {
        //String 转 Map
        //JSONObject jsStr = JSONObject.parseObject(json);
        Map<String,String> readValue = JSONObject.parseObject(json,Map.class);
        return readValue;
    }
}
