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.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dto.search.StudentSearch;
import com.yonge.cooleshow.biz.dal.entity.Student;
import com.yonge.cooleshow.biz.dal.entity.TenantGroup;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.service.ImGroupService;
import com.yonge.cooleshow.biz.dal.service.StudentService;
import com.yonge.cooleshow.biz.dal.service.TenantGroupService;
import com.yonge.cooleshow.biz.dal.vo.StudentVo;
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.base.util.StringUtil;
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.http.HttpStatus;
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.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

    @Resource
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private ImGroupService imGroupService;

    @Autowired
    private TenantGroupService tenantGroupService;


    @ApiOperation(value = "查询指定学员信息-融云token")
    @GetMapping("/queryUserById")
    public HttpResponseResult<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));
    }

    /**
     * 查询老师所属机构下所有的学生
     *
     * @param query 参数
     * @return 学生列表
     */
    @PostMapping("/page")
    @ApiOperation(value = "查询分页", notes = "传入StudentSearch")
    public HttpResponseResult<PageInfo<StudentVo>> page(@RequestBody StudentSearch query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null || null == sysUser.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        Long tenantId = sysUser.getTenantId();
        if (tenantId == null || tenantId.equals(-1L)) {
            IPage<StudentVo> page = PageUtil.getPage(query);
            page.setRecords(new ArrayList<>());
            return succeed(PageUtil.pageInfo(page));
        }

        query.setTenantId(tenantId);
        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<StudentVo> pages = studentService.selectPage(PageUtil.getPage(query), query);
        List<StudentVo> rows = pages.getRecords();

        List<Long> tenantGroupIds = rows.stream().map(Student::getTenantGroupId)
                .filter(next -> next != null && next != -1L).distinct().collect(Collectors.toList());
        Map<Long, String> tenantGroupIdNameMap = new HashMap<>();
        if (!tenantGroupIds.isEmpty()) {
            Map<Long, String> tenantGroupMap = tenantGroupService.lambdaQuery()
                    .eq(TenantGroup::getTenantId, tenantId)
                    .in(TenantGroup::getId, tenantGroupIds)
                    .list().stream().collect(Collectors.toMap(TenantGroup::getId, TenantGroup::getName));
            tenantGroupIdNameMap.putAll(tenantGroupMap);
        }

        for (StudentVo 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);
                }
            }
            vo.setImUserId(imGroupService.getImUserId(vo.getUserId(), ClientEnum.STUDENT));
            vo.setTenantGroupName(tenantGroupIdNameMap.getOrDefault(vo.getTenantGroupId(), ""));
        }
        return succeed(PageUtil.pageInfo(pages));
    }

}