package com.ruoyi.api.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.lang.LangUnit;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
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 org.springframework.web.servlet.LocaleResolver;

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

/**
 * API Controller
 *
 * @author Leo
 * @date 22-05-10
 */
//@Api(tags = "1 账户接口")
//@ApiSupport(order = 1)
@RestController
@RequestMapping("/wx/api")
public class UserApiController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysDictDataService sysDictService;

    @Autowired
    private LangUnit langUnit;

    @Autowired
    private LocaleResolver localeResolver;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 用户登录
     *
     * @param loginBody 登录信息
     * @return 结果
     */
//    @ApiOperation(value = "1.1 用户登录")
//    @ApiOperationSupport(order = 1)
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody, HttpServletRequest request, HttpServletResponse response)
    {
        AjaxResult ajax = AjaxResult.success();
        String userName = loginBody.getUsername();

        // 生成令牌
        String token = loginService.login(userName, loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid(), request);
        ajax.put(Constants.TOKEN, token);

        //读取配置文件
        if (StringUtils.isNotNull(token) && StringUtils.isNotEmpty(token)){
            SysUser sysUser = userService.selectUserByUserName(userName);
            if (sysUser != null) {
                String langStr  = sysUser.getLanguage();
                if (langStr == null || langStr == ""){
                    langStr = "zh";
                }
                Locale locale = new Locale(langStr);
                localeResolver.setLocale(request, response, locale);
                // 保存用户语言到redis中
                redisCache.setCacheObject(Constants.USER_LANGUAGE_KEY + sysUser.getUserId(), langStr);
            }
        }
        return ajax;
    }

//    @ApiOperation(value = "1.2 用户详情")
//    @ApiOperationSupport(order = 2)
    @PostMapping("/userInfo")
    @PreAuthorize("@ss.hasPermi('wx:user:info')")
    public String getUser(HttpServletRequest request) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("code", 200);
        jsonObj.put("msg", "success");

        String userName = getUsername();
        SysUser sysUser = userService.selectUserByUserName(userName);
        if (sysUser != null) {
            JSONObject jsonObjSub = addOneSysUser(sysUser, sysUser.getLanguage());
            jsonObj.put("data", jsonObjSub);
        }

        //设置LoginUser
        LoginUser loginUser = getLoginUser();
        if (loginUser != null) {
            SysUser sysUser1 = loginUser.getUser();
            if (sysUser1 != null) {
                sysUser1.setLanguage(sysUser.getLanguage());
            }
        } // end if

        return jsonObj.toJSONString();
    }

    public JSONObject addOneSysUser(SysUser sysUser, String language) {
        JSONObject jsonOne = new JSONObject();
        jsonOne.put("userId",     sysUser.getUserId());
        jsonOne.put("userName",     sysUser.getUserName());
        String nickName = sysUser.getNickName();
        if (StringUtils.isNotNull(language) && StringUtils.isNotEmpty(language) && (language.equals("zh") == false)) {
            if (StringUtils.isNotEmpty(sysUser.getNickNameEn())) {
                nickName = sysUser.getNickNameEn();
            }
        }
        jsonOne.put("nickName",     nickName);

        jsonOne.put("sex",          sysUser.getSex());
        jsonOne.put("email",        sysUser.getEmail());
        jsonOne.put("phoneumber",   sysUser.getPhonenumber());
        jsonOne.put("language",     sysUser.getLanguage());

        jsonOne.put("loginIp",      sysUser.getLoginIp());
        jsonOne.put("loginDate",    sysUser.getLoginDate());

        Long deptId = sysUser.getDept().getDeptId();
        jsonOne.put("deptId",       deptId );
        String deptName = sysUser.getDept().getDeptName();
        if (StringUtils.isNotNull(language) && StringUtils.isNotEmpty(language) && (language.equals("zh") == false)) {
            //查对应语言部门名称
            String deptNameEn = sysDeptService.selectDeptName(deptId, language);
            if (StringUtils.isNotEmpty(deptNameEn)) {
                deptName = deptNameEn;
            }
        }
        jsonOne.put("deptName",     deptName);
        String urlPrefix = configService.selectConfigByKey("iot.profile.urlPrefix");
        jsonOne.put("avatar",     StringUtils.isNotEmpty(sysUser.getAvatar()) ? urlPrefix + sysUser.getAvatar() : "");

        List<Long> roleList = roleService.selectRoleListByUserId(sysUser.getUserId());
        ArrayList roleArr = new ArrayList();
        for (Long roleId : roleList) {
            SysRole role = roleService.selectRoleById(roleId);
            if (role != null) {
                roleArr.add(role.getRoleKey());
            }
        }
        jsonOne.put("roleArr",  roleArr.toString());
        jsonOne.put(Constants.UUID, getUserUUID());

        return jsonOne;
    }

    /**
     * 重置密码
     */
    @Log(title = "账户接口", businessType = BusinessType.UPDATE)
//    @ApiOperation(value = "1.3 重置密码")
//    @ApiOperationSupport(order = 3)
    @PostMapping("/updatePwd")
    @PreAuthorize("@ss.hasPermi('wx:user:updatePwd')")
    public String updatePwd(String oldPassword, String newPassword)
    {
        JSONObject jsonObj = new JSONObject();

        LoginUser loginUser = getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            jsonObj.put("code", 1001);
            jsonObj.put("msg",  langUnit.getValueTag("userApi.updatePwd.1001","修改密码失败，旧密码错误") );
            return jsonObj.toJSONString();
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            jsonObj.put("code", 1002);
            jsonObj.put("msg",  langUnit.getValueTag("userApi.updatePwd.1002","新密码不能与旧密码相同") );
            return jsonObj.toJSONString();
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);

            jsonObj.put("code", 200);
            jsonObj.put("msg", "success");
            return jsonObj.toJSONString();
        }

        jsonObj.put("code", 1003);
        jsonObj.put("msg",  langUnit.getValueTag("userApi.updatePwd.1003","修改密码异常，请联系管理员") );
        return jsonObj.toJSONString();
    }

}
