package org.springblade.ship;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.model.LogUsual;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.ILogUsualService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.ship.cable.entity.Cable;
import org.springblade.ship.cable.service.ICableService;
import org.springblade.ship.device.entity.Device;
import org.springblade.ship.device.service.IDeviceService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@AllArgsConstructor
@RequestMapping("ship/home")
@Api(value = "", tags = "首页")
public class HomeController extends BladeController {

	private final IUserService userService;
	private final ICableService cableService;
	private final IDeviceService deviceService;
	private final ILogUsualService usualService;


	/**
	 *
	 */
	@GetMapping("/getTotalData")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "总数", notes = "")
	public R getTotalData() {
		Map<String, Object> map = new HashMap<>();
		map.put("userCount", userService.count());
		map.put("cableCount", cableService.count());
		map.put("deviceCount", deviceService.count());
		return R.data(map);
	}

	/**
	 *
	 */
	@GetMapping("/getTodayData")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "今日新增", notes = "")
	public R getTodayData(String theDay) {
		Map<String, Object> map = new HashMap<>();

		if (theDay == null){
			theDay = DateUtil.formatDate(DateUtil.now());
		}

		map.put("userCount", userService.count(new QueryWrapper<>(new User()).lambda().like(User::getCreateTime, theDay)));
		map.put("cableCount", cableService.count(new QueryWrapper<>(new Cable()).lambda().like(Cable::getCreateTime, theDay)));
		map.put("deviceCount", deviceService.count(new QueryWrapper<>(new Device()).lambda().like(Device::getCreateTime, theDay)));
		return R.data(map);
	}

	/**
	 *
	 */
	@GetMapping("/getMonthData")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "今日新增", notes = "")
	public R getMonthData(String theMonth) {
		Map<String, Object> map = new HashMap<>();

		if (theMonth == null){
			theMonth = DateUtil.format(DateUtil.now(), "yyyy-MM");
		}

		map.put("userList", userService.list(new QueryWrapper<>(new User()).lambda().like(User::getCreateTime, theMonth).orderByDesc(User::getCreateTime)));
		map.put("cableList", cableService.list(new QueryWrapper<>(new Cable()).lambda().like(Cable::getCreateTime, theMonth).orderByDesc(Cable::getCreateTime)));
		map.put("deviceList", deviceService.list(new QueryWrapper<>(new Device()).lambda().like(Device::getCreateTime, theMonth).orderByDesc(Device::getCreateTime)));
		map.put("modifyList", usualService.list(new QueryWrapper<>(new LogUsual()).lambda().eq(LogUsual::getRequestUri, "/cable/update").eq(LogUsual::getMethodName, "update")));

		return R.data(map);
	}


	/**
	 *
	 */
	@GetMapping("/getUpdateData")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "更新信息", notes = "")
	public HttpServletResponse  getUpdateData(HttpServletResponse response) {

		QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(new User());
		QueryWrapper<Cable> cableQueryWrapper = new QueryWrapper<>(new Cable());
		List<User> userList = userService.list(userQueryWrapper);
		List<Cable> cableList = cableService.list(cableQueryWrapper);

		Map<String, Object> map = new HashMap<>();
		map.put("userList", userList);
		map.put("cableList", cableList);
		map.put("updateTime", DateUtil.format(DateUtil.now(), "yyyy-MM-dd HH:mm:ss"));

		BufferedWriter out = null;
		try {
			File file = new File("datas.json");
			if(!file.exists()){
				file.createNewFile();
			}

			out = new BufferedWriter(new FileWriter(file, false));
			out.write(JSONUtil.toJsonStr(map));
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 读到流中
		InputStream inStream = null;// 文件的存放路径
		try {
			File f = new File("datas.json");
			if (!f.exists()) {
//				response.sendError(404, "File not found!");
				return response;
			}
			BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
			byte[] buf = new byte[1024];
			int len = 0;

			response.reset(); // 非常重要
			URL u = new URL("file:///" + f.getAbsolutePath());
			response.setContentType(u.openConnection().getContentType());
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
			// 文件名应该编码成UTF-8
			OutputStream out2 = response.getOutputStream();
			while ((len = br.read(buf)) > 0)
				out2.write(buf, 0, len);
			br.close();
			out2.close();


		} catch (FileNotFoundException | MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return response;

	}

}
