package com.sqx.modules.app.controller.app;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.common.annotation.Debounce;
import com.sqx.common.exception.SqxException;
import com.sqx.common.utils.ApiAccessLimitUtil;
import com.sqx.common.utils.DataLimitUtil;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.annotation.LoginUser;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserInfo;
import com.sqx.modules.app.service.AliService;
import com.sqx.modules.app.service.AppService;
import com.sqx.modules.app.service.UserInfoService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * APP登录授权
 */
@RestController
@RequestMapping("/app/user")
@Api(value = "APP管理", tags = {"APP管理"})
public class AppController {

    @Autowired
    private UserService userService;
    @Autowired
    private AppService appService;
    @Autowired
    private CommonInfoService commonRepository;
    private final UserInfoService userInfoService;
    private final AliService aliService;

    public AppController(UserInfoService userInfoService, AliService aliService) {
        this.userInfoService = userInfoService;
        this.aliService = aliService;
    }

    @PostMapping("/authenticationRegister")
    @ApiOperation("认证创建账号")
    public Result authenticationRegister(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        return userService.authenticationRegister(jsonObject, request);
    }

    @Login
    @PostMapping("/getNewUserRed")
    @ApiOperation("领取新用户红包")
    public Result getNewUserRed(@RequestAttribute Long userId) {
        return userService.getNewUserRed(userId);
    }

    @Login
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("用户端修改密码")
    public Result updatePwd(@LoginUser UserEntity user, String pwd, String oldPwd) {
        if (!user.getPassword().equals(DigestUtils.sha256Hex(oldPwd))) {
            return Result.error("原始密码不正确！");
        }
        if (pwd.equals(oldPwd)) {
            return Result.error("新密码不能与旧密码相同！");
        }
        user.setPassword(DigestUtils.sha256Hex(pwd));
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updatePhone", method = RequestMethod.POST)
    @ApiOperation("用户端换绑手机号")
    @ResponseBody
    public Result updatePhone(@RequestAttribute("userId") Long userId, @RequestParam String phone, @RequestParam String msg) {
        return userService.updatePhone(phone, msg, userId);
    }

    @Login
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ApiOperation("用户修改个人信息")
    @ResponseBody
    @Debounce(interval = 3000, value = "#userId")
    public Result updateUserImageUrl(@RequestAttribute("userId") Long userId, @RequestParam(required = false) String zhiFuBao,
                                     @RequestParam String certName, @RequestParam(required = false) String certNum) {
        if (StrUtil.isAllBlank(zhiFuBao, certNum)) {
            return Result.error("支付宝账号或实名身份证号码必须传递一个");
        }

        UserInfo userInfo = userInfoService.getByUserId(userId);
        UserEntity userEntity = userService.getById(userId);

        String errMsg = null;
        if (StrUtil.isNotBlank(zhiFuBao)) {
            int count = userService.count(new QueryWrapper<UserEntity>()
                    .ne("user_id", userId)
                    .eq("zhi_fu_bao_name", certName)
                    .eq("zhi_fu_bao", zhiFuBao));
            if (count > 0) {
                errMsg = "支付宝信息修改失败: 一个支付宝账号仅可绑定一个用户";
            }
            if (StrUtil.isNotBlank(userInfo.getCertName()) && !certName.equals(userInfo.getCertName())) {
                errMsg = "支付宝信息修改失败: 姓名与实名认证信息不相符";
            }

            if (!DataLimitUtil.isAccessAllowed(zhiFuBao+certName,  Integer.parseInt(commonRepository.findOne(924).getValue()), "month")) {
                errMsg = "支付宝信息修改失败: 相同支付宝账号每月可绑定次数已用完";
            }

            if (!ApiAccessLimitUtil.isAccessAllowed(userId.toString(), "updateZFB", Integer.parseInt(commonRepository.findOne(925).getValue()), "month")) {
                errMsg = "支付宝信息修改失败: 每月可修改次数已用完,请联系管理员";
            }

            userEntity.setZhiFuBao(zhiFuBao);
            userEntity.setZhiFuBaoName(certName);
            userService.updateById(userEntity);
        }


        if (StrUtil.isNotBlank(certNum)) {
            if (StrUtil.isNotBlank(userEntity.getZhiFuBaoName()) && !certName.equals(userEntity.getZhiFuBaoName())) {
                errMsg = "实名修改失败: 姓名与绑定支付宝信息不相符";
            }
            if (!IdcardUtil.isValidCard(certNum)) {
                errMsg = "实名修改失败: 身份证号码有误";
            }

            Integer idCount = userInfoService.countCertCount(certName, certNum);
            if (idCount > 1) {
                errMsg = "实名修改失败: 此实名信息已存在";
            }

            if (!ApiAccessLimitUtil.isAccessAllowed(String.valueOf(userId), "updateAuthCertInfo", 1, "month")) {
                errMsg = "实名修改失败: 每月可修改次数已用完,请联系管理员";
            }

            try {
                aliService.authCertNo(certName, certNum);
            }catch (Exception e) {
                ApiAccessLimitUtil.removeKey(String.valueOf(userId), "updateAuthCertInfo");
                errMsg = "实名修改失败: 身份证信息不匹配";
            }
            userInfo.setCertName(certName);
            userInfo.setCertNo(certNum);
            userInfo.setUpdateTime(DateUtil.date());
            userInfoService.updateById(userInfo);
        }

        if (errMsg != null) {
            return Result.error(errMsg);
        }
        return Result.success();
        // 去除首绑支付宝奖励
//        if (bool && isFirstBind) {
//            userService.firstBindAwardsMoney(old);
//        }
    }


    @Login
    @RequestMapping(value = "/updateUsers", method = RequestMethod.POST)
    @ApiOperation("用户修改个人信息")
    @ResponseBody
    public Result updateUsers(@RequestAttribute("userId") Long userId, @RequestBody UserEntity userEntity) {
        userEntity.setUserId(userId);
        userService.updateById(userEntity);
        return Result.success();
    }


    /*@Login
    @RequestMapping(value = "/updateUsers", method = RequestMethod.POST)
    @ApiOperation("用户修改个人信息")
    @ResponseBody
    public Result updateUsers(@RequestAttribute("userId") Long userId,String userName,String avatar,String phone) {
        UserEntity userEntity=new UserEntity();
        userEntity.setUserId(userId);
        userEntity.setUserName(userName);
        userEntity.setAvatar(avatar);
        userEntity.setPhone(phone);
        userService.updateById(userEntity);
        return Result.success();
    }*/


    @Login
    @RequestMapping(value = "/updateUserImageUrl", method = RequestMethod.POST)
    @ApiOperation("用户修改头像")
    @ResponseBody
    public Result updateUserImageUrl(@LoginUser UserEntity user, String avatar) {
        user.setAvatar(avatar);
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updateUserName", method = RequestMethod.POST)
    @ApiOperation("用户修改昵称")
    @ResponseBody
    public Result updateUserName(@LoginUser UserEntity user, String userName) {
        user.setUserName(userName);
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/selectUserById", method = RequestMethod.GET)
    @ApiOperation("获取用户详细信息")
    @ResponseBody
    public Result selectUserById(@LoginUser UserEntity user) {
        UserInfo userInfo = userInfoService.getByUserId(user.getUserId());
        Map<String, Object> map = BeanUtil.beanToMap(user);
        map.putAll(BeanUtil.beanToMap(userInfo));
        return Result.success().put("data", map);
    }


    @RequestMapping(value = "/selectNewApp", method = RequestMethod.GET)
    @ApiOperation("升级检测")
    @ResponseBody
    public Result selectNewApp() {
        return Result.success().put("data", appService.selectNewApp());
    }

    @GetMapping("/openId/{code:.+}/{userId}")
    @ApiOperation("根据code获取openid")
    public Result getOpenid(@PathVariable("code") String code, @PathVariable("userId") Long userId) {
        return userService.getOpenId(code, userId);
    }

    @RequestMapping(value = "/updateClientId", method = RequestMethod.GET)
    @ApiOperation("绑定ClientId")
    @ResponseBody
    public Result updateClientId(String clientId, Long userId, Integer sysPhone) {
        userService.updateUserClientIdIsNull(clientId);
        UserEntity userEntity = new UserEntity();
        userEntity.setSysPhone(sysPhone);
        userEntity.setUserId(userId);
        userEntity.setClientid(clientId);
        userService.updateById(userEntity);
        return Result.success();
    }

}
