package com.yonge.cooleshow.teacher.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.TeacherDto;
import com.yonge.cooleshow.biz.dal.entity.Subject;
import com.yonge.cooleshow.biz.dal.entity.Teacher;
import com.yonge.cooleshow.biz.dal.entity.TenantInfo;
import com.yonge.cooleshow.biz.dal.entity.TenantUnbindRecord;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.service.SmsCodeService;
import com.yonge.cooleshow.biz.dal.service.SubjectService;
import com.yonge.cooleshow.biz.dal.service.SysUserService;
import com.yonge.cooleshow.biz.dal.service.TeacherService;
import com.yonge.cooleshow.biz.dal.service.TenantInfoService;
import com.yonge.cooleshow.biz.dal.service.TenantUnbindRecordService;
import com.yonge.cooleshow.biz.dal.vo.MyFens;
import com.yonge.cooleshow.biz.dal.vo.TeacherHomeVo;
import com.yonge.cooleshow.biz.dal.vo.TeacherVo;
import com.yonge.cooleshow.biz.dal.wrapper.teacher.TeacherWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.ETenantUnBindAuditStatus;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.base.page.QueryInfo;
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.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.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("${app-config.url.teacher:}/teacher")
@Api(value = "教师表", tags = "教师表")
public class TeacherController extends BaseController {
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SmsCodeService smsCodeService;

    @Autowired
    private TenantUnbindRecordService tenantUnbindRecordService;

    @Autowired
    private TenantInfoService tenantInfoService;

    @Autowired
    private SubjectService subjectService;

    @ApiOperation(value = "我的-查询教师基本信息")
    @GetMapping("/queryUserInfo")
    public HttpResponseResult<TeacherHomeVo> queryUserInfo() {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return teacherService.queryUserInfo(user.getId());
    }

    @ApiOperation(value = "开通直播")
    @GetMapping("/openLive")
    public HttpResponseResult<Boolean> openLive() {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return teacherService.openLive(user.getId());
    }

    @ApiOperation(value = "获取老师可授课声部列表")
    @PostMapping("/querySubject")
    public HttpResponseResult<List<Subject>> querySubject() {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(teacherService.querySubject(user.getId()));
    }

    @ApiOperation(value = "设置声部")
    @GetMapping("/setSubject")
    public HttpResponseResult setSubject(@ApiParam(value = "声部主键集合", required = true) @RequestParam("subjectIds") String subjectIds) {
        if (StringUtil.isEmpty(subjectIds)) {
            return failed("参数不能为空");
        }

        if (subjectIds.split(",").length > 5) {
            return failed("最多选择5个乐器");
        }

        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return status(teacherService.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(teacherService.querySubjectItem(user.getId(), type));
    }

    @ApiOperation(value = "我的-个人风采")
    @GetMapping("/queryTeacherStyle")
    public HttpResponseResult<TeacherVo> queryTeacherStyle() {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return HttpResponseResult.succeed(teacherService.detail(user.getId()));
    }

    @ApiOperation(value = "我的-个人风采保存")
    @PostMapping("/saveTeacherStyle")
    public HttpResponseResult<TeacherVo> saveTeacherStyle(@RequestBody TeacherDto teacherDto) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        if (StringUtil.isEmpty(teacherDto.getSubjectId())) {
            return failed("请选择乐器");
        }
        teacherDto.setUserId(user.getId());
        return teacherService.saveTeacherStyle(teacherDto);
    }

    @ApiOperation(value = "我的粉丝")
    @PostMapping(value = "/queryMyFans")
    public HttpResponseResult<PageInfo<MyFens>> queryMyFans(@RequestBody QueryInfo query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null || sysUser.getId() == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }

        IPage<MyFens> pages = teacherService.queryMyFans(PageUtil.getPage(query), sysUser.getId());
        return succeed(PageUtil.pageInfo(pages));
    }


    /**
     * 最近练习
     */
    @PostMapping("/defaultSubject")
    @ApiOperation(value = "设置老师默认查询声部")
    public HttpResponseResult defaultSubject(@RequestParam(required = false) Long subjectId) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        if (subjectId == null) {
            return succeed();
        }
        Teacher teacher = new Teacher();
        teacher.setUserId(sysUser.getId());
        teacher.setDefaultSubject(subjectId);
        return succeed(teacherService.updateById(teacher));
    }

    @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.TEACHER);
        return succeed(idcardInfoExtractor);
    }

    @PostMapping("/unbindTenant")
    @ApiOperation(value = "解绑机构申请")
    public HttpResponseResult<Boolean> unbindTenant(@Validated @RequestBody TeacherWrapper.UnbindTenant unbindTenant) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        boolean validCode = smsCodeService.verifyValidCode(user.getPhone(), unbindTenant.getCode(), "");
        if (!validCode) {
            return failed("验证码错误");
        }
        if (user.getTenantId() == null || user.getTenantId() == -1) {
            return failed("非机构用户不需要解绑");
        }

        Teacher teacher = teacherService.getById(user.getId());
        if (teacher == null) {
            return failed("未查询到老师的信息");
        }


        TenantInfo tenantInfo = tenantInfoService.getById(user.getTenantId());
        TenantUnbindRecord tenantUnbindRecord = new TenantUnbindRecord();

        TenantUnbindRecord one = tenantUnbindRecordService.lambdaQuery()
                .eq(TenantUnbindRecord::getUserType, "TEACHER")
                .eq(TenantUnbindRecord::getUserId, user.getId())
                .last("limit 1").one();
        if(one != null) {
            if(ETenantUnBindAuditStatus.DOING.equals(one.getStatus())){
                return failed("请勿重复提交申请");
            }
            tenantUnbindRecord.setId(one.getId());
        }

        tenantUnbindRecord.setTenantId(user.getTenantId());
        tenantUnbindRecord.setTenantName(tenantInfo == null ? "" : tenantInfo.getName());
        tenantUnbindRecord.setUserId(user.getId());
        tenantUnbindRecord.setUserName(user.getUsername());
        tenantUnbindRecord.setPhone(user.getPhone());

        String subjectId = teacher.getSubjectId();
        if (StringUtils.isNotEmpty(subjectId)) {
            List<Long> subjectIdList = Arrays.stream(subjectId.split(",")).map(Long::valueOf)
                    .collect(Collectors.toList());
            List<Subject> subject = subjectService.findBySubjectByIdList(subjectIdList);
            String subjectName = subject.stream().map(Subject::getName).collect(Collectors.joining(","));
            tenantUnbindRecord.setSubjectName(subjectName);
        }

        tenantUnbindRecord.setUserType("TEACHER");
        tenantUnbindRecord.setUnbindReason(unbindTenant.getUnbindReason());
        tenantUnbindRecord.setStatus(ETenantUnBindAuditStatus.DOING);
        tenantUnbindRecordService.saveOrUpdate(tenantUnbindRecord);

        if (one != null) {
            tenantUnbindRecordService.lambdaUpdate()
                    .set(TenantUnbindRecord::getVerifyUserId, null)
                    .set(TenantUnbindRecord::getReason, null)
                    .set(TenantUnbindRecord::getInterveneTime, null)
                    .eq(TenantUnbindRecord::getId, one.getId())
                    .update();
        }
        return succeed();
    }

    @PostMapping("/unbindTenantCancel")
    @ApiOperation(value = "解绑机构申请撤销")
    public HttpResponseResult<Boolean> unbindTenantCancel() {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        boolean update = tenantUnbindRecordService.lambdaUpdate()
                .eq(TenantUnbindRecord::getUserId, user.getId())
                .eq(TenantUnbindRecord::getTenantId, user.getTenantId())
                .eq(TenantUnbindRecord::getStatus, ETenantUnBindAuditStatus.DOING)
                .set(TenantUnbindRecord::getStatus, ETenantUnBindAuditStatus.CANCEL)
                .update();
        if (!update) {
            throw new BizException("未查询到提交的申请记录");
        }
        return succeed();

    }

    @GetMapping("/unbindTenantDetail")
    @ApiOperation(value = "解绑机构申请记录")
    public HttpResponseResult<TenantUnbindRecord> unbindTenantDetail() {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }

        TenantUnbindRecord one = tenantUnbindRecordService.lambdaQuery()
                .eq(TenantUnbindRecord::getUserId, user.getId())
                .eq(TenantUnbindRecord::getTenantId, user.getTenantId())
                .eq(TenantUnbindRecord::getStatus, ETenantUnBindAuditStatus.DOING)
                .orderByDesc(TenantUnbindRecord::getId)
                .last("limit 1").one();
        return succeed(one);

    }
}