/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/8/31
 */
package org.springblade.modules.manage.version.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.business.notice.entity.NoticeEntity;
import org.springblade.modules.business.notice.service.INoticeService;
import org.springblade.modules.manage.version.entity.VersionInfoEntity;
import org.springblade.modules.manage.version.service.IVersionManageService;
import org.springblade.modules.manage.version.vo.VersionInfoVO;
import org.springblade.modules.manage.version.wrapper.VersionInfoWrapper;
import org.springblade.utils.QRCodeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.*;
import java.util.*;


/***
 * Date:2022/8/31
 * Title: 系统管理
 * Description：版本更新管理功能
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
@RequestMapping("galaxy-business/version")
@RequiredArgsConstructor
@Api(value = "版本管理模块", tags = "版本管理模块")
public class VersionManageController extends BladeController {

	final IVersionManageService versionManageService;

	final INoticeService noticeService;

	@Value("${spring.apk.url}")
	String apkUrl;

	@Value("${spring.apk.save-path}")
	String apkSavePaht;

	/**
	 * 工单查询，分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "")
	public R<IPage<VersionInfoVO>> page(Query query) {
		IPage<VersionInfoEntity> pages = versionManageService.selectPage(Condition.getPage(query));
		return R.data(VersionInfoWrapper.build().pageVO(pages));
	}


	@GetMapping("/check")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "appId", value = "APPID", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "version", value = "版本号", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "versionNote", value = "版本提示", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "版本信息")
	public R<VersionInfoVO> detail(@ApiIgnore VersionInfoEntity entity) {
		LambdaQueryWrapper<VersionInfoEntity> wrapper = Wrappers.<VersionInfoEntity>query().lambda();
		wrapper.eq(VersionInfoEntity::getIsDeleted, 0);
		wrapper.eq(VersionInfoEntity::getAppId, entity.getAppId());
		VersionInfoEntity versionInfoEntity = versionManageService.getOne(wrapper);
		VersionInfoVO vo = VersionInfoWrapper.build().entityVO(versionInfoEntity);
		if (!versionInfoEntity.getVersion().equals(entity.getVersion())) {
			vo.setUpdateStatus(1);
			String url = apkUrl + "/" + versionInfoEntity.getAppPath() + "/" + versionInfoEntity.getAppName();
			vo.setApkUrl(url);
			vo.setVersionNote(versionInfoEntity.getVersionNote());
		} else {
			vo.setUpdateStatus(0);
		}
		return R.data(vo);
	}

	@GetMapping("/app")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "版本信息")
	public R<VersionInfoVO> app() {
		LambdaQueryWrapper<VersionInfoEntity> wrapper = Wrappers.<VersionInfoEntity>query().lambda();
		wrapper.eq(VersionInfoEntity::getIsDeleted, 0);
		VersionInfoEntity versionInfoEntity = versionManageService.getOne(wrapper);
		VersionInfoVO vo = VersionInfoWrapper.build().entityVO(versionInfoEntity);
		String url = apkUrl + "/" + versionInfoEntity.getAppPath() + "/" + versionInfoEntity.getAppName();
		vo.setApkUrl(url);
		try {
			String qrPath = apkSavePaht + File.separator + versionInfoEntity.getAppPath() + File.separator + versionInfoEntity.getAppPath() + ".jpg";
			File file = new File(qrPath);
			if (!file.exists()) {
				QRCodeUtils.encode2(url, versionInfoEntity.getAppPath(), apkSavePaht + File.separator + versionInfoEntity.getAppPath() + File.separator);
			}
			String qrurl = apkUrl + "/" + versionInfoEntity.getAppPath() + "/" + versionInfoEntity.getAppPath() + ".jpg";
			vo.setApkQrUrl(qrurl);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.data(vo);
	}

	@ApiLog("上传")
	@PostMapping(value = "/apk")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "上传APK", notes = "")
	public R<Map<String, String>> uploadApk(MultipartFile file, @RequestParam Map<String, Object> postData) {
		try {
			if (file.isEmpty()) {
				return R.fail("上传文件为空");
			}
			if (!postData.containsKey("appId") || !postData.containsKey("version")) {
				return R.fail("参数为空");
			}
			InputStream inputStream = file.getInputStream();
			String fileName = file.getOriginalFilename();
			String uuid = Func.randomUUID();
			String path = apkSavePaht + File.separator + uuid;
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdir();
			}
			path += File.separator + fileName;
			File apkFile = new File(path);
			FileOutputStream fileOutputStream = new FileOutputStream(apkFile);
			byte[] buff = new byte[1024];
			int len = -1;
			while ((len = inputStream.read(buff)) != -1) {
				fileOutputStream.write(buff, 0, len);
			}
			fileOutputStream.close();
			inputStream.close();
			String appId = (String) postData.get("appId");
			String version = (String) postData.get("version");
			String versionNote = (String) postData.get("versionNote");

			LambdaUpdateWrapper<VersionInfoEntity> wrapper = Wrappers.<VersionInfoEntity>update().lambda();
			wrapper.eq(VersionInfoEntity::getAppId, appId);
			wrapper.eq(VersionInfoEntity::getIsDeleted, 0);
			wrapper.set(VersionInfoEntity::getIsDeleted, 1);
			versionManageService.update(wrapper);

			VersionInfoEntity versionInfoEntity = new VersionInfoEntity();
			versionInfoEntity.setAppId(appId);
			versionInfoEntity.setAppName(fileName);
			versionInfoEntity.setAppPath(uuid);
			versionInfoEntity.setVersion(version);
			versionInfoEntity.setVersionNote(versionNote);
			versionManageService.save(versionInfoEntity);

			NoticeEntity noticeEntity = new NoticeEntity();
			noticeEntity.setCategory(3);
			noticeEntity.setSysMsg(1);
			noticeEntity.setReleaseTime(new Date());
			noticeEntity.setPublicState(1);
			noticeEntity.setTitle("APP版本更新提示");
			noticeEntity.setContent("APP版本更新，版本号:" + version + ",更新内容:" + versionNote + ",请及时到我的页面进行版本检查更新！");
			noticeService.save(noticeEntity);

			return R.success("上传成功");
		} catch (IOException e) {
			e.printStackTrace();
			return R.fail("上传错误 " + e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail("上传错误 " + e.getMessage());
		}
	}

}
