package com.iotechn.unimall.launcher.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.config.JlbConfig;
import com.iotechn.unimall.core.util.StringUtils;
import com.iotechn.unimall.data.domain.tools.gen.GenTable;
import com.iotechn.unimall.data.domain.tools.gen.GenTableColumn;
import com.iotechn.unimall.data.mapper.tools.gen.GenTableColumnMapper;
import com.iotechn.unimall.data.mapper.tools.gen.GenTableMapper;
import com.iotechn.unimall.data.util.VelocityInitializer;
import com.iotechn.unimall.data.util.VelocityUtils;
import com.iotechn.unimall.launcher.utils.FileUtils;

@Controller
@RequestMapping("/common")
public class CommonController {
	private static final Logger logger = LoggerFactory.getLogger(ApiController.class);
	@Autowired
	private GenTableMapper tableMapper;
	@Autowired
	private GenTableColumnMapper tableColumnMapper;

	/**
	 * 通用下载请求
	 * 
	 * @param fileName 文件名称
	 * @param delete   是否删除
	 */
	@GetMapping("/download")
	public void fileDownload(String fileName, Boolean delete, HttpServletResponse response,
			HttpServletRequest request) {
		try {
			if (!FileUtils.isValidFilename(fileName)) {
				throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
			}
			String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
			String filePath = JlbConfig.getDownloadPath() + fileName;

			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition","attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
			FileUtils.writeBytes(filePath, response.getOutputStream());
			if (delete) {
				FileUtils.deleteFile(filePath);
			}
		} catch (Exception e) {
			logger.error("下载文件失败", e);
		}
	}

	@GetMapping("/batchGenCode")
	public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
		String[] tableNames = tables.split(",");
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);
		for (String tableName : tableNames) {
			generatorCode(tableName, zip);
		}
		IOUtils.closeQuietly(zip);
		genCode(response, outputStream.toByteArray(),tableNames[0]);
	}
	
	/**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data,String tables) throws IOException
    {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\""+tables+".zip\"");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:9528");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
	private void generatorCode(String tableName, ZipOutputStream zip) {
		GenTable gentable = new GenTable();
		gentable.setTableName(tableName);
		GenTable table = tableMapper.selectOne(gentable);
		// 查询表信息
		Wrapper<GenTableColumn> wrapper = new EntityWrapper<GenTableColumn>();
		wrapper.eq("table_id", table.getTableId());
		List<GenTableColumn> columns = tableColumnMapper.selectList(wrapper);
		table.setColumns(columns);
		setPkColumn(table, columns);

		VelocityInitializer.initVelocity();

		VelocityContext context = VelocityUtils.prepareContext(table);

		// 获取模板列表
		List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
		for (String template : templates) {
			// 渲染模板
			StringWriter sw = new StringWriter();
			Template tpl = Velocity.getTemplate(template, "UTF-8");
			tpl.merge(context, sw);
			try {
				// 添加到zip
				zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
				IOUtils.write(sw.toString(), zip, "UTF-8");
				IOUtils.closeQuietly(sw);
				zip.flush();
				zip.closeEntry();
			} catch (IOException e) {
			}
		}
	}

	public void setPkColumn(GenTable table, List<GenTableColumn> columns) {
		for (GenTableColumn column : columns) {
			if (column.isPk()) {
				table.setPkColumn(column);
				break;
			}
		}
		if (StringUtils.isNull(table.getPkColumn())) {
			table.setPkColumn(columns.get(0));
		}
	}

}
