package cn.wise.sc.cement.business.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.wise.sc.cement.business.entity.Cabinet;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.SampleManageQuery;
import cn.wise.sc.cement.business.service.ISampleService;
import cn.wise.sc.cement.business.service.ISysDictionaryService;
import cn.wise.sc.cement.business.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ztw
 * @since 2020-09-04
 */
@Api(tags = "样品管理")
@RestController
@RequestMapping("/business/sample")
public class SampleController {

	private static final Logger log = LoggerFactory.getLogger("SampleController");

	@Autowired
	private ISampleService sampleService;
	@Autowired
	private ISysDictionaryService dictionaryService;
	@Autowired
	RedisUtil redisUtil;

	@ApiOperation(value = "样品分页列表")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "sampleName", value = "样品名称", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "cementCode", value = "样品本所编号", paramType = "query", dataType = "String")
	})
	@GetMapping("/getPage")
	public BaseResponse getPage(PageQuery pageQuery, String sampleName, String cementCode) {
		try {
			return sampleService.getPage(pageQuery, sampleName, cementCode);
		} catch (Exception e) {
			log.debug("样品分页列表{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation("样品列表导出")
	@PostMapping("/export")
	public void export(String sampleName, String cementCode,
	                   String fileName, HttpServletResponse response) {
		try {
			sampleService.export(sampleName, cementCode,
					fileName, response);
		} catch (Exception e) {
			log.debug("样品列表导出{}", e);
		}
	}

	@ApiOperation("样品列表导出(word)")
	@PostMapping("/export/word")
	public void exportWord(String sampleName, String cementCode,
	                       String fileName,HttpServletResponse response){
		sampleService.exportWord(sampleName, cementCode,
				fileName,response);
	}

	@ApiOperation(value = "样品详情")
	@GetMapping("/{id}")
	public BaseResponse getById(@PathVariable Integer id) {
		try {
			return sampleService.getDetail(id);
		} catch (Exception e) {
			log.debug("样品详情{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "样品登记")
	@PostMapping("/register")
	public BaseResponse register(@RequestBody SampleManageQuery query) {
		try {
			return sampleService.register(query);
		} catch (Exception e) {
			log.debug("样品登记{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation("绑定样品信息")
	@PutMapping("/bind/savePosition")
	public BaseResponse<String> bindSavePosition(@RequestBody SampleManageQuery query) {

		try {
			return sampleService.bindSavePosition(query);
		} catch (Exception e) {
			log.debug("样品登记{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation("样品复查")
	@PutMapping("/review")
	public BaseResponse<Boolean> ampleReview(Integer id) {
		return sampleService.ampleReview(id);
	}

	@ApiOperation("获取存储位置二维码")
	@PostMapping("/saverq/init")
	public BaseResponse<List<String>> getSaveRQ(@RequestBody List<String> savePositions) throws IOException {

		if (CollectionUtil.isEmpty(savePositions)) {
			log.error("生成存储位置二维码失败!savePosition参数为空!");
		}
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		List<String> rts = new ArrayList<>(savePositions.size());
		for (String savePosition : savePositions) {
			stream.reset();
			BufferedImage bufferedImage = QrCodeUtil.generate(savePosition, 200, 200);
			ImageIO.write(bufferedImage, "png", stream);
			String base64 = Base64.encode(stream.toByteArray());
			rts.add(base64);
			System.out.println(base64);
		}
		stream.close();
		return BaseResponse.okData(rts);
	}

	@ApiOperation("获取样品二维码")
	@PostMapping("/samplerq/init")
	public BaseResponse<String> getSampleRQ(String sampleId) throws IOException {

		if (StrUtil.isBlank(sampleId)) {
			log.error("生成样品二维码失败!savePosition参数为空!");
		}
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		BufferedImage bufferedImage = QrCodeUtil.generate(sampleId, 200, 200);
		ImageIO.write(bufferedImage, "png", stream);
		stream.close();
		return BaseResponse.okData(Base64.encode(stream.toByteArray()));
	}

	private static final String CABINET_KEY = "CABINET:CACHE:";

	public BaseResponse<String> newCabinet(String cabinetName) {

		if (StrUtil.isBlank(cabinetName)) {
			return BaseResponse.errorMsg("柜子名不能为空!");
		}
		//如果存在
		if (redisUtil.existsKey(CABINET_KEY)) {
			String cabinetStr = redisUtil.getString(CABINET_KEY).toString();
			List<String> list = JSON.parseObject(cabinetStr, ArrayList.class);
			list.add(cabinetName);
			String newCabinetStr = JSON.toJSONString(list);
			redisUtil.setString(newCabinetStr, CABINET_KEY);
			return BaseResponse.okData(newCabinetStr);
		} else {
			List<String> list = new ArrayList<>();
			list.add(cabinetName);
			String newCabinetStr = JSON.toJSONString(list);
			redisUtil.setString(CABINET_KEY, newCabinetStr);
			return BaseResponse.okData(newCabinetStr);
		}
	}

	public BaseResponse<String> editCabinet(String cabinetNames) {

		if (StrUtil.isBlank(cabinetNames)) {
			redisUtil.setString(CABINET_KEY, cabinetNames);
			return BaseResponse.okData("更新成功!");
		} else {
			return BaseResponse.errorMsg("更新字符串不能为空!");
		}
	}

	@ApiOperation(value = "样品销毁")
	@PostMapping("/destruction/{id}")
	public BaseResponse destruction(@PathVariable Integer id) {
		try {
			return sampleService.destruction(id);
		} catch (Exception e) {
			log.debug("样品销毁{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "获取样品状态列表")
	@GetMapping("/getSampleFormList")
	public BaseResponse getSampleFormList() {
		try {
			return dictionaryService.getContent("样品状态");
		} catch (Exception e) {
			log.debug("获取样品状态列表{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation("下载样品处理记录")
	@PostMapping("/uploadSampleSaveList")
	public void upload(HttpServletResponse response){
		sampleService.upload(response);
	}
}

