package com.ozs.appshow.controller;

import java.io.InputStreamReader;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.ozs.appshow.dto.ChartInfoDTO;
import com.ozs.appshow.dto.ChartTypeDTO;
import com.ozs.appshow.dto.GetChartViewDTO;
import com.ozs.appshow.dto.RichTextFileR;
import com.ozs.appshow.dto.mdm.MdmInfoColumn;
import com.ozs.appshow.dto.mdm.MdmInfoDatabase;
import com.ozs.appshow.dto.mdm.MdmInfoTable;
import com.ozs.appshow.service.ChartInfoService;
import com.ozs.appshow.util.AccountApi;
import com.ozs.appshow.util.R;
import com.ozs.appshow.util.S;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * @ClassName: ChartInfoController
 * @Description: 应用展示--图表相关接口
 * @author: Zhao You Kai
 * @date: Apr 18, 2019 7:12:58 PM
 */

@Api(tags = { "应用展示—>图表管理接口" })
@RestController
public class ChartInfoController {

	@Autowired
	private ChartInfoService chartInfoService;
	@Autowired
	private AccountApi accountApi;

	@ApiOperation("获取MDM数据库列表-非原始库")
	@ApiImplicitParam(name = "resourceName", value = "资源名称", required = false, paramType = "query", dataType = "String")
	@GetMapping(value = "/appshow/chartInfo/listDatabase")
	public R<List<MdmInfoDatabase>> listDatabase(
			@RequestParam(value = "resourceName", required = false) String resourceName) {
		try {
			return chartInfoService.listDatabase(resourceName);
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("获取根据数据库ID获取数据表信息")
	@ApiImplicitParam(name = "databaseId", value = "数据库ID", required = false, paramType = "query", dataType = "String")
	@GetMapping(value = "/appshow/chartInfo/listTableByDatabaseId")
	public R<List<MdmInfoTable>> listTableByDatabaseId(
			@RequestParam(value = "databaseId", required = false) String databaseId) {
		try {
			return chartInfoService.listTableByDatabaseId(databaseId);
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("获取根据数据表ID获取字段信息")
	@ApiImplicitParam(name = "tableId", value = "数据表ID", required = false, paramType = "query", dataType = "String")
	@GetMapping(value = "/appshow/chartInfo/listColumnByTableId")
	public R<List<MdmInfoColumn>> listColumnByTableId(
			@RequestParam(value = "tableId", required = false) String tableId) {
		try {
			return chartInfoService.listColumnByTableId(tableId);
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("图表分页列表展示")
	@GetMapping("/appshow/chartInfo/list")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "chartName", value = "图表名称", required = false, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "chartType", value = "编辑状态，是否成功", required = false, paramType = "query", dataType = "Integer"),
			@ApiImplicitParam(name = "page", value = "当前页数", required = false, paramType = "query", dataType = "Integer"),
			@ApiImplicitParam(name = "pageSize", value = "每页条数", required = false, paramType = "query", dataType = "Integer"),
			@ApiImplicitParam(name = "sort", value = "排序字段", required = false, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "order", value = "排序方式", required = false, paramType = "query", dataType = "String") })
	public R<List<ChartInfoDTO>> listChartInfo(@RequestParam(value = "chartName", required = false) String chartName,
			@RequestParam(value = "chartType", required = false) Integer chartType,
			@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
			@RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", required = false, defaultValue = "update_time") String sort,
			@RequestParam(value = "order", required = false) String order) {
		try {
			return chartInfoService.listChartInfo(chartName, chartType, page, pageSize, sort, order);
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("获取图表类型")
	@GetMapping(value = "/appshow/chartType")
	public R<List<ChartTypeDTO>> listChartType() {
		try {
			return chartInfoService.listChartType();
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("根据数据库和表信息生成获取DML")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "tableId", value = "表Id", required = false, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "columnIds", value = "字段Id，多选逗号隔开的字符串", required = false, paramType = "query", dataType = "String") })
	@GetMapping(value = "/appshow/chartInfo/getDML")
	public R<String> getDML(@RequestParam("tableId") String tableId, @RequestParam("columnIds") String columnIds) {
		try {
			return chartInfoService.getDML(tableId, columnIds);
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("根据ID获取图表信息")
	@GetMapping("/appshow/chartInfo/{id}")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "图表Id", required = false, paramType = "path", dataType = "String") })
	public R<ChartInfoDTO> getChartInfo(@PathVariable String id) {
		try {
			return chartInfoService.getChartInfo(id);
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation(value = "图表新建上传文件")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "file", value = "图表文件", required = true, paramType = "form", dataType = "__file") })
	@PostMapping(value = "/appshow/chartInfo/loadChartFile", consumes = "multipart/*", headers = "content-type=multipart/form-data")
	public R<String> loadChartFile(@RequestParam("file") MultipartFile file, @RequestHeader("token") String token) {
		try {
			return chartInfoService.loadChartFile(file, accountApi.parseTokenId(token));
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("保存图表信息")
	@PostMapping("/appshow/chartInfo")
	public R<String> saveChartInfo(@RequestBody ChartInfoDTO chartInfoDTO, @RequestHeader("token") String token) {
		try {
			chartInfoDTO.setUpdateUserId(accountApi.parseTokenId(token));
			return chartInfoService.saveChartInfo(chartInfoDTO);
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("修改图表信息")
	@ApiImplicitParam(name = "id", value = "图表Id", required = false, paramType = "path", dataType = "String")
	@PutMapping("/appshow/chartInfo/{id}")
	public R<String> updateChartInfo(@PathVariable String id, @RequestBody ChartInfoDTO chartInfoDTO,
			@RequestHeader("token") String token) {
		try {
			chartInfoDTO.setId(id);
			chartInfoDTO.setUpdateUserId(accountApi.parseTokenId(token));
			return chartInfoService.updateChartInfo(chartInfoDTO);
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("图表配置接口")
	@PutMapping("/appshow/updateChartJson")
	public R<String> updateChartJson(@RequestBody ChartInfoDTO chartInfoDTO, @RequestHeader("token") String token) {
		try {
			chartInfoDTO.setUpdateUserId(accountApi.parseTokenId(token));
			return chartInfoService.updateChartJson(chartInfoDTO);
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("图表删除接口")
	@DeleteMapping("/appshow/chartInfo/{id}")
	public R<String> removeChart(@PathVariable String id) {
		try {
			return chartInfoService.removeChart(id);
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("通过分类编号获取分类下图表")
	@GetMapping("/appshow/chartInfo/listByClass")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "classCode", value = "图表分类编号", required = false, paramType = "query", dataType = "String") })
	public R<List<ChartInfoDTO>> listChartInfoByClass(
			@RequestParam(value = "classCode", required = false) String classCode) {
		try {
			return chartInfoService.listChartInfoByClass(classCode);
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("图表预览接口")
	@GetMapping("/appshow/chartView/{id}")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "图表ID", required = false, paramType = "path", dataType = "String") })
	public R<GetChartViewDTO> getChartView(@PathVariable String id) {
		try {
			return chartInfoService.getChartView(id);
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation(value = "富文本上传文件")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "dir", value = " 上传类型，分别为image、media、file", required = true, paramType = "form", dataType = "String"),
			@ApiImplicitParam(name = "imgFile", value = "图表文件", required = true, paramType = "form", dataType = "__file") })
	@PostMapping(value = "/appshow/chartInfo/loadRichTextFile", consumes = "multipart/*", headers = "content-type=multipart/form-data", produces = {
			"application/json;charset=UTF-8" })
	public RichTextFileR uploadRichTextFile(@RequestParam("imgFile") MultipartFile imgFile,
			@RequestParam("dir") String dir, @RequestParam("token") String token, HttpServletResponse response) {
		try {
			String userId = accountApi.parseTokenId(token);
			if (token == null || userId == null) {
				return new RichTextFileR(1, "token或秘钥不正确!");
			}
			// 视频文件类型只允许上传.mp4格式
			if ("media".equals(dir) && !imgFile.getOriginalFilename().contains(".mp4")) {
				return new RichTextFileR(1, "视频请上传.mp4文件");
			}
			return chartInfoService.uploadRichTextFile(imgFile, userId);
		} catch (Exception e) {
			e.printStackTrace();
			return new RichTextFileR(1, e.getMessage());
		}
	}

	@ApiOperation(value = "返回热力图坐标json数据")
	@GetMapping(value = "/appshow/chartInfo/tracksJson", produces = { "application/json;charset=UTF-8" })
	public Object tracksJson() {
		try {
			ClassPathResource classPathResource = new ClassPathResource("beijing.json");
			String json = IOUtils.toString(new InputStreamReader(classPathResource.getInputStream(), "UTF-8"));

			return JSONArray.parseArray(json);
		} catch (Exception e) {
			e.printStackTrace();
			return new RichTextFileR(1, e.getMessage());
		}
	}

}
