package com.younike.admin.controller.system;


import com.younike.admin.shiro.authc.SmsToken;
import com.younike.admin.utils.ShiroUtils;
import com.younike.common.annotation.OpLog;
import com.younike.common.constant.BusinessType;
import com.younike.common.constant.Constants;
import com.younike.common.constant.OperatorType;
import com.younike.common.core.dto.AjaxResult;
import com.younike.common.redis.ICached;
import com.younike.common.utils.i18n.MessageUtils;
import com.younike.common.utils.string.RandomUtil;
import com.younike.service.pojo.SysMenu;
import com.younike.service.pojo.SysUser;
import com.younike.service.service.ISysMenuService;
import com.younike.service.service.ISysRoleService;
import com.younike.service.service.ISysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

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

import static com.younike.common.core.dto.AjaxResult.success;

/**
 * 登录验证
 */
@RestController
public class SysLoginController {

    @Autowired
    ICached iCached;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysUserService sysUserService;


    @PostMapping("/login")
    @OpLog(type = BusinessType.LOGIN, operatorType = OperatorType.MANAGE, isSaveRequestData = false)
    public AjaxResult ajaxLogin(HttpServletRequest request, @RequestBody Map<String, String> payload) {
        request.setAttribute("captcha", payload.get("code"));
        request.setAttribute("uuid", payload.get("uuid"));
        UsernamePasswordToken token = new UsernamePasswordToken(payload.get("username"), payload.get("password"));
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        return success();

    }

    @PostMapping("/sms-login")
    public AjaxResult smsLogin(@RequestBody Map<String, String> payload) {
        SmsToken token = new SmsToken(payload.get("username"), payload.get("code"));
        Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            return success();

    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping(path = "/getInfo")
    public AjaxResult getInfo() {
        // 取身份信息
        SysUser user = ShiroUtils.getSysUser();
        if (user == null) {
            return AjaxResult.error("登录信息超时，请重新登录");
        }

        AjaxResult ajax = success();
        // 用户信息
        ajax.put("user", user);
        // 用户角色字符串集合
        ajax.put("roles", roleService.getRoles(user));
        // 用户权限字符串集合
        ajax.put("permissions", menuService.getMenuPermissions(user));
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public AjaxResult getRouters() {
        // 取身份信息
        SysUser user = ShiroUtils.getSysUser();
        List<SysMenu> menus = menuService.selectMenusByUser(user);
        return success(menuService.buildMenus(menus));
    }


    @GetMapping("/sendSms")
    public AjaxResult sendSmsCompanyLogin(@RequestParam("phone") String phone) {
        SysUser sysUser = sysUserService.selectUserByPhoneNumber(phone);
        if (!ObjectUtils.isEmpty(sysUser)) {
            if ("1".equals(sysUser.getStatus())) {
                // 如果手机号已经被禁用。则提示账户已冻结
                return AjaxResult.error(MessageUtils.message("user.blocked"));
            }
            if ("2".equals(sysUser.getDelFlag())) {
                return AjaxResult.error(MessageUtils.message("user.password.delete"));
            }
            String code = RandomUtil.numberRandon(6);
//            JSONObject param = new JSONObject();
//            param.put("code", code);
//            smsUtil.sendSms(phone, param, AliTemplateCode.AUTHENTICATION_CODE);
            iCached.put(Constants.SMS_LOGIN_CODE, phone, code);
            return success();
        } else {
            return AjaxResult.error(MessageUtils.message("user.not.exists"));
        }
    }
}
