package com.neusoft.smart.pos.device.controller;


import com.neusoft.smart.pos.device.constants.DeviceErrorCode;
import com.neusoft.smart.pos.device.service.DeviceService;
import com.neusoft.smart.pos.dto.device.request.DeviceQueryRequest;
import com.neusoft.smart.pos.dto.device.request.DeviceRequest;
import com.neusoft.smart.pos.dto.device.request.DeviceStatusRequest;
import com.neusoft.smart.pos.dto.device.request.DeviceStoreRequest;
import com.neusoft.smart.pos.dto.device.response.DeviceResponse;
import com.neusoft.smart.pos.dto.device.response.GetAppProjectConfigResponse;
import com.neusoft.smart.pos.dto.device.response.GetDeviceAuthLicenceResponse;
import com.neusoft.smart.pos.framework.bean.PaginationExtendBean;
import com.neusoft.smart.pos.framework.dto.ResponseData;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.framework.utils.LocalDateTimeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.Pair;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

@Api(value = "设备管理restful接口", description = "设备管理restful接口")
@RestController
public class DeviceController {
	
	@Autowired
	private DeviceService deviceService;
	
	
	@PostMapping("/device")
	@ApiOperation(value = "设备添加接口", notes = "设备添加接口")
	public ResponseData<DeviceResponse> create(@Valid @RequestBody DeviceRequest deviceRequest,
			BindingResult bindingResult) {
		return new ResponseData<>(deviceService.create(deviceRequest, true));
	}
	
	
	@PutMapping("/device")
	@ApiOperation(value = "设备修改接口", notes = "设备修改接口")
	public ResponseData<?> update(@RequestBody DeviceRequest deviceRequest) {
		deviceService.update(deviceRequest);
		return new ResponseData<>();
	}
	
	@PutMapping("/device/selective")
	@ApiOperation(value = "设备修改接口", notes = "设备修改接口")
	public ResponseData<?> updateSelective(@RequestBody DeviceRequest deviceRequest) {
		deviceService.updateSelective(deviceRequest);
		return new ResponseData<>();
	}
	
	
	@PostMapping("/device/batch")
	@ApiOperation(value = "设备批量添加接口", notes = "设备批量添加接口")
	public ResponseData<List<DeviceResponse>> createByBatch(@RequestBody List<DeviceRequest> deviceRequestList) {
		List<DeviceResponse> result = deviceService.create(deviceRequestList);
		ResponseData<List<DeviceResponse>> responseData = new ResponseData<>();
		if (!result.isEmpty()) {
			responseData.setResult(result);
//			responseData.setCode(DeviceErrorCode.DEVICE_BATCH_CREATE_ERROR.getCode());
			responseData.setMessage(DeviceErrorCode.DEVICE_BATCH_CREATE_ERROR.getMessage());
		}
		return responseData;
	}
	
	@PostMapping("/device/parse")
	@ApiOperation(value = "解析设备excel文件接口", notes = "解析设备excel文件接口")
	public ResponseData<List<DeviceResponse>> importXlsx(@RequestParam("file") MultipartFile file) {
		String filename = file.getOriginalFilename();
		String fileType = filename.substring(filename.lastIndexOf("."));
		if (!fileType.equals(".xlsx") && !fileType.equals(".xls")) {
			throw new BusinessCommonException(DeviceErrorCode.FILE_TYPE_ERROR);
		}
		return new ResponseData<>(deviceService.parseDeviceFromFile(file));
	}
	
	
	@PostMapping("/devices")
	@ApiOperation(value = "分页查询设备接口", notes = "分页查询设备接口")
	public ResponseData<PaginationExtendBean<DeviceResponse>> fetchList(@RequestBody DeviceQueryRequest deviceQueryRequest) {
		PaginationExtendBean<DeviceResponse> paginationExtendBean = new PaginationExtendBean<>();
		paginationExtendBean.setRows(deviceService.getList(deviceQueryRequest));
		paginationExtendBean.setTotal(deviceService.getCount(deviceQueryRequest));
		return new ResponseData<>(paginationExtendBean);
	}
	
	
	@PutMapping("/device/status")
	@ApiOperation(value = "修改设备状态接口", notes = "修改设备状态接口")
	public ResponseData<Pair<List<Integer>, List<Integer>>> updateStatus(@Valid @RequestBody DeviceStatusRequest deviceStatusRequest,
			BindingResult bindingResult) {
		return new ResponseData<>(deviceService.updateStatus(deviceStatusRequest.getDeviceIds(), deviceStatusRequest.getStatus()));
	}
	
	@PutMapping("/device/store")
	@ApiOperation(value = "设置设备归属门店接口", notes = "设置设备归属门店接口")
	public ResponseData<DeviceResponse> updateStore(@Valid @RequestBody DeviceStoreRequest deviceStoreRequest,
			BindingResult bindingResult) {
		deviceService.setStoreId(deviceStoreRequest.getDeviceIds(), deviceStoreRequest.getStoreId());
		return new ResponseData<>();
	}
	
	@GetMapping("/device/export")
	@ApiOperation(value = "导出设备列表excel接口", notes = "导出设备列表excel接口")
	public void export(DeviceQueryRequest deviceQueryRequest, HttpServletResponse response) throws Exception {
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + new String(("设备列表-" + LocalDateTimeUtils.getDateTime() + ".xlsx").getBytes(), "iso-8859-1"));
		deviceService.export(deviceQueryRequest, response.getOutputStream());
	}
	
	/**
	 * 数据库到redis
	 *
	 * @return
	 */
	@GetMapping("/device/load2Redis")
	@ApiOperation(value = "重新加载设备数据到redis接口", notes = "重新加载设备数据到redis接口")
	public String load2Redis() {
		try {
			deviceService.loadData2Redis();
			return "ok";
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessCommonException(DeviceErrorCode.LOAD_REDIS_ERROR);
		}
	}
	
	@ApiOperation(value = "人证通设备授权信息查询方法接口", notes = "人证通设备授权信息查询方法")
	@GetMapping("/device/deviceAuthLicence")
	public ResponseData<GetDeviceAuthLicenceResponse> queryDeviceAuthLicence(@RequestParam(value = "serialNo", defaultValue = "") String serialNo) {
		return new ResponseData<>(deviceService.queryDeviceAuthLicence(serialNo));
	}
	
	@ApiOperation(value = "应用项目配置信息查询方法接口", notes = "应用项目配置信息查询方法")
	@GetMapping("/device/appProjectConfig")
	public ResponseData<GetAppProjectConfigResponse> queryAppProjectConfig(@RequestParam(value = "serialNo", defaultValue = "") String serialNo,
	                                                                       @RequestParam(value = "appId", defaultValue = "") String appId) {
		return new ResponseData<>(deviceService.queryAppProjectConfig(serialNo,appId));
	}
}
