package digital.laboratory.platform.imr.controller;

import cn.hutool.core.io.file.FileNameUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import digital.laboratory.platform.common.core.util.R;
import digital.laboratory.platform.common.log.annotation.SysLog;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.imr.dto.QueryStorageDTO;
import digital.laboratory.platform.imr.entity.StorageCell;
import digital.laboratory.platform.imr.entity.StorageCupboard;
import digital.laboratory.platform.imr.mapper.StorageCellMapper;
import digital.laboratory.platform.imr.mapper.StorageCupboardMapper;
import digital.laboratory.platform.imr.service.StorageCellService;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import digital.laboratory.platform.common.oss.service.OssFile;

/**
 * 
 *
 * @author Zhang Xiaolong created at  2023-03-17
 * @describe  前端控制器
 *
 * 这是与表示层的接口, 不应该接业务逻辑写在这里, 业务逻辑应该写在 service 中
 * 这里写什么:
 *     为前端提供数据, 接受前端的数据
 *     为前端提供的数据, 从 service 取得后, 可以做一些适当的加工, 这种加工不是业务层面的, 只能是数据格式上, 为方便前端处理
 *     接受前端的数据, 每一个函数的参数可以先做一些整理后, 再调用 service 中的函数。这里对参数的整理, 应该只是格式上的, 而不能是业务上的
 * 数据层在 mapper 中, 数据层不涉及业务, 只管技术上的 对象<->表 之间的转换
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/storage_cell" )
@Api(value = "storage_cell", tags = "存储柜子对应格子管理")
public class StorageCellController {

    private final  StorageCellService storageCellService;


	private final StorageCellMapper cellMapper;

	private final StorageCupboardMapper cupboardMapper;


	private final OssFile ossFile;

	/**
	 * 通过id查询
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}" )
	@PreAuthorize("@pms.hasPermission('imr_storage_cell_get')" )
	public R<StorageCell> getById(@PathVariable("id" ) String id, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        StorageCell storageCell = storageCellService.getById(id);
		return R.ok(storageCell);
		//return R.ok(storageCellService.getById(id));
	}

	/**
	 * 上传图片
	 * @param cellId
	 * @param file
	 * @return
	 * @throws Exception
	 */


	@ApiOperation(value = "上传格子图片", notes = "上传格子图片")
	@PostMapping(value = " /{cellId}")
	//@PreAuthorize("@pms.hasPermission('roomUpload')")
	public R uploadAttachmentObj(@PathVariable("cellId") String cellId, @RequestPart("file") MultipartFile file) throws Exception {

		StorageCell storageCell = cellMapper.selectById(cellId);
		if (storageCell != null) {

			String path = "cell" + "/" + cellId;
			String fileName = FileNameUtil.getName(file.getOriginalFilename());
			boolean r = ossFile.fileUpload(file, path);
			Map<String, String> ResultData = new HashMap<>();
			ResultData.put("fileName", fileName);
			ResultData.put("path", path);

			if (r) {
				//修改数据库
				storageCell.setCellPhoto(path);
				storageCell.setFileName(fileName);
				cellMapper.updateById(storageCell);
				return R.ok(ResultData, "上传成功");
			}
			return R.failed("上传失败");
		}
		return R.failed(null, "这个格子不存在");
	}








	/*HairSample hs = hairSampleService.getById(hairSampleId);
		if (hs != null) {
		try {
			// 获取样品所属的任务信息
			HairJob hairJob = hairJobService.getById(hs.getJobId());
			if (hairJob == null) {
				throw new RuntimeException(String.format("任务id为 %s 的任务不存在", hs.getJobId()));
			}
			String rootId;
			// 获取根任务id
			if (hairJob.getRootTaskId().equals("0")) {
				rootId = hairJob.getId();
			} else {
				rootId = hairJob.getRootTaskId();
			}
			ossFile.fileGet("hair_job" + "/" + rootId + "/" + hairSampleId + "/" + fileName, httpServletResponse.getOutputStream());
			httpServletResponse.setContentType(new MimetypesFileTypeMap().getContentType(hs.getPicture()));
		} catch (AmazonS3Exception s3e) {
			httpServletResponse.sendError(s3e.getStatusCode(), s3e.toString());
		} catch (Exception e) {
			httpServletResponse.sendError(501, e.toString());
		}
	}
		else {
		httpServletResponse.sendError(404, "不存在这个毛发样品");
	}*/



	@ApiOperation(value = "柜子列表查询接口--存储管理", notes = "柜子列表查询接口--存储管理")
	@GetMapping("/cell/list" )
	//@PreAuthorize("@pms.hasPermission('imr_storage_room_get')" )
	public R<IPage<StorageCell>> getStorageRoomPage(QueryStorageDTO dto){


		Page<StorageCell> page = new Page<>();

		IPage<StorageCell> storageList = cellMapper.getStorageCellPage(page,Wrappers.<StorageCell>query()
				.eq(!dto.getId().isEmpty(),"id",dto.getId())
				.orderByDesc("create_time")
		);
		return R.ok(storageList,"查询成功");
	}




	/**
	 *
	 * @param dto
	 * @return
	 */
	@ApiOperation(value = "格子分页查询--入库模块使用", notes = "格子分页查询--入库模块使用")
	@GetMapping("/page" )
	//@PreAuthorize("@pms.hasPermission('imr_storage_room_get')" )
	public R<IPage<StorageCell>> getStorageRoomList(QueryStorageDTO dto) {

		Page<StorageCell> page = new Page<>(dto.getCurrent(),dto.getSize());

		IPage<StorageCell> storage = cellMapper.getStorageCellPage(page,Wrappers.<StorageCell>query()
				.eq("cupboard_id",dto.getId())
				.orderByDesc("sort")
		);
		return R.ok(storage,"查询成功");
	}


    /**
     * 通过id删除
     * @return R
     */
    @ApiOperation(value = "通过格子id删除图片", notes = "通过格子id删除图片")
    @SysLog("通过id删除" )
    @DeleteMapping("/deletePicture/{cellId}" )
    //@PreAuthorize("@pms.hasPermission('imr_storage_cell_del')" )
    public R deleteById(@PathVariable("cellId") String cellId) throws Exception {


		StorageCell storageCell = cellMapper.selectById(cellId);
		if(storageCell==null){
			throw new RuntimeException(String.format("当前格子数据不存在"));
		}
		if(storageCell.getCellPhoto()!=null && storageCell.getFileName()!=null ){
			//删除图片
			ossFile.fileDelete("cell" + "/" + storageCell.getId() + "/" + storageCell.getFileName());
			storageCell.setCellPhoto("");
			storageCell.setFileName("");
			cellMapper.updateById(storageCell);
		}
		return R.ok("删除成功");
    }



	/**
	 * 通过id删除
	 * @return R
	 */
	@ApiOperation(value = "批量删除格子", notes = "批量删除格子")
	@SysLog("通过id删除" )
	@DeleteMapping("/deleteCell" )
	//@PreAuthorize("@pms.hasPermission('imr_storage_cell_del')" )
	public R deleteById(@RequestBody List<String> cellIds) throws Exception {

		List<StorageCell> storageCells = cellMapper.selectBatchIds(cellIds);

		for (StorageCell storageCell : storageCells) {
			if(storageCell.getStatus()){
				throw new RuntimeException(String.format("编号为"+storageCell.getCellNo()+"的格子已存放东西"));
			}
		}
		for (StorageCell storageCell : storageCells) {

			//删除数据库数据
			cellMapper.deleteById(storageCell.getId());
			if(storageCell.getCellPhoto()!=null && storageCell.getFileName()!=null ){
				//删除图片
				ossFile.fileDelete("cell" + "/" + storageCell.getId() + "/" + storageCell.getFileName());
			}
			//更新对应格子的规格数据
			StorageCupboard storageCupboard = cupboardMapper.selectById(storageCell.getCupboardId());
			storageCupboard.setSpecifications(storageCupboard.getSpecifications()-1);//删除一个减-
			//获取对应格子数量
			/*QueryWrapper<StorageCell> wrapper = new QueryWrapper<>();
			wrapper.eq("cupboard_id",storageCell.getCupboardId());
			cellMapper.selectCount(wrapper);*/
			cupboardMapper.updateById(storageCupboard);
		}
		return R.ok("删除成功");
	}


	/**
	 * 通过柜子id和文件名获取图片"/getRoomPicture/{roomId}/{fileName}"
	 */
	@ApiOperation(value = "通过格子id和文件名获取图片--存储管理", notes = "通过格子id和文件名获取图片--存储管理")
	@GetMapping("/getCellPicture/{cellId}/{fileName}")
	//@PreAuthorize("@pms.hasPermission('imr_storage_room_get')" )
	public void getRoomPicture (@PathVariable("cellId") String cellId,
								@PathVariable("fileName") String fileName,
								HttpServletResponse httpServletResponse) throws Exception {
		StorageCell storageCell = storageCellService.getById(cellId);
		if (storageCell == null) {
			throw new RuntimeException(String.format("当前柜子数据不存在"));
		}
		ossFile.fileGet("cell" + "/" + storageCell.getId() + "/" + fileName, httpServletResponse.getOutputStream());
		httpServletResponse.setContentType(new MimetypesFileTypeMap().getContentType(storageCell.getFileName()));
	}

}
