package com.yonge.cooleshow.admin.controller;

import com.alibaba.fastjson.JSON;
import com.yonge.cooleshow.admin.io.request.TeacherBindingUserVo;
import com.yonge.cooleshow.admin.io.request.coupon.CouponIssueVo;
import com.yonge.cooleshow.biz.dal.queryInfo.TeacherBindingUserQueryInfo;
import com.yonge.cooleshow.biz.dal.queryInfo.TeacherQueryInfo;
import com.yonge.cooleshow.biz.dal.service.UserBindingTeacherService;
import com.yonge.cooleshow.biz.dal.vo.userBindingTeacher.UserBindingCourseWrapper;
import com.yonge.cooleshow.biz.dal.vo.userBindingTeacher.UserBindingTeacherWrapper;
import com.yonge.cooleshow.admin.io.request.teacher.TeacherVO;
import com.yonge.cooleshow.biz.dal.vo.MyFens;
import com.yonge.cooleshow.biz.dal.wrapper.teacher.TeacherWrapper;
import com.yonge.toolset.base.page.QueryInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
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 com.baomidou.mybatisplus.core.metadata.IPage;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dto.TeacherDto;
import com.yonge.cooleshow.biz.dal.dto.VipSubmitReq;
import com.yonge.cooleshow.biz.dal.dto.req.TeacherSubmitReq;
import com.yonge.cooleshow.biz.dal.dto.search.TeacherSearch;
import com.yonge.cooleshow.biz.dal.dto.search.VipRecordSearch;
import com.yonge.cooleshow.biz.dal.entity.TeacherStyleVideo;
import com.yonge.cooleshow.biz.dal.enums.AuthStatusEnum;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.service.MemberPriceSettingsService;
import com.yonge.cooleshow.biz.dal.service.TeacherService;
import com.yonge.cooleshow.biz.dal.service.VipCardRecordService;
import com.yonge.cooleshow.biz.dal.vo.TeacherVo;
import com.yonge.cooleshow.biz.dal.vo.VipRecordVo;
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.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.date.DateUtil;
import com.yonge.toolset.utils.excel.POIUtil;

