package com.yh.saas.platform.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.winsea.svc.base.base.entity.CommonAppendix;
import com.winsea.svc.base.base.service.IAppendixService;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.common.support.util.StringUtils;
import com.yh.saas.platform.exception.EnterpriseErrorCodeEnums;
import com.yh.saas.platform.exception.EnterpriseException;
import com.yh.saas.toolkit.ie.util.ExcelTemplateUtils;

/**
 * <p>
 * Excel存储 - Controller层
 * </p>
 *
 * @author ZhangMingYu
 * @since 2019年12月30日10:45:30
 */

@RestController
@RequestMapping("/excel")
public class ExcelController {

	@Autowired
	private ExcelTemplateUtils excelTemplateUtils;

	@SofaReference
	private IAppendixService appendixService;

	private static final String EXCEL_TEMPLATE = "excelTemplate";

	private static final String PRIVATE_PATH = "private";

	private static final String PUBLIC_PATH = "public";

	@PostMapping("/api/savePrivateTemplate")
	public void savePrivateTemplate(HttpServletRequest request) throws IOException {
		MultipartFile file = ((MultipartHttpServletRequest) request).getFile("template");
		if (null == file) {
			throw new EnterpriseException(EnterpriseErrorCodeEnums.EXCEL_TEMPLATE_FILE_NOT);
		}
		String compId = AuthSecurityUtils.getCurrentUserInfo().getCompId();
		String serviceCode = request.getParameter("serviceCode");

		if (StringUtils.isEmpty(compId) || StringUtils.isEmpty(serviceCode)) {
			throw new EnterpriseException(EnterpriseErrorCodeEnums.EXCEL_TEMPLATE_NOT);
		}

		String fileRootPath = excelTemplateUtils.getFileRootPath();
		String privatePath = fileRootPath + File.separator + EXCEL_TEMPLATE;
		checkPath(privatePath);

		privatePath += File.separator + PRIVATE_PATH;
		checkPath(privatePath);

		privatePath += File.separator + compId;
		checkPath(privatePath);

		String originalFileName = file.getOriginalFilename();
		String suffixName = originalFileName.substring(originalFileName.lastIndexOf("."));

		// 创建文件
		privatePath += File.separator + serviceCode + suffixName;
		Streams.copy(file.getInputStream(), new FileOutputStream(new File(privatePath)), true);

		createAppendixData(compId, originalFileName, privatePath);
	}

	@PostMapping("/api/savePublicTemplate")
	public void savePublicTemplate(HttpServletRequest request) throws IOException {
		MultipartFile file = ((MultipartHttpServletRequest) request).getFile("template");
		if (null == file) {
			throw new EnterpriseException(EnterpriseErrorCodeEnums.EXCEL_TEMPLATE_FILE_NOT);
		}
		String serviceCode = request.getParameter("serviceCode");
		if (StringUtils.isEmpty(serviceCode)) {
			throw new EnterpriseException(EnterpriseErrorCodeEnums.EXCEL_TEMPLATE_NOT);
		}

		String fileRootPath = excelTemplateUtils.getFileRootPath();
		String publicPath = fileRootPath + File.separator + EXCEL_TEMPLATE;
		checkPath(publicPath);

		publicPath += File.separator + PUBLIC_PATH;
		checkPath(publicPath);

		String originalFileName = file.getOriginalFilename();
		String filePath = publicPath + File.separator + serviceCode
				+ originalFileName.substring(originalFileName.lastIndexOf("."));
		Streams.copy(file.getInputStream(), new FileOutputStream(new File(filePath)), true);

		createAppendixData(null, originalFileName, filePath);
	}

	/**
	 * 检测路径是否拥有(如果没有进行创建)
	 *
	 * @param path 路径
	 */
	private void checkPath(String path) {
		if (!new File(path).exists()) {
			new File(path).mkdir();
		}
	}

	/**
	 * 创建附件数据
	 *
	 * @param compId       公司id
	 * @param appendixName 附件名称
	 * @param appendixPath 附件路径
	 */
	private void createAppendixData(String compId, String appendixName, String appendixPath) {
		// 如果是共通模板那就所有船都进行同步
		if (StringUtils.isEmpty(compId)) {
			CommonAppendix appendix = new CommonAppendix();
			appendix.setAppendixId(IdGenerator.generateUUID());
			appendix.setAppendixName(appendixName);
			appendix.setAppendixPath(appendixPath);
			appendix.setFromTableName(EXCEL_TEMPLATE);
			appendixService.insert(appendix);
			return;
		}

		// 如果是私有模板那就生成多条数据进行同步
		List<CommonAppendix> appendices = new ArrayList<>();
		CommonAppendix appendix = new CommonAppendix();
		appendix.setVesselId(null);
		appendix.setAppendixId(IdGenerator.generateUUID());
		appendix.setCompId(compId);
		appendix.setAppendixName(appendixName);
		appendix.setAppendixPath(appendixPath);
		appendix.setFromTableName(EXCEL_TEMPLATE);

		appendices.add(appendix);

		appendixService.insertBatch(appendices);
	}
}