package org.springblade.modules.app.web;


import com.wn.common.controller.BaseController;
import com.wn.common.datamodel.ModelConvertUtil;
import com.wn.common.datamodel.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.app.common.dto.UserDTO;
import org.springblade.modules.app.common.dto.VerifyStationDTO;
import org.springblade.modules.app.manager.UserManager;
import org.springblade.modules.app.service.IVerifyStationService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 入省检疫站表 前端控制器
 * </p>
 *
 * @author fuxinsheng
 * @since 2021-11-05
 */
@Slf4j
@RestController
@RequestMapping("app/verify")
public class VerifyController extends BaseController {

    @Autowired
    private IVerifyStationService verifyStationService;

    @Autowired
    private BladeRedis bladeRedis;

    @Autowired
    private UserManager userManager;

    //@ApiOperation(value = "查询入省检疫站列表")
    @GetMapping("/list")
    public ResponseEntity<ResultDTO<List<VerifyStationDTO>>> getQuarantineStation(String token) {
        UserDTO user = userManager.getUserInfo(token);

        List<VerifyStationDTO> data = ModelConvertUtil.copyListTo(verifyStationService.list(),VerifyStationDTO.class);
        if(StringUtil.isEmpty(token)){
            return success(data);
        }

        for (VerifyStationDTO verifyStationDTO : data){
            if(bladeRedis.exists(user.getId().toString()+verifyStationDTO.getId().toString())){
                verifyStationDTO.setSort(Integer.valueOf(getIncr(user.getId().toString()+verifyStationDTO.getId().toString())));
            }else {
                verifyStationDTO.setSort(0);
            }
        }
        data = data.stream().sorted(Comparator.comparing(VerifyStationDTO::getSort).reversed()).collect(Collectors.toList());
        return success(data);
    }

    private String getIncr(String key){
        RedisSerializer stringSerializer = bladeRedis.getRedisTemplate().getStringSerializer();
        byte[] serialize = stringSerializer.serialize(key);
        String deserialize = (String) stringSerializer.deserialize(bladeRedis.getRedisTemplate().getConnectionFactory().getConnection().get(serialize));
        return deserialize;
    }
}