import static com.yonge.cooleshow.common.entity.HttpResponseResult.succeed;

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

    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private TeacherService teacherService;

    @Autowired
    private MemberPriceSettingsService memberPriceSettingsService;


    @Autowired
    private VipCardRecordService vipCardRecordService;

    @Autowired
    private UserBindingTeacherService userBindingTeacherService;

    /**
     * 查询单条
     */
    @GetMapping("/detail/{id}")
    @ApiOperation(value = "详情", notes = "传入id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "path", dataType = "long", required = true),
    })
    @PreAuthorize("@pcs.hasPermissions('teacher/detail')")
    public HttpResponseResult<TeacherVo> detail(@PathVariable("id") Long userId) {
        //TeacherVo detail = teacherService.detail(userId);

        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);
    }

    /**
     * 查询分页
     */
    @PostMapping("/page")
    @ApiOperation(value = "查询分页", notes = "传入teacher")
    @PreAuthorize("@pcs.hasPermissions('teacher/page')")
    public HttpResponseResult<PageInfo<TeacherVo>> page(@RequestBody TeacherSearch query) {
    	
    	if(StringUtils.isNotBlank(query.getUserStatus())){
    		switch (query.getUserStatus()) {
			case "LOCKED":
				query.setDelFlag(YesOrNoEnum.NO);
				query.setLockFlag(UserLockFlag.LOCKED);
				break;
			case "CLOSED":
				query.setDelFlag(YesOrNoEnum.YES);
				break;

			default:
				query.setDelFlag(YesOrNoEnum.NO);
				query.setLockFlag(UserLockFlag.NORMAL);
				break;
			}
    	}
        IPage<TeacherVo> pages = teacherService.selectPage(PageUtil.getPage(query), query);
		List<TeacherVo> rows = pages.getRecords();
		
		for(TeacherVo vo : rows){
			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("/submit")
    @ApiOperation(value = "新增或修改", notes = "传入teacher")
    @PreAuthorize("@pcs.hasPermissions('teacher/submit')")
    public HttpResponseResult<Boolean> submit(@Valid @RequestBody TeacherSubmitReq teacherSubmitReq) {
        return teacherService.submit(teacherSubmitReq);
    }

    @ApiOperation(value = "老师列表导出")
    @PostMapping("export")
    @PreAuthorize("@pcs.hasPermissions('teacher/export')")
    public void export(HttpServletResponse response, @RequestBody TeacherSearch queryInfo) throws IOException {
        queryInfo.setPage(1);
        queryInfo.setRows(49999);
    	
    	if(StringUtils.isNotBlank(queryInfo.getUserStatus())){
    		switch (queryInfo.getUserStatus()) {
			case "LOCKED":
				queryInfo.setDelFlag(YesOrNoEnum.NO);
				queryInfo.setLockFlag(UserLockFlag.LOCKED);
				break;
			case "CLOSED":
				queryInfo.setDelFlag(YesOrNoEnum.YES);
				break;

			default:
				queryInfo.setDelFlag(YesOrNoEnum.NO);
				queryInfo.setLockFlag(UserLockFlag.NORMAL);
				break;
			}
    	}
        List<TeacherVo> rows = teacherService.selectPage(PageUtil.getPage(queryInfo), queryInfo).getRecords();
        if (rows.size() < 1) {
            throw new BizException("没有可导出数据");
        }
		
		for(TeacherVo vo : rows){
			if(vo.getDelFlag() == YesOrNoEnum.YES){
				vo.setUserStatus(UserStatusEnum.CLOSED);
			}else{
				if(vo.getLockFlag() == UserLockFlag.LOCKED){
					vo.setUserStatus(UserStatusEnum.LOCKED);
				}else{
					vo.setUserStatus(UserStatusEnum.NORMAL);
				}
			}
		}
        for(TeacherVo vo : rows){
        	if(StringUtils.isNotBlank(vo.getTag())){
        		vo.setTag(vo.getTag().replace("STYLE", "个人风采").replace("LIVE", "直播课").replace("VIDEO", "视频课").replace("MUSIC", "乐谱").replace("DEGREE", "学历").replace("TEACHER", "教资"));
        	}
        }
        OutputStream outputStream = response.getOutputStream();
        try {
            HSSFWorkbook workbook = POIUtil.exportExcel(new String[]{"老师编号", "昵称", "姓名", "手机号", "老师类型",
                    "注册时间", "认证时间", "状态", "是否是会员", "徽章"}, new String[]{
                    "userId", "username", "realName", "phone", "entryFlag.code == 1 ? '达人' : '游客'", "createTime", "entryAuthDate",
                    "userStatus.msg", "isVip.code == 1 ? '是' : '否'", "tag"}, rows);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attac:wq" +
                    "hment;filename=老师列表-" + DateUtil.getDate(new Date()) + ".xls");

            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @PostMapping("/addVip")
    @ApiOperation(value = "添加会员")
    @PreAuthorize("@pcs.hasPermissions('teacher/addVip')")
    public HttpResponseResult<Boolean> addVip(@Valid @RequestBody VipSubmitReq vipSubmitReq) {


        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        return succeed(memberPriceSettingsService.addVip(vipSubmitReq, ClientEnum.TEACHER,sysUser));
    }


    @PostMapping("/vipRecord")
    @ApiOperation(value = "会员记录")
    @PreAuthorize("@pcs.hasPermissions('teacher/vipRecord')")
    public HttpResponseResult<PageInfo<VipRecordVo>> vipRecord(@Valid @RequestBody VipRecordSearch recordSearch) {

        recordSearch.setClient(ClientEnum.TEACHER);
        return succeed(vipCardRecordService.vipRecord(recordSearch));
    }

    @ApiOperation(value = "个人风采保存")
    @PostMapping("/updateStyleVideo")
    @PreAuthorize("@pcs.hasPermissions('teacher/updateStyleVideo')")
    public HttpResponseResult<Boolean> updateStyleVideo(@RequestBody TeacherDto teacherDto) {
        if (StringUtil.isEmpty(teacherDto.getSubjectId())) {
            return failed("参数异常");
        }
        teacherService.updateStyleVideo(teacherDto.getUserId(), teacherDto.getStyleVideo(), teacherDto.getMessage());
        return succeed();
    }


    @ApiOperation(value = "老师琴房课绑定学员列表")
    @PostMapping("/bindingUserList")
    // @PreAuthorize("@pcs.hasPermissions('teacher/bindingUserList')")
    public HttpResponseResult<PageInfo<TeacherBindingUserVo.BindingUserList>> bindingUserList(@RequestBody  @Valid  TeacherBindingUserVo.BindingUserQuery query) {
        IPage<UserBindingTeacherWrapper> wrapperIPage = userBindingTeacherService.selectBindingUserPage(PageUtil.getPage(query),
                                                        TeacherBindingUserQueryInfo.BindingUserQuery.from(query.jsonString()));
        // 数据转换
        List<TeacherBindingUserVo.BindingUserList> pageInfos = JSON.parseArray(JSON.toJSONString(wrapperIPage.getRecords()),
                                                                               TeacherBindingUserVo.BindingUserList.class);

        return succeed(PageUtil.getPageInfo(wrapperIPage,pageInfos));
    }


    @ApiOperation(value = "查看课表")
    @PostMapping("/selectBindingUserCourse")
    // @PreAuthorize("@pcs.hasPermissions('teacher/selectBindingUserCourse')")
    public HttpResponseResult<PageInfo<TeacherBindingUserVo.BindingStudentCourseList>> selectBindingUserCourse(@RequestBody @Valid TeacherBindingUserVo.BindingStudentCourseQuery query) {
        IPage<UserBindingCourseWrapper> wrapperIPage = userBindingTeacherService.selectBindingUserCoursePage(PageUtil.getPage(query),
                                                                                                             TeacherBindingUserQueryInfo.BindingStudentCourseQuery.from(query.jsonString()));
        // 数据转换
        List<TeacherBindingUserVo.BindingStudentCourseList> pageInfos = JSON.parseArray(JSON.toJSONString(wrapperIPage.getRecords()),
                                                                                        TeacherBindingUserVo.BindingStudentCourseList.class);

        return succeed(PageUtil.getPageInfo(wrapperIPage, pageInfos));
    }
    /**
     * 查询老师统计指标
     * @param userId 老师ID
     * @return HttpResponseResult<TeacherVO.TeacherStat>
     */
    @ApiOperation(value = "老师统计指标", notes = "传入id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "path", dataType = "long", required = true),
    })
    @GetMapping("/stat/{id}")
    public HttpResponseResult<TeacherVO.TeacherStat> teacherStatInfo(@PathVariable("id") Long userId) {

        // 老师统计指标
        TeacherWrapper.TeacherStatInfo statInfo = teacherService.findTeacherStatInfoById(userId);

        return succeed(TeacherVO.TeacherStat.from(statInfo.jsonString()));
    }

    /**
     * 老师粉丝信息查询
     * @param query TeacherVO.TeacherFansQuery
     * @return HttpResponseResult<PageInfo<MyFens>>
     */
    @ApiOperation(value = "我的粉丝")
    @PostMapping(value = "/myFans")
    public HttpResponseResult<PageInfo<TeacherVO.TeacherFans>> queryMyFans(@RequestBody TeacherVO.TeacherFansQuery query) {

        if (Optional.ofNullable(query.getTeacherId()).orElse(0L) <= 0) {
            return failed("无效的请求参数");
        }

        IPage<MyFens> pages = teacherService.queryMyFans(PageUtil.getPage(query), TeacherQueryInfo.FansQuery.from(query.jsonString()));

        // 数据转换
        List<TeacherVO.TeacherFans> responses = JSON.parseArray(JSON.toJSONString(pages.getRecords()),
                TeacherVO.TeacherFans.class);

        return succeed(PageUtil.getPageInfo(pages, responses));
    }
}