package com.cirle.scientific.controller.register;

import com.alibaba.fastjson.JSONObject;
import com.cirle.scientific.dao.MemberDao;
import com.cirle.scientific.dao.QkjMemberOpenidDao;
import com.cirle.scientific.dao.QkjMemberTaskInfoDao;
import com.cirle.scientific.dto.WxUerInfoDTO;
import com.cirle.scientific.po.QkjMember;
import com.cirle.scientific.po.QkjMemberOpenid;
import com.cirle.scientific.po.QkjMemberTaskInfo;
import com.cirle.scientific.pojo.BizCodeEnum;
import com.cirle.scientific.pojo.Result;
import com.cirle.scientific.service.MemberService;
import com.cirle.scientific.service.WeixinService;
import com.cirle.scientific.utils.DESUtil;
import com.cirle.scientific.utils.IpUtil;
import com.cirle.scientific.utils.SmsUtils;
import com.cirle.scientific.utils.StringUtil;
import com.cirle.scientific.utils.weixin.WeixinpayConfig;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/register")
@Api("登录相关接口")
@Slf4j
public class RegisterController {

    @Autowired
    MemberDao memberDao;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    WeixinService weixinService;
    @Autowired
    MemberService memberService;
    @Autowired
    QkjMemberTaskInfoDao qkjMemberTaskInfoDao;
    @Autowired
    QkjMemberOpenidDao openidDao;

    @GetMapping("")
    @ApiOperation(value = "手机号登录页面")
    public String login(
            @ApiParam(name = "from", value = "请求类型 web：网站 H5：手机端") @RequestParam(name = "from", required = true) String from,
            @ApiParam(name = "redirectUrl", value = "回调地址") @RequestParam(name = "redirectUrl", required = false) String redirectUrl,
            HttpServletRequest request
    ) {
        request.setAttribute("redirectUrl", redirectUrl);
        if (StringUtils.isNotBlank(from) && from.equals("H5")) {
            return "html5/user/register";
        } else {
            return "";
        }
    }

    @GetMapping(value = "/isRegister")
    @ResponseBody
    public Result isRegister(
            @ApiParam(name = "wxId", value = "微信ID") @RequestParam(name = "wxId", required = false) String wxId
    ) {
        Map<String, Boolean> map = Maps.newHashMap();
        boolean isRegister = true;
        if (StringUtils.isNotBlank(wxId)) {
            QkjMember member = memberDao.findByWxId(wxId);
            if (Objects.isNull(member)) {
                isRegister = false;
            }
        }
        map.put("isRegister", isRegister);
        return Result.success(map);
    }

    @RequestMapping(value = "/mobilReg", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result register(
            @ApiParam(name = "memMobile", value = "用户手机号") @RequestParam(name = "memMobile", required = true) String memMobile,
            @ApiParam(name = "memMobile", value = "用户名") @RequestParam(name = "userName", required = false) String userName,
            @ApiParam(name = "valCode", value = "验证码") @RequestParam(name = "valCode", required = true) String valCode,
            @ApiParam(name = "passwd", value = "密码") @RequestParam(name = "passwd", required = true) String passwd,
            @ApiParam(name = "memRegisterSource", value = "注册终端，1-H5，2-pc") @RequestParam(name = "memRegisterSource", required = true) Integer memRegisterSource,
            HttpServletRequest request
    ) {

        //校验用户名的唯一性
        if(StringUtils.isNotBlank(userName)){
            List<QkjMember> qkjMembers = memberDao.listByMemNickname(userName);
            if(CollectionUtils.isNotEmpty(qkjMembers) && qkjMembers.size() >=1){
                return Result.failed(BizCodeEnum.NAME_REPEAT);
            }
        }
        //注册：修改密码
        QkjMember member = memberDao.findByMemMobile(memMobile);

        int valRs = validateMobileYzm(memMobile, valCode);
        if (valRs == -1) {
            return Result.failed(BizCodeEnum.CODE_TIME_OUT);
        }
        if (valRs == -2) {
            return Result.failed(BizCodeEnum.CODE_ERROR);
        }
        if (member != null) {
            member.setPasswd(DigestUtils.md5DigestAsHex(passwd.getBytes()));
            if(StringUtils.isNotBlank(userName)){
                member.setMemNickname(userName);
            }
            memberDao.save(member);
            return Result.success("","手机号已注册，密码重置成功");
        }


        //注册：添加用户
        member = memberService.register(memMobile, memRegisterSource, 0, DigestUtils.md5DigestAsHex(passwd.getBytes()), userName);
        if (member == null) {
            log.info("创建用户失败");
            return Result.failed("创建用户失败");
        }
        return Result.success("","创建用户成功，请登录！");
    }

    protected int validateMobileYzm(String memUserId, String inputYzm) {

        String realYzm = (String) stringRedisTemplate.opsForValue().get(memUserId + "yzm");
        log.info("用户输入的验证码 " + inputYzm);
        log.info("缓存里面的验证码" + realYzm);
        if (realYzm == null) {
            return -1;
        }

        if (!inputYzm.equals(realYzm)) {
            return -2;
        }

        stringRedisTemplate.delete(memUserId + "yzm");
        return 0;
    }


}
