package com.yizhi.application.protal.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.core.application.cache.CacheNamespace;
import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.site.application.feign.TrSiteStudentFeignClients;
import com.yizhi.site.application.vo.site.TrSitePageVO;
import com.yizhi.site.application.vo.site.TrSiteStudentVo;
import com.yizhi.system.application.system.remote.SiteClient;
import com.yizhi.system.application.vo.SiteVO;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 站点管理
 */

@Api(tags = "专区配置学员端")
@RestController
@RequestMapping("/student/site/student/")
public class TrSiteStudentController {
    @Autowired
    private TrSiteStudentFeignClients trSiteStudentFeignClients;
    @Autowired
    private SiteClient remoteSiteClient;
    @Autowired
    private RedisCache redisCache;
    private final static Long EXPIRE_TIME = 60 * 1L;


    /**
     * 查询配置的列表
     *
     * @return
     */
    @PostMapping("/getPage")
    @ApiOperation(value = "查询配置的列表", response = TrSiteStudentVo.class)
    public Response getPage(@ApiParam("trSitePageVO") @RequestBody TrSitePageVO trSitePageVO) {
        RequestContext context = ContextHolder.get();
        String key = CacheNamespace.SITE_STUDENT_RECORDS + context.getSiteId();
        List<TrSiteStudentVo> trSiteStudentVos = null;
        Object o = redisCache.get(key);
        if (o != null) {
            trSiteStudentVos = JSON.parseArray(o.toString(), TrSiteStudentVo.class);
        } else {
            Page<TrSiteStudentVo> page = trSiteStudentFeignClients.getPage(trSitePageVO);
            trSiteStudentVos = page.getRecords();
        }
        //数据处理
        dealData(trSiteStudentVos, context);
        return Response.ok(trSiteStudentVos);
    }

    /**
     * 数据处理
     *
     * @param records
     */
    private void dealData(List<TrSiteStudentVo> records, RequestContext context) {
        //获取当前学员可访问的站点
        Set<Long> accessSiteIds = remoteSiteClient.frontList();
        if (CollectionUtils.isNotEmpty(records)) {
            //获取实时数据
            //获取有权限访问的站点id
            List<Long> collect = new ArrayList<>(records.size());
            records.parallelStream().forEach(a -> {
                //移除无权限的站点
                if (accessSiteIds.contains(a.getStudentSiteId())) {
                    collect.add(a.getStudentSiteId());
                }
            });
            if (CollectionUtils.isNotEmpty(collect)) {
                List<SiteVO> siteVOS = remoteSiteClient.selectByIds(collect);
                if (CollectionUtils.isNotEmpty(siteVOS)) {
                    Map<Long, SiteVO> siteVOMap = siteVOS.parallelStream().collect(Collectors.toMap(SiteVO::getId, a -> a));
                    if (siteVOMap != null) {
                        records.forEach(a -> {
                            SiteVO siteVO = siteVOMap.get(a.getStudentSiteId());
                            if (siteVO != null) {
                                a.setCode(siteVO.getCode());
                                a.setEnabled(siteVO.getEnabled() ? 1 : 0);
                                a.setLogo(siteVO.getLogo());
                                a.setSiteName(siteVO.getName());
                            }
                        });
                    }
                }
                //需求为超过16个直接截取
                if (records.size() > 16) {
                    records.subList(0, 15);
                }
                String key = CacheNamespace.SITE_STUDENT_RECORDS + context.getSiteId();
                redisCache.set(key, JSON.toJSONString(records), EXPIRE_TIME);
            }
        }
    }

    /**
     * 获取返回的站点
     * @return
     */
    @GetMapping("/getReturnSite")
    @ApiOperation(value = "点击返回站点需要信息")
    public Response getReturnSite() {
        RequestContext context = ContextHolder.get();
        String domain = "";
        Object hget = redisCache.hget(CacheNamespace.SITE_STUDENT_LAST_LOGIN_RECORDS, context.getAccountId().toString());
        if (hget!=null){
            domain = hget.toString();
        }else {
            domain = context.getCompanyCode()+"/"+context.getSiteCode();
        }
        return Response.ok(domain);
    }

    /**
     * 判断对应终端是否发布  1:发布了   0：未发布
     * @param type
     * @return
     */
    @GetMapping("/canVisit")
    @ApiOperation(value = "判断对应终端是否发布")
    public Response canVisit(@ApiParam("type 1：PC  3移动端")@RequestParam("type") Integer type) {
        return Response.ok(trSiteStudentFeignClients.canVisit(type));
    }
}
