package com.yonge.cooleshow.tenant.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.microsvc.toolkit.common.webportal.exception.BizException;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dto.req.TeacherSubmitReq;
import com.yonge.cooleshow.biz.dal.dto.search.TeacherSearch;
import com.yonge.cooleshow.biz.dal.entity.Teacher;
import com.yonge.cooleshow.biz.dal.entity.TeacherStyleVideo;
import com.yonge.cooleshow.biz.dal.entity.TenantInfo;
import com.yonge.cooleshow.biz.dal.enums.AuthStatusEnum;
import com.yonge.cooleshow.biz.dal.service.OssFileService;
import com.yonge.cooleshow.biz.dal.service.TeacherService;
import com.yonge.cooleshow.biz.dal.service.TenantInfoService;
import com.yonge.cooleshow.biz.dal.vo.TeacherVo;
import com.yonge.cooleshow.biz.dal.wrapper.OssFileWrapper;
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.UserLockFlag;
import com.yonge.cooleshow.common.enums.UserStatusEnum;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.mybatis.support.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/teacher")
@Api(value = "教师表", tags = "教师表")
public class TeacherController extends BaseController {

    @Autowired
    private TeacherService teacherService;

    @Resource
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private TenantInfoService tenantInfoService;

    @Autowired
    private OssFileService ossFileService;

    /**
     * 查询单条
     */
    @GetMapping("/detail/{id}")
    @ApiOperation(value = "详情", notes = "传入id")
    public HttpResponseResult<TeacherVo> detail(@PathVariable("id") Long userId) {
        TeacherVo detail = teacherService.findTeacherDetailInfo(userId);
        if (detail == null) {
            throw new BizException("数据不存在");
        }
        if (!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);
    }

    /**
     * 查询分页
     */
    @PostMapping("/page")
    @ApiOperation(value = "查询分页", notes = "传入teacher")
    public HttpResponseResult<PageInfo<TeacherVo>> page(@RequestBody TeacherSearch query) {
        TenantInfo tenantInfo = getTenantInfo();
        query.setTenantId(tenantInfo.getId());
        query.setDelFlag(YesOrNoEnum.NO);
        query.setLockFlag(UserLockFlag.NORMAL);
        query.setOrderBy("u.username_ asc");

        IPage<TeacherVo> pages = teacherService.selectPage(PageUtil.getPage(query), query);
        List<TeacherVo> rows = pages.getRecords();

        for (TeacherVo vo : rows) {
            if (StringUtils.isNotEmpty(vo.getPhone())) {
                vo.setPhone(vo.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            }
            if (vo.getDelFlag() == YesOrNoEnum.YES) {
                vo.setUserStatus(UserStatusEnum.CLOSED);
            } else {
                if (vo.getLockFlag() == UserLockFlag.LOCKED) {
                    vo.setUserStatus(UserStatusEnum.LOCKED);
                } else {
                    vo.setUserStatus(UserStatusEnum.NORMAL);
                }
            }
        }
        return succeed(PageUtil.pageInfo(pages));
    }


    @PostMapping("/exportTeacher")
    @ApiOperation(value = "导出老师", notes = "传入TeacherSearch")
    public HttpResponseResult<OssFileWrapper.ExportFile> exportTeacher(@RequestBody TeacherSearch query) {
        TenantInfo tenantInfo = getTenantInfo();
        query.setTenantId(tenantInfo.getId());
        query.setDelFlag(YesOrNoEnum.NO);
        query.setLockFlag(UserLockFlag.NORMAL);
        query.setPage(1);
        query.setRows(9999);
        query.setOrderBy("u.username_ asc");

        IPage<TeacherVo> pages = teacherService.selectPage(PageUtil.getPage(query), query);
        List<TeacherVo> rows = pages.getRecords();

        if (rows.isEmpty()) {
            throw new BizException("没有可导出数据");
        }

        List<TeacherWrapper.ExportTeacherTemplate> templates = rows.stream().map(next -> {
            TeacherWrapper.ExportTeacherTemplate template = new TeacherWrapper.ExportTeacherTemplate();
            template.setUserName(next.getUsername());
            template.setPhone(next.getPhone());
            template.setMusicSheet(next.getMusicSheetName());
            template.setSubjectName(next.getSubjectName());
            template.setSettlementFrom(next.getSettlementFrom() == null ? "" : next.getSettlementFrom().getMsg());
            return template;
        }).collect(Collectors.toList());

        String format = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
        OssFileWrapper.ExportFile exportFile = ossFileService.uploadFile(templates,
                TeacherWrapper.ExportTeacherTemplate.class, format, "老师", "teacher");
        return succeed(exportFile);
    }

    /**
     * 新增或修改
     */
    @PostMapping("/submit")
    @ApiOperation(value = "新增或修改", notes = "传入teacher")
    public HttpResponseResult<Boolean> submit(@Valid @RequestBody TeacherSubmitReq teacherSubmitReq) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        TenantInfo tenantInfo = tenantInfoService.getById(sysUser.getTenantId());
        if (tenantInfo == null) {
            throw new BizException("非法请求");
        }
        if (teacherSubmitReq.getUserId() != null) {
            Teacher teacher = teacherService.lambdaQuery().eq(Teacher::getUserId, teacherSubmitReq.getUserId())
                    .eq(Teacher::getTenantId, tenantInfo.getId()).last("limit 1").one();
            if (teacher == null) {
                throw new BizException("老师不存在");
            }
        }
        teacherSubmitReq.setTenantId(tenantInfo.getId());
        teacherSubmitReq.setUpdateBy(sysUser.getId());
        return teacherService.submit(teacherSubmitReq);
    }

    @PostMapping("/setSettlement")
    @ApiOperation(value = "设置结算方式")
    public HttpResponseResult<Boolean> setSettlement(@Valid @RequestBody TeacherWrapper.TeacherSetSettlement setSettlement) {

        List<Long> teacherIdList = setSettlement.getTeacherIdList();
        if (teacherIdList.isEmpty()) {
            throw new BizException("未选择老师");
        }

        TenantInfo tenantInfo = getTenantInfo();
        teacherService.lambdaUpdate()
                .set(Teacher::getSettlementFrom, setSettlement.getSettlementFrom())
                .eq(Teacher::getTenantId, tenantInfo.getId())
                .in(Teacher::getUserId, setSettlement.getTeacherIdList()).update();
        return succeed();
    }

    private TenantInfo getTenantInfo() {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        TenantInfo tenantInfo = tenantInfoService.getById(sysUser.getTenantId());
        if (tenantInfo == null) {
            throw new BizException("非法请求");
        }
        return tenantInfo;
    }
}