package com.sysu.admin.api.user;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.sysu.admin.support.base.BaseComponent;
import com.sysu.admin.support.sms.SmsReqVo;
import com.sysu.admin.support.sms.SmsService;
import com.sysu.admin.support.sms.aliyun.AliSmsSenderHelper;
import com.sysu.admin.support.system.organ.Organ;
import com.sysu.admin.support.system.role.SRole;
import com.sysu.admin.support.system.user.User;
import com.sysu.admin.support.system.user.UserService;
import com.xiesx.fastboot.base.result.BaseResult;
import com.xiesx.fastboot.base.result.R;
import com.xiesx.fastboot.core.token.JwtHelper;
import com.xiesx.fastboot.core.token.cfg.TokenCfg;
import com.xiesx.fastboot.core.token.handle.CurrentToken;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.impl.xb.ltgfmt.FileDesc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

@RequestMapping("/api/user")
@RestController
@Slf4j
public class ApiUserController extends BaseComponent {
    @Autowired
    AliSmsSenderHelper mSmsSenderHelper;
    @Autowired
    SmsService mSmsService;
    @Autowired
    UserService userService;
    /**
     * 会员登录并返回用户信息集合
     * @return
     */
    @PostMapping("/login")
    public BaseResult login(@RequestBody String data, @RequestHeader(value = "token", required = false) String token) {
        SmsReqVo sms = JSON.parseObject(data, SmsReqVo.class);
        if(StringUtils.isNotEmpty(token)){
            return R.succ(getTokenUser(sms.getToken()));
        }else{
            if(ObjectUtils.isEmpty(sms.getCode())){
                return R.fail("请输入验证码！");
            }
            log.warn("正在登陆:" + sms.getMobile() + " 验证码:" + sms.getCode());
            // 判断验证码
            BaseResult smsRes = mSmsService.validate(sms.getMobile(), sms.getCode());
            if (smsRes.isFail()) {
                return smsRes;
            }
            return R.succ(getUser(sms.getCode(), sms.getMobile()));
        }
    }

    private User getTokenUser(String token){
        mSmsSenderHelper.checkToken(token);
        CurrentToken currentToken = CurrentToken.getCurrentToken(token);
        Long userId = Long.valueOf(currentToken.getUserId());
        User user = userService.findOne(userId);
        Map<String, Object> claims = Maps.newConcurrentMap();
        claims.put(TokenCfg.USERID, user.getId());
        claims.put(TokenCfg.USERNAME, user.getUsername());
        String newToken = JwtHelper.create("sysuimars", "api", claims, JwtHelper.JWT_EXPIRE_D_1 * 20);
        user.setToken(newToken);
        return user;
    }

    private User getUser(String code, String mobile){
        User user = userService.findByUsername(mobile);
        if(user == null) {
            user = new User().setCode(code).setUsername(mobile).setIsBlack(0).setIsDel(0).setIsEnable(0)
                    .setRoleId((long) SRole.RoleEnum.zjxc.ordinal()).setNickname("")
                    .setPassword(DigestUtils.md5Hex(mobile + code)).setOrganId(Organ.defaultOrgan);
            userService.saveAndFlush(user);
        }
        Map<String, Object> claims = Maps.newConcurrentMap();
        claims.put(TokenCfg.USERID, user.getId());
        claims.put(TokenCfg.USERNAME, user.getUsername());
        String token = JwtHelper.create("sysuimars", "api", claims, JwtHelper.JWT_EXPIRE_D_1 * 20);
        user.setToken(token);
        return user;
    }
}
