package com.cirle.scientific.controller.index;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cirle.scientific.constants.LoginConsts;
import com.cirle.scientific.dto.QkjPeopleCounDTO;
import com.cirle.scientific.dto.QkjSearchdataDto;
import com.cirle.scientific.pojo.BizCodeEnum;
import com.cirle.scientific.utils.DeviceUtil;
import com.cirle.scientific.utils.LoginUtil;
import com.cirle.scientific.utils.UserLoginUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cirle.scientific.dto.HomeDataDTO;
import com.cirle.scientific.pojo.Result;
import com.cirle.scientific.service.HomeService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import javax.servlet.http.*;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/index")
@Api("首页相关接口")
public class IndexController {

	@Autowired
	private HomeService homeService;

    @Autowired
    LoginUtil loginUtil;



    @GetMapping("/index")
    @ApiOperation("首页接口")
    public String index(HttpServletRequest request,
                        @ApiParam(name = "from",value = "请求类型 web：网站 H5：手机端") @RequestParam(name = "from",required = true) String from, Model model){
        String refererUrl = request.getHeader("Referer");
        if(refererUrl!=null && refererUrl.contains("login")){
            model.addAttribute("fromlogin","1");
        }else{
            model.addAttribute("fromlogin","0");
        }
        if (StringUtils.isNotBlank(from) && from.equals("H5")) {
            return "html5/index/index1";
        }else if (StringUtils.isNotBlank(from) && from.equals("web")){
            return "web/index";
        } else {
            return "";
        }
    }

    @GetMapping("/search")
    @ApiOperation("搜索页面")
    public String search(@ApiParam(name = "from",value = "请求类型 web：网站 H5：手机端") @RequestParam(name = "from",required = true) String from){
        if (StringUtils.isNotBlank(from) && from.equals("H5")) {
            return "html5/search/search";
        } else if (StringUtils.isNotBlank(from) && from.equals("web")){
            return "web/search";
        }else {
            return "";
        }
    }

    @PostMapping("/homeData")
    @ApiOperation("首页接口数据")
    @ResponseBody
    public Result<HomeDataDTO> homeData(
    		@RequestAttribute(value = "memCard",required = false) String memCard,HttpServletRequest request) {
        // 默认展示pc端内容  0全部不显示 、1全部显示 、2m端显示、3pc端显示
        Integer status = 3;
        if(DeviceUtil.isMobileDevice(request)) {
            status = 2;
        }
    		return homeService.getHomeData(memCard, status);
    }

    @PostMapping("/isLogin")
    @ApiOperation("判断是否登录")
    @ResponseBody
    public Result isLogin(HttpServletRequest request, HttpServletResponse response,
                          @RequestAttribute(value = "memCard", required = false) String memCard){

        boolean replace = loginUtil.isReplace(request, response, memCard);
        if(replace){
            return Result.failed(BizCodeEnum.NO_LOGIN_REPLACE);
        }

        if(StringUtils.isBlank(memCard)){
            return Result.success(BizCodeEnum.NO_LOGIN);
        }

        return Result.success(memCard);
    }

    /**
     * 开放搜索接口
     * @return
     */
    @PostMapping(value = "/search")
    @ResponseBody
    @ApiOperation("首页搜索接口")
    public Result<Object> search(@RequestParam int start, @RequestParam int size
            , @RequestParam String searchKw){
        try {
            String rdlist = homeService.search(searchKw, start, size);
            JSONObject jsonObject = JSONObject.parseObject(rdlist);
            String items  = jsonObject.getString("items");
            List<QkjSearchdataDto> qkjSearchdataDtos = JSONArray.parseArray(items, QkjSearchdataDto.class);
            if(CollectionUtils.isNotEmpty(qkjSearchdataDtos)){
                qkjSearchdataDtos = qkjSearchdataDtos.stream().filter(e -> e.getObj_pid()==0).collect(Collectors.toList());
            }
            Object o = JSONArray.toJSON(qkjSearchdataDtos);
            jsonObject.put("items",o);
            //Object parse = JSONObject.parse(rdlist);
            return Result.success(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("搜索错误");
        }
    }

    @GetMapping("/peopleCoun")
    @ResponseBody
    @ApiOperation("注册人数以及在线人数的接口")
    public Result<Object> peopleCoun(HttpServletRequest request ) {
        QkjPeopleCounDTO qkjPeopleCounDTO = homeService.peopleCount(request);
        //进行虚拟填充
        if (Objects.nonNull(qkjPeopleCounDTO)) {
            qkjPeopleCounDTO.setRegisterPerson(qkjPeopleCounDTO.getRegisterPerson() + 150000);

            Random random = new Random();
            int randomInt = random.nextInt(50) + 51;
            qkjPeopleCounDTO.setOnlinePerson(qkjPeopleCounDTO.getOnlinePerson() + randomInt);
        }
        return Result.success(qkjPeopleCounDTO);
    }
}
