package com.yonge.cooleshow.student.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.dto.RealnameAuthReq;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dto.search.QueryMyFollowSearch;
import com.yonge.cooleshow.biz.dal.entity.Student;
import com.yonge.cooleshow.biz.dal.entity.Subject;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.service.SmsCodeService;
import com.yonge.cooleshow.biz.dal.service.StudentService;
import com.yonge.cooleshow.biz.dal.service.SysUserService;
import com.yonge.cooleshow.biz.dal.vo.MyFollow;
import com.yonge.cooleshow.biz.dal.vo.StudentHomeVo;
import com.yonge.cooleshow.biz.dal.wrapper.StudentWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.base.util.StringUtil;
import com.yonge.toolset.mybatis.support.PageUtil;
import com.yonge.toolset.utils.idcard.IdcardInfoExtractor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("${app-config.url.student:}/student")
@Api(value = "学生表", tags = "学生表")
public class StudentController extends BaseController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SmsCodeService smsCodeService;


    @ApiOperation(value = "查询指定学员信息")
    @GetMapping("/queryUserById")
    public HttpResponseResult<com.yonge.cooleshow.biz.dal.vo.StudentVo> queryUserById(String rongCloudUserId) {

        if (StringUtil.isEmpty(rongCloudUserId)) {
            return failed("用户信息获取失败");
        }

        Long userId = null;
        String[] split = rongCloudUserId.split(":");
        if (split.length == 2 && !StringUtil.isEmpty(split[0])) {
            try {
                userId = Long.parseLong(split[0]);
            } catch (Exception e) {
                e.printStackTrace();
                return failed("用户信息获取失败");
            }
        }
        return succeed(studentService.detail(userId));
    }

    @ApiOperation(value = "查询学员")
    @GetMapping("/queryUser")
    public HttpResponseResult<Student> queryUser() {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        Student student = studentService.getById(user.getId());
        return succeed(student);
    }

    @ApiOperation(value = "查询学员基本信息")
    @GetMapping("/queryUserInfo")
    public HttpResponseResult<StudentHomeVo> queryUserInfo() throws Exception {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(studentService.queryUserInfo(user));
    }

    @ApiOperation(value = "设置声部")
    @GetMapping("/setSubject")
    public HttpResponseResult setSubject(@ApiParam(value = "声部主键集合", required = true) @RequestParam("subjectIds") String subjectIds) {
        if (StringUtil.isEmpty(subjectIds)) {
            return failed("参数不能为空");
        }
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return status(studentService.setSubject(user.getId(), subjectIds) > 0);
    }

    @ApiOperation(value = "获取声部搜索下拉框")
    @PostMapping("/querySubjectItem")
    public HttpResponseResult<List<Subject>> querySubjectItem(
            @ApiParam(value = "类型 PRACTICE 陪练课 LIVE 直播课 VIDEO 视频课 PIANO_ROOM 琴房 MUSIC 曲目 ") String type) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(studentService.querySubjectItem(user.getId(), type));
    }

    @ApiOperation(value = "我的关注")
    @PostMapping(value = "/queryMyFollow")
    public HttpResponseResult<PageInfo<MyFollow>> queryMyFollow(@RequestBody QueryMyFollowSearch query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null || sysUser.getId() == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        query.setUserId(sysUser.getId());
        IPage<MyFollow> pages = studentService.queryMyFollow(PageUtil.getPage(query), query);
        return succeed(PageUtil.pageInfo(pages));
    }

    @PostMapping("/realNameAuth")
    @ApiOperation(value = "实名认证", notes = "传入realNameAuthDto")
    @ResponseBody
    public HttpResponseResult<IdcardInfoExtractor> realNameAuth(@Valid @RequestBody RealnameAuthReq realNameAuthDto) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        IdcardInfoExtractor idcardInfoExtractor = sysUserService.updateUserCard(realNameAuthDto, user,
                ClientEnum.STUDENT);
        return succeed(idcardInfoExtractor);
    }

    @PostMapping("/logoffAccount")
    @ApiOperation(value = "注销学生账户")
    public HttpResponseResult<Boolean> logoffAccount(@RequestParam("code") String code) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        if (StringUtils.isEmpty(code)) {
            return failed("验证码不能为空");
        }
        boolean validCode = smsCodeService.verifyValidCode(user.getPhone(), code, "");
        if (!validCode) {
            return failed("验证码错误");
        }

        studentService.lambdaUpdate()
                .set(Student::getLockFlag, true)
                .set(Student::getHideFlag, true)
                .eq(Student::getUserId, user.getId())
                .update();
        user.setDelFlag(true);
        sysUserFeignService.update(user);
        return succeed();
    }


    @PostMapping("/checkPassword")
    @ApiOperation(value = "校验密码")
    public Object checkPassword(@Validated @RequestBody StudentWrapper.StudentUpdatePassword updatePassword){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(!encoder.matches(updatePassword.getPassword(),sysUser.getPassword())){
            throw new BizException("原密码错误");
        }
        return succeed();
    }

}