package com.YuyeTech.TPlat.game.controller;

import com.YuyeTech.TPlat.VO.ResultVO;
import com.YuyeTech.TPlat.dataobject.DeviceInfo;
import com.YuyeTech.TPlat.dto.DeviceBindDTO;
import com.YuyeTech.TPlat.enums.DeviceEnum;
import com.YuyeTech.TPlat.service.DeviceInfoService;
import com.YuyeTech.TPlat.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 操作设备相关
 * @author:slambb
 * @date:2020/6/12
 */
@RestController
@RequestMapping("/device")
@Slf4j
public class DeviceController {

    @Autowired
    private DeviceInfoService deviceInfoService;

    @GetMapping(value = "/bind")
    public ResultVO generateDeviceInfo(@RequestParam(value = "uuid") String uuid,
                                       @RequestParam(value = "type") Integer type,
                                       @RequestParam(value = "userId") String userId){

        if(!type.equals(1)&&!type.equals(2)){
            return  ResultVOUtil.error(DeviceEnum.NOT_DEVICE_TYPE.getCode(),
                    DeviceEnum.NOT_DEVICE_TYPE.getMessage());
        }

        //1.判断是否存在userId 绑定对应的类型设备
        DeviceInfo deviceUserInfo = deviceInfoService.findByUserIdAndType(userId,type);
        if(deviceUserInfo != null){
            //如果绑定过，返回
            return  ResultVOUtil.error(DeviceEnum.HAS_BIND_DEVICE_TYPE.getCode(),
                    DeviceEnum.HAS_BIND_DEVICE_TYPE.getMessage());
        }
        //2.未绑定过，判断uuid 对应的设备type 是否合法
        DeviceInfo deviceInfo = deviceInfoService.findByUUIDAndType(uuid,type);
        if(deviceInfo == null){
            //不合法
            return  ResultVOUtil.error(DeviceEnum.NOT_DEVICE_UUID.getCode(),
                    DeviceEnum.NOT_DEVICE_UUID.getMessage());
        }

        //3.合法后判断是否绑定使用过
        if(deviceInfo.getDeviceStatus().equals(1)){
            //已经使用过，返回
            return ResultVOUtil.error(DeviceEnum.UUID_HAD_USED.getCode(),
                    DeviceEnum.UUID_HAD_USED.getMessage());
        }

        //4.合法，绑定用户信息
        deviceInfo.setUserId(userId);
        deviceInfo.setDeviceStatus(1);

        DeviceInfo backDevice = deviceInfoService.saveDeviceInfo(deviceInfo);
        Map map = new HashMap();
        map.put("BindUUID",backDevice.getDeviceUuid());
        return ResultVOUtil.success(map);

    }

    @GetMapping(value = "/binding_list")
    public ResultVO getBindDeviceInfo(@RequestParam(value = "userId") String userId){

        List<DeviceBindDTO> deviceBindDTO = deviceInfoService.findAllByUserId(userId);
        Map map = new HashMap();
        map.put("devices",deviceBindDTO);
        return ResultVOUtil.success(map);

    }

}
