package com.philisense.www.controller.app;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.philisense.www.annotation.log.OperateLog;
import com.philisense.www.common.config.CommonConst;
import com.philisense.www.controller.BaseUtilController;
import com.philisense.www.enums.ClientStatus;
import com.philisense.www.exception.BadRequestException;
import com.philisense.www.exception.ServiceException;
import com.philisense.www.pojos.entity.JwtUser;
import com.philisense.www.service.JwtUserDetailsService;
import com.philisense.www.service.ProUserService;
import com.philisense.www.utils.JwtTokenUtils;
import com.philisense.www.utils.SecurityUtils;
import com.philisense.www.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(CommonConst.APP_REST_SERVICE_PREFICX+"auth")
@Api(tags = "AuthenticationControllerForApp |一个用来操作-{用户App登陆}-业务模块的控制器")
public class AuthenticationControllerForApp   extends BaseUtilController {

    @Value("${jwt.tokenHead}")
    private String tokenHeader;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Autowired
    @Qualifier("jwtUserDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Autowired
    private PasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private ProUserService proUserService;


    /**
     * 登录授权
     * @param map
     * @return
     */
    @PostMapping(value = "${jwt.auth.path}")
    @ApiOperation(value="根据-{用户名和密码}-登陆", notes="成功返回:{\"success\":true,\"message\",\"登陆成功\"},失败返回:{\"success\":false,\"message\",\"数据失败\"}")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="body", name = "username", value = "用户名", required = true,  dataTypeClass = String.class),
            @ApiImplicitParam(paramType="body", name = "password", value = "用户密码", required = true,  dataTypeClass = String.class),
    })
    @OperateLog(name = "登录授权",value = "query",type = "PC")
    public Map<String, Object> loginForApp(HttpServletRequest request , HttpServletResponse response, @RequestBody Map<String, Object> map){
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Object username = map.get("username");
            if(null == username) {
                throw new BadRequestException("参数不能为空");
            }

            //判断是邮箱还是手机号的正则表达式
            String em = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
            String ph = "^[1][34578]\\d{9}$";

            final JwtUser jwtUser;
            //手机号登录
            if(String.valueOf(username).matches(ph)){
                jwtUser = (JwtUser) jwtUserDetailsService.loadUserByPhone(username + "");
            }else if(String.valueOf(username).matches(em)){
                //邮箱登录
                jwtUser = (JwtUser) jwtUserDetailsService.loadUserByEmail(username + "");
            }else {
                //就是用户名登录
                jwtUser = (JwtUser) userDetailsService.loadUserByUsername(username + "");
            }

            if (StringUtils.isNull(jwtUser)) {
                throw new ServiceException("对不起，[" + username + "] 用户不存在或者密码错误");
            } else if (jwtUser.isAccountNonLocked()) {
                throw new ServiceException("对不起，您的账号：[" + username + "] 已冻结");
            } else if (jwtUser.isEnabled()) {
                throw new ServiceException("对不起，您的账号：[" + username + "] 已停用");
            } else if (!SecurityUtils.matchesPassword(map.get("password")+"", jwtUser.getPassword())) {
                /*// 输错3次锁定用户
                Map<String, Object> user = jwtUser.getUser();
                user.put("freeze_date", new Date());
                user.put("freeze_cause", "3次密码错误");
                user.put("status", "3");
                proUserService.update(user);*/
                throw new ServiceException("对不起，[" + username + "] 用户不存在或者密码错误");
            }

            List<String> listroles = new ArrayList<>();
            List<String> listrolesvalue = new ArrayList<>();
            for(GrantedAuthority auth : jwtUser.getAuthorities()){
                listroles.add(auth.getAuthority());
            }
            /*for(GrantedAuthority auth : jwtUser.getAuthoritiesValue()){
                listrolesvalue.add(auth.getAuthority());
            }*/

            // 生成令牌
            jwtUser.setClient(ClientStatus.APP.ordinal());
            jwtUser.getUser().remove("password");
            final String token = jwtTokenUtils.generateToken(jwtUser);

            Map<String,Object> tempmap = new HashMap<String,Object>();
            tempmap.put("userId", jwtUser.getUserId());
            tempmap.put("token", this.tokenHeader + token);
            tempmap.put("roles", listroles);
            tempmap.put("rolesvalue", listrolesvalue);
            tempmap.put("user", jwtUser.getUser());

            result.put("type", "account");
            result.put("status", "ok");
            result.put("currentAuthority", listroles);
            result.put(DATASUCCESS, SUCCESSFLAG);
            result.put(DATARECORD, tempmap);
        } catch (Exception e) {
            result.put(DATASUCCESS, ERRORFLAG);
            result.put(DATAMESSAGE, "登录失败！" + e.getMessage());
        }

        // 返回 token
        return result;
    }

    /**
     * 获取登陆用户信息
     * @param map
     * @return
     */
    @PostMapping(value = "${jwt.auth.account}")
    @ApiOperation(value="根据-{用户名}-获取用户信息", notes="成功返回:{\"success\":true,\"message\",\"登陆成功\"},失败返回:{\"success\":false,\"message\",\"数据失败\"}")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="body", name = "username", value = "用户名", required = true,  dataTypeClass = String.class)
    })
    @OperateLog(name = "获取登陆用户信息",value = "query",type = "PC")
    public Map<String, Object> currentUser(HttpServletRequest request , HttpServletResponse response, @RequestBody Map<String, Object> map){
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            JwtUser jwtUser = new JwtUser();
            String username = SecurityUtils.getUsername();

            Map<String, Object> parms = new HashMap();
            parms.put("user_name",username);
            Map<String, Object> userMap = proUserService.getOneByUserName(parms);

            if(null!=jwtUser) {
                result.putAll(userMap);
                result.put("name", userMap.get("user_name"));
                result.put("userid", userMap.get("user_id"));
                result.put("signature", userMap.get("signature"));
                result.put("group", "飞利信金融－某某某事业群－" + userMap.get("dept") + "-" + userMap.get("job"));
                result.put("tags", JSONArray.parse(userMap.get("tags") + ""));

                Map<String, Object> tempgeomapson0 = new HashMap<String, Object>();

                Map<String, Object> tempgeomapson = new HashMap<String, Object>();

                //            tempgeomapson.put("label", "北京省");
                //            tempgeomapson.put("key", "330000");
                tempgeomapson0.put("province", JSONObject.parse( "" + userMap.get("province")));

                //            tempgeomapson = new HashMap<String, Object>();
                //            tempgeomapson.put("label", "北京省");
                //            tempgeomapson.put("key", "330100");
                tempgeomapson0.put("city", JSONObject.parse("" + userMap.get("city")));

                result.put("geographic", tempgeomapson0);
            }

        } catch (Exception e) {
            result.put(DATASUCCESS, ERRORFLAG);
            result.put(DATAMESSAGE, "获取用户信息失败！" + e.getMessage());
        }

        // 返回 token
        return result;
    }
}
