/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.ship.open;

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.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.system.entity.Dict;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDictService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.ship.appversion.entity.AppVersion;
import org.springblade.ship.appversion.service.IAppVersionService;
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.util.Assert;
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 javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-11-15
 */
@RestController
@AllArgsConstructor
@RequestMapping("open")
@Api(value = "", tags = "接口")
public class OpenController extends BladeController {

	private final IDeviceService deviceService;
	private final IUserService userService;
	private final ICableService cableService;
	private final IDictService dictService;
	private final IAppVersionService appVersionService;

	/**
	 * 设备更新信息（用户、电缆、设备）
	 */
	@GetMapping("/device/updateInfo")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入device")
	public R updateInfo(@RequestParam String deviceCode) {
		System.out.println("/device/updateInfo");
		Device device = deviceService.getOne(new QueryWrapper<>(new Device()).lambda().eq(Device::getCode, deviceCode));
		Assert.notNull(device, "系统找不到编码为【" + deviceCode + "】的设备！");
		QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(new User());
		QueryWrapper<Cable> cableQueryWrapper = new QueryWrapper<>(new Cable());
		if (device.getLastUpdateTime() != null){
			userQueryWrapper.lambda().gt(User::getUpdateTime, device.getLastUpdateTime());
			cableQueryWrapper.lambda().gt(Cable::getUpdateTime, device.getLastUpdateTime());
		}
		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("device", device);
		map.put("updateTime", DateUtil.format(DateUtil.now(), "yyyy-MM-dd HH:mm:ss"));
		return R.data(map);
	}


	/**
	 * 设备最后更新时间
	 */
	@GetMapping("/device/updateTime")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入device")
	public R updateTime(@RequestParam String deviceCode, Boolean reset) {
		System.out.println("/device/updateTime");

		Device device = deviceService.getOne(new QueryWrapper<>(new Device()).lambda().eq(Device::getCode, deviceCode));
		Assert.notNull(device, "系统找不到编码为【" + deviceCode + "】的设备！");

		if (reset != null && reset){
			device.setLastUpdateTime(DateUtil.parse("2020-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss"));
		}else{
			device.setLastUpdateTime(DateUtil.now());
		}

		return R.status(deviceService.updateById(device));
	}

	/**
	 * 获取字典
	 */
	@GetMapping("/system/dictionary")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "获取字典", notes = "获取字典")
	public R dictionary(@RequestParam String codes) {
		System.out.println("/system/dictionary");

		codes = "yes_no,post_category,user_type,cable_category,cable_model,ship_cabin,ship_side";

		List<Map<String, Object>> dictList = new ArrayList<>();
		List<String> codeList = Func.toStrList(codes);
		codeList.forEach(code -> {
			List<Dict> tree = dictService.getList(code);
			if (tree != null && tree.size() > 0){
				Map<String, Object> map = new HashMap<>();
				map.put(code, tree);
				dictList.add(map);
			}
		});

		return R.data(dictList);
	}

/**
 * 获取字典
 */
	@GetMapping("/app/version/update")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "获取字典", notes = "获取字典")
	public R versionUpdate() {
		System.out.println("/app/version/update");

		AppVersion version = appVersionService.getLastVersion();

		return R.data(version);
	}

	/**
	 *
	 */
	@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);

		String codes = "yes_no,post_category,user_type,cable_category,cable_model,ship_cabin,ship_side";

		List<Map<String, Object>> dictList = new ArrayList<>();
		List<String> codeList = Func.toStrList(codes);
		codeList.forEach(code -> {
			List<Dict> tree = dictService.getList(code);
			if (tree != null && tree.size() > 0){
				Map<String, Object> map = new HashMap<>();
				map.put(code, tree);
				dictList.add(map);
			}
		});

		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"));
		map.put("dictList", dictList);

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

			String path = file.getPath();

			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;

	}

}
