package yangtz.cs.liu.wechat.controller.api;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.MpLoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.framework.util.UserInfoUtil;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.MpTokenService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysUserService;

import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.bind.annotation.*;
import yangtz.cs.liu.campus.domain.student.SchoolStudent;
import yangtz.cs.liu.campus.service.impl.student.SchoolStudentParentServiceImpl;
import yangtz.cs.liu.campus.service.student.ISchoolStudentService;
import yangtz.cs.liu.wechat.domain.WxLoginBody;
import yangtz.cs.liu.wechat.service.api.IWxLoginService;

import javax.servlet.http.HttpServletRequest;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;
import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNull;
import static yangtz.cs.liu.wechat.constant.LoginTypeConstant.PARENT_LOGIN;
import static yangtz.cs.liu.wechat.constant.LoginTypeConstant.TEACHER_LOGIN;


/**
 * @author lyric
 * @date 2022/10/16 20:29
 * <p>
 * 登录接口
 */
@RestController
@RequestMapping("/wx/user")
public class WxLoginController extends BaseController {

    @Autowired
    private IWxLoginService loginService;

    @Autowired
    private MpTokenService mpTokenService;

    @Autowired
    UserInfoUtil userInfoUtil;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISchoolStudentService studentService;

    @Value("${ruoyi.serverAddress}")
    private String serverAddress;

    @Value("${server.port}")
    private String port;
    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SchoolStudentParentServiceImpl schoolStudentParentService;
    private Logger log = LoggerFactory.getLogger(WxLoginController.class);

    /**
     * @param wxLoginBody 登录信息
     * @return token
     * @author lyric
     * @date 2022/10/17 9:41
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody WxLoginBody wxLoginBody) {
        if (StringUtils.isEmpty(wxLoginBody.getType())) {
            throw new ServiceException("empty type");
        }
        MpLoginUser user = loginService.login(wxLoginBody);
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("login error");
        }
        String userName = TEACHER_LOGIN.equals(user.getType()) ? user.getTeacherName() : user.getParentName();
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        String token = mpTokenService.createToken(user);
        return AjaxResult.success().put(Constants.TOKEN, token);
    }
    @GetMapping("/getRoleType/{phonenumber}")
    public AjaxResult getRoleType(@PathVariable("phonenumber") String phonenumber){
        // 根据手机号查询家长手机号
        List<Map<String,Object>>  list =  schoolStudentParentService.getRoleTypeByPhoneNumber(phonenumber);
        return AjaxResult.success(list);
    }

    /**
     * @author lyric
     * @date 2022/10/17 9:48
     * <p>
     * 登录前发起请求 校验token
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        MpLoginUser mpLoginUser = userInfoUtil.getMpLoginUser();
        SysUser user = sysUserService.selectUserById(mpLoginUser.getUserId());
        //家长登录获取学生头像
        if(user.getUserLoginType().equals(PARENT_LOGIN)){
            SchoolStudent student = studentService.getById(user.getStudentId());
//            if(StringUtils.isNotNull(student.getAvatar()) && !"".equals(student.getAvatar())){
//                String url = serverAddress+student.getAvatar();
//                byte[] b = ImageUtils.readFile(url);
//                //转为base64传过去
//                String base64 = Base64.encodeBase64String(b);
//                student.setAvatar("data:image/jpeg;base64,"+base64);
//            }
            mpLoginUser.setAvatar(student.getAvatar());
        }else{
//            if(StringUtils.isNotNull(user.getAvatar()) && !"".equals(user.getAvatar())){
//                String url = serverAddress+user.getAvatar();
//                byte[] b = ImageUtils.readFile(url);
//                //转为base64传过去
//                String base64 = Base64.encodeBase64String(b);
//                user.setAvatar("data:image/jpeg;base64,"+base64);
//            }
            mpLoginUser.setAvatar(user.getAvatar());
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        mpLoginUser.setRoles(roles);
        return AjaxResult.success().put("userInfo",mpLoginUser);
    }

    /**
     *
     * @author lyric
     * @date 2022/11/19 21:31
     * 自定义退出逻辑
     */
    @GetMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        String mpToken = mpTokenService.getToken(request);
        MpLoginUser loginUser = mpTokenService.getMpLoginUser(mpToken);
        if (StringUtils.isNotNull(loginUser))
        {

            String userName = TEACHER_LOGIN.equals(loginUser.getType()) ? loginUser.getTeacherName() : loginUser.getParentName();
            // 删除用户缓存记录
            mpTokenService.delMpLoginUser(loginUser.getMpToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
        }
        return AjaxResult.success("退出成功");
    }

    //判断是否有token
    @GetMapping("/getToken")
    public AjaxResult getToken(HttpServletRequest request){
        String token = mpTokenService.getToken(request);
        MpLoginUser mpLoginUser = mpTokenService.getMpLoginUser(token);
        if (isNotNull(token)){
            try {
                mpTokenService.verifyToken(mpLoginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(mpLoginUser, null, null);
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                return AjaxResult.success(true);
            }catch (Exception e){
                return AjaxResult.success(false);
            }
        }
        return AjaxResult.success(false);
    }
}
