package com.yonge.cooleshow.teacher.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
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.*;
import com.yonge.cooleshow.biz.dal.enums.AuthStatusEnum;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.service.*;
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.TeacherFreeTimeWrapper;
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.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
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 {
    @Resource
    private TeacherService teacherService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SmsCodeService smsCodeService;
    @Resource
    private TenantUnbindRecordService tenantUnbindRecordService;
    @Resource
    private TenantInfoService tenantInfoService;
    @Resource
    private SubjectService subjectService;

    @ApiOperation(value = "我的-查询教师基本信息")
    @GetMapping("/queryUserInfo")
    public HttpResponseResult<TeacherHomeVo> queryUserInfo() {
        return teacherService.queryUserInfo(sysUserService.getUserId());
    }

    @ApiOperation(value = "设置系统默认客服")
    @GetMapping("/updateUserCustomerService")
    public HttpResponseResult<String> updateUserCustomerService() {
        return succeed(teacherService.updateUserCustomerService(sysUserService.getUserId()));
    }


    /**
     * 查询单条
     */
    @GetMapping("/detail/{id}")
    public HttpResponseResult<TeacherVo> detail(@PathVariable("id") Long userId) {
        Teacher teacher = teacherService.getById(sysUserService.getUserId());
        if (Boolean.FALSE.equals(teacher.getCustomerService())) {
            throw new BizException("权限不足");
        }

        TeacherVo detail = teacherService.findTeacherDetailInfo(userId);
        if (null != detail && !CollectionUtils.isEmpty(detail.getStyleVideo())) {
            List<TeacherStyleVideo> styleVideo = detail.getStyleVideo();
            List<TeacherStyleVideo> collect = styleVideo.stream().filter(o -> AuthStatusEnum.PASS.equals(o.getAuthStatus())).collect(Collectors.toList());
            detail.setStyleVideo(collect);
        }
        return succeed(detail);
    }

    @ApiOperation(value = "开通直播")
    @GetMapping("/openLive")
    public HttpResponseResult<Boolean> openLive() {
        return teacherService.openLive(sysUserService.getUserId());
    }

    @ApiOperation(value = "获取老师可授课声部列表")
    @PostMapping("/querySubject")
    public HttpResponseResult<List<Subject>> querySubject() {
        List<Subject> subjects = teacherService.querySubject(sysUserService.getUserId());
        subjectService.convertSubject(subjects);
        return succeed(subjects);
    }

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

        if (subjectIds.split(",").length > 5) {
            return failed("最多选择5个乐器");
        }
        return status(teacherService.setSubject(sysUserService.getUserId(), subjectIds) > 0);
    }

    @ApiOperation(value = "获取声部搜索下拉框")
    @PostMapping("/querySubjectItem")
    public HttpResponseResult<List<Subject>> querySubjectItem(
            @ApiParam(value = "类型 PRACTICE 趣纠课 LIVE 直播课 VIDEO 视频课 PIANO_ROOM 琴房 MUSIC 曲目 ") String type) {
        List<Subject> subjects = teacherService.querySubjectItem(sysUserService.getUserId(), type);
        subjectService.convertSubject(subjects);
        return succeed(subjects);
    }

    @ApiOperation(value = "我的-个人风采")
    @GetMapping("/queryTeacherStyle")
    public HttpResponseResult<TeacherVo> queryTeacherStyle() {
        return HttpResponseResult.succeed(teacherService.detail(sysUserService.getUserId()));
    }

    @ApiOperation(value = "我的-个人风采保存")
    @PostMapping("/saveTeacherStyle")
    public HttpResponseResult<TeacherVo> saveTeacherStyle(@RequestBody TeacherDto teacherDto) {
        if (StringUtil.isEmpty(teacherDto.getSubjectId())) {
            return failed("请选择乐器");
        }
        teacherDto.setUserId(sysUserService.getUserId());
        return teacherService.saveTeacherStyle(teacherDto);
    }

    @ApiOperation(value = "我的粉丝")
    @PostMapping(value = "/queryMyFans")
    public HttpResponseResult<PageInfo<MyFens>> queryMyFans(@RequestBody QueryInfo query) {
        IPage<MyFens> pages = teacherService.queryMyFans(PageUtil.getPage(query), sysUserService.getUserId());
        return succeed(PageUtil.pageInfo(pages));
    }


    @ApiOperation(value = "移除粉丝")
    @PostMapping(value = "/delFans/{userId}")
    public HttpResponseResult<Void> delFans(@PathVariable("userId") Long userId) {
        teacherService.delFans(userId, sysUserService.getUserId());
        return succeed();
    }


    /**
     * 最近练习
     */
    @PostMapping("/defaultSubject")
    @ApiOperation(value = "设置老师默认查询声部")
    public HttpResponseResult defaultSubject(@RequestParam(required = false) Long subjectId) {
        if (subjectId == null) {
            return succeed();
        }
        Teacher teacher = new Teacher();
        teacher.setUserId(sysUserService.getUserId());
        teacher.setDefaultSubject(subjectId);
        return succeed(teacherService.updateById(teacher));
    }

    @PostMapping("/realNameAuth")
    @ApiOperation(value = "实名认证", notes = "传入realNameAuthDto")
    @ResponseBody
    public HttpResponseResult<IdcardInfoExtractor> realNameAuth(@Valid @RequestBody RealnameAuthReq realNameAuthDto) {
        IdcardInfoExtractor idcardInfoExtractor = sysUserService.updateUserCard(realNameAuthDto, sysUserService.getUser(),
                ClientEnum.TEACHER);
        return succeed(idcardInfoExtractor);
    }

    @PostMapping("/unbindTenant")
    @ApiOperation(value = "解绑机构申请")
    public HttpResponseResult<Boolean> unbindTenant(@Validated @RequestBody TeacherWrapper.UnbindTenant unbindTenant) {
        SysUser user = sysUserService.getUser();
        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 = sysUserService.getUser();
        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 = sysUserService.getUser();
        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);

    }

    //获取老师可排课时间段
    @ApiOperation(value = "获取老师可排课时间段")
    @GetMapping("/queryTeacherTime")
    public HttpResponseResult<TeacherFreeTimeWrapper.TeacherFreeConfig> queryTeacherTime() {
        return succeed(teacherService.queryTeacherTime());
    }
}