package com.dsk.web.controller.system;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.RegexPool;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import com.dsk.common.constant.Constants;
import com.dsk.common.constant.GlobalConstants;
import com.dsk.common.core.domain.R;
import com.dsk.common.exception.ServiceException;
import com.dsk.common.tenant.helper.TenantHelper;
import com.dsk.common.utils.StringUtils;
import com.dsk.common.utils.redis.RedisUtils;
import com.dsk.jsk.util.IpUtil;
import com.dsk.system.domain.SysMenu;
import com.dsk.system.domain.SysUser;
import com.dsk.common.core.domain.model.EmailLoginBody;
import com.dsk.common.core.domain.model.LoginBody;
import com.dsk.common.core.domain.model.LoginUser;
import com.dsk.common.core.domain.model.SmsLoginBody;
import com.dsk.common.helper.LoginHelper;
import com.dsk.system.domain.vo.LoginVo;
import com.dsk.system.domain.vo.RouterVo;
import com.dsk.system.domain.vo.SysTenantVo;
import com.dsk.system.service.ISysMenuService;
import com.dsk.system.service.ISysUserService;
import com.dsk.system.service.SysLoginService;
import lombok.RequiredArgsConstructor;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.dromara.sms4j.provider.enumerate.SupplierType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.time.Duration;
import java.util.*;

/**
 * 登录验证
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
public class SysLoginController {

    private final SysLoginService loginService;
    private final ISysMenuService menuService;
    private final ISysUserService userService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/login")
    public R<LoginVo> login(@Validated @RequestBody LoginBody loginBody, HttpServletRequest request) {


//        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
//        LoginVo loginVo = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
//            loginBody.getUuid());
//        ajax.put(Constants.TOKEN, token);
//        return R.ok(ajax);


        String ipAddr = IpUtil.getIpAddr(request);
        LoginVo loginVo = loginService.passwordLogin(loginBody, ipAddr);
        return R.ok(loginVo);
    }


//    /**
//     * 发送短信验证码
//     *
//     * @param phones     电话号
//     * @param templateId 模板ID
//     */
//    @SaIgnore
//    @GetMapping("/send/sms/code")
//    public R<Object> sendAliyun(String phones, String templateId) {
//        LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
//        map.put("code", RandomUtil.randomNumbers(4));
//        SmsBlend smsBlend = SmsFactory.createSmsBlend(SupplierType.ALIBABA);
//        SmsResponse smsResponse = smsBlend.sendMessage(phones, templateId, map);
//        return R.ok(smsResponse);
//    }

    /**
     * 短信登录
     *
     * @param smsLoginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/smsLogin")
    public R<LoginVo> smsLogin(@Validated @RequestBody SmsLoginBody smsLoginBody) {
        // 生成令牌
        LoginVo loginVo = loginService.smsLogin(smsLoginBody.getPhonenumber(), smsLoginBody.getSmsCode());
        return R.ok(loginVo);
    }


    /**
     * 动态切换租户
     */
    @SaCheckLogin
    @PostMapping("/switch/tenant")
    public R<LoginVo> switchTenant(String tenantId) {
        LoginVo loginVo = loginService.switchTenant(tenantId);
        return R.ok(loginVo);
    }


    /**
     * 用户租户列表：根据用户账号获取用户绑定的租户列表
     *
     * @return 结果
     */
    @SaCheckLogin
    @PostMapping("/user/tenants")
    public R<List<SysTenantVo>> userTenants() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<SysTenantVo> tenantList = loginService.tenantListByAccount(loginUser.getUserPhone());
        return R.ok(tenantList);
    }


    /**
     * 用户租户列表：根据用户账号获取用户绑定的租户列表
     *
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/user/tenant/list")
    public R<List<SysTenantVo>> userTenantList(String phone) {
        if (!ReUtil.isMatch(RegexPool.MOBILE, phone)) {
            return R.ok(new ArrayList<>());
        }
        List<SysTenantVo> tenantList = loginService.tenantListByAccount(phone);
        if (CollectionUtil.isNotEmpty(tenantList)) {
            for (SysTenantVo sysTenantVo : tenantList) {
                sysTenantVo.setCompanyName("");
            }
        }
        return R.ok(tenantList);
    }

    /**
     * 获取当前用户默认租户
     *
     * @return
     */
    @SaCheckLogin
    @PostMapping("/user/default/tenant")
    public R<Map> userDefaultTenant() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        Assert.notNull(loginUser, "用户信息不存在！");
        String defaultTenantKey = GlobalConstants.PHONE_DEFAULT_TENANT + loginUser.getUserPhone();
        String defaultTenant = RedisUtils.getCacheObject(defaultTenantKey);
        return R.ok(MapUtil.of("tenantId", defaultTenant));
    }


    /**
     * 获取当前用户默认租户
     *
     * @return
     */
    @SaIgnore
    @PostMapping("/user/default/tenant/phone")
    public R<Map> userDefaultTenant(String phone) {
//        LoginUser loginUser = LoginHelper.getLoginUser();
//        Assert.notNull(loginUser,"用户信息不存在！");
        String defaultTenantKey = GlobalConstants.PHONE_DEFAULT_TENANT + phone;
        String defaultTenant = RedisUtils.getCacheObject(defaultTenantKey);
        return R.ok(MapUtil.of("tenantId", defaultTenant));
    }

    /**
     * 邮件登录
     *
     * @param body 登录信息
     * @return 结果
     */
    @PostMapping("/emailLogin")
    public R<Map<String, Object>> emailLogin(@Validated @RequestBody EmailLoginBody body) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.emailLogin(body.getEmail(), body.getEmailCode());
        ajax.put(Constants.TOKEN, token);
        return R.ok(ajax);
    }

    /**
     * 小程序登录(示例)
     *
     * @param xcxCode 小程序code
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/xcxLogin")
    public R<Map<String, Object>> xcxLogin(@NotBlank(message = "{xcx.code.not.blank}") String xcxCode) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.xcxLogin(xcxCode);
        ajax.put(Constants.TOKEN, token);
        return R.ok(ajax);
    }

    /**
     * 退出登录
     */
    @SaIgnore
    @PostMapping("/logout")
    public R<Void> logout() {
        loginService.logout();
        return R.ok("退出成功");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public R<Map<String, Object>> getInfo(HttpServletRequest request) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        //校验当前发请求的IP与登录账号的IP是否相同
        String loginUserIpaddr = loginUser.getIpaddr();
        if (StringUtils.isNotBlank(loginUserIpaddr) && !Objects.equals(IpUtil.getIpAddr(request), loginUserIpaddr)) {
            throw new ServiceException("该账号已在其他地方登录，请求失败！", 401);
        }
        SysUser user = userService.selectUserById(loginUser.getUserId());
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("roles", loginUser.getRolePermission());
        ajax.put("permissions", loginUser.getMenuPermission());
        return R.ok(ajax);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public R<List<RouterVo>> getRouters() {
        Long userId = LoginHelper.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return R.ok(menuService.buildMenus(menus));
    }
}
