package com.hotent.portal.controller;


import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import com.hotent.base.exception.BaseException;
import com.hotent.base.query.*;
import com.hotent.base.util.*;
import com.hotent.base.util.time.DateFormatUtil;
import com.hotent.portal.model.PortalNewsNotice;
import com.hotent.portal.persistence.manager.PortalNewsNoticeManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.hotent.base.controller.BaseController;
import com.hotent.base.enums.ResponseErrorEnums;
import com.hotent.base.model.CommonResult;
import com.hotent.portal.model.PortalNewsTree;
import com.hotent.portal.persistence.manager.PortalNewsTreeManager;
import com.hotent.sys.persistence.model.SysMenu;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

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

/**
 *  前端控制器
 *
 * @company 广州宏天软件股份有限公司
 * @author 赵祥云
 * @since 2020-07-03
 */
@RestController
@RequestMapping("/portalNewsTree/v1/")
public class PortalNewsTreeController extends BaseController<PortalNewsTreeManager, PortalNewsTree> {

	@Resource
	PortalNewsNoticeManager portalNewsNoticeManager;

	@PostMapping("/createEntity")
	@ApiOperation("添加实体的接口")
	public CommonResult<String> createEntity(@ApiParam(name="model", value="实体信息") @RequestBody PortalNewsTree t) throws Exception{

		if(StringUtil.isEmpty(t.getId())){
			//拼接path与panthname
			t.setId(UniqueIdUtil.getSuid());
			t.setIntervalTime(BigDecimal.valueOf(3000L));
			String parentId = t.getParentId();
			PortalNewsTree portalNewsTree = baseService.get(parentId);
			t.setPath(portalNewsTree.getPath()+t.getId()+".");
			baseService.create(t);
		}else{

			baseService.updateEntity(t);
		}
		return new CommonResult<>();
	}

	@RequestMapping(value="getTree", method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "获得树形菜单", httpMethod = "GET", notes = "获得树形菜单")
	public List<PortalNewsTree> getTree() throws Exception {
		List<PortalNewsTree> list =baseService.getAll();
		list=BeanUtils.listToTree(list);
		return list;
	}

	@GetMapping("/issue")
	@ApiOperation("把第三级菜单发布成首页栏目")
	public CommonResult<String> issue(@ApiParam(name="id", value="主键") @RequestParam String id) throws Exception {
		return baseService.issue(id);
	}
	@GetMapping("/mobileIssue")
	@ApiOperation("把第三级菜单发布成首页栏目")
	public CommonResult<String> mobileIssue(@ApiParam(name="id", value="主键") @RequestParam String id) throws Exception {
		return baseService.mobileIssue(id);
	}

	@RequestMapping(value="mobileRemove", method=RequestMethod.DELETE, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "取消发布", httpMethod = "DELETE", notes = "取消发布")
	public CommonResult<String> mobileRemove(@ApiParam(name="id", value="主键") @RequestParam String id) throws Exception {
		return baseService.mobileRemove(id);
	}

	@PostMapping("exportTree")
	@ApiOperation(value = "导出分类", httpMethod = "POST", notes = "导出分类")
	public void exportTree(HttpServletResponse response, HttpServletRequest request, @RequestBody PortalNewsTree portalNewsTree,@RequestParam String exportType) throws Exception{
		BigDecimal rank = portalNewsTree.getRank();
		PageBean pageBean = new PageBean(PageBean.NO_PAGE,PageBean.WITHOUT_PAGE);
		if(BeanUtils.isNotEmpty(rank)){
			String json = "";
			Map<String, Object> exportMap = new HashMap();
			if (rank.intValue() == 1) {
				//一级分类
				QueryFilter<PortalNewsTree> queryFilter = QueryFilter.build();
				queryFilter.addFilter("PATH_",portalNewsTree.getPath().split("\\.")[0], QueryOP.RIGHT_LIKE, FieldRelation.AND);
				queryFilter.addFilter("ID_",portalNewsTree.getId(),QueryOP.NOT_EQUAL, FieldRelation.AND);
				queryFilter.setPageBean(pageBean);
				PageList<PortalNewsTree> query = baseService.query(queryFilter);
				exportMap.put("trees",query.getRows());
				if("1".equals(exportType)){
					//仅导出菜单数据
					json = JsonUtil.toJson(exportMap);
				}else if("2".equals(exportType)){
					//导出菜单数据和公告数据
					QueryFilter<PortalNewsNotice> noticeFilter = QueryFilter.build();
					noticeFilter.addFilter("CLASSIFY_PATH_",portalNewsTree.getPath().split("\\.")[0], QueryOP.RIGHT_LIKE, FieldRelation.AND);
					noticeFilter.setPageBean(pageBean);
					PageList<PortalNewsNotice> notices = portalNewsNoticeManager.query(noticeFilter);
					exportMap.put("notices",notices.getRows());
					json = JsonUtil.toJson(exportMap);
				}

			}else if(rank.intValue() == 2){
				//二级分类
				QueryFilter<PortalNewsTree> queryFilter = QueryFilter.build();
				queryFilter.addFilter("PATH_",
						portalNewsTree.getPath().split("\\.")[0]+"."+portalNewsTree.getPath().split("\\.")[1],
						QueryOP.RIGHT_LIKE, FieldRelation.AND);
				queryFilter.addFilter("PARENT_ID_",portalNewsTree.getId(),QueryOP.EQUAL, FieldRelation.AND);
				queryFilter.setPageBean(pageBean);
				PageList<PortalNewsTree> query = baseService.query(queryFilter);
				exportMap.put("trees", query.getRows());
				if("1".equals(exportType)){
					//仅导出菜单数据
					json = JsonUtil.toJson(exportMap);
				}else if("2".equals(exportType)){
					//导出菜单数据和公告数据
					QueryFilter<PortalNewsNotice> noticeFilter = QueryFilter.build();
					noticeFilter.addFilter("CLASSIFY_PATH_",
							portalNewsTree.getPath().split("\\.")[0]+"."+portalNewsTree.getPath().split("\\.")[1],
							QueryOP.RIGHT_LIKE, FieldRelation.AND);
					noticeFilter.setPageBean(pageBean);
					PageList<PortalNewsNotice> notices = portalNewsNoticeManager.query(noticeFilter);
					exportMap.put("notices", notices.getRows());
					json = JsonUtil.toJson(exportMap);
				}
			}else{
				throw new BaseException("不支持该分类的导出");
			}

			if(StringUtil.isNotEmpty(json)){
				String fileName = "portalTree" + DateFormatUtil.format(LocalDateTime.now(), "yyyy_MMdd_HHmm"); //压缩文件名
				HttpUtil.downLoadFile(request,response,json, "portalTree.json",fileName);
			}
		}
	}

	@PostMapping("importTree")
	@ApiOperation(value = "导入分类", httpMethod = "POST", notes = "导入分类")
	public CommonResult<String> importTree(MultipartHttpServletRequest request, HttpServletResponse response, @RequestParam String classifyId)throws Exception{
		MultipartFile file = request.getFile("file");
		String operate = request.getParameter("operate");
		String uzPath = "";
		try {
			String rootRealPath = (FileUtil.getIoTmpdir() +"/attachFiles/unZip/").replace("/", File.separator);
			FileUtil.createFolder(rootRealPath, true);
			String name = file.getOriginalFilename();
			String fileDir = StringUtil.substringBeforeLast(name, ".");
			ZipUtil.unZipFile(file, rootRealPath); // 解压文件
			uzPath = rootRealPath + File.separator + fileDir; // 解压后文件的真正路径
			if(StringUtils.equals(operate,"check")){
				return baseService.importCheck(uzPath,classifyId);
			}else {
				baseService.importFile(uzPath, classifyId);
			}
			return new CommonResult<>(true,"导入成功");
		}catch (Exception e){
			return new CommonResult(false,"导入失败："+e.getMessage());
		}finally {
			if (StringUtil.isNotEmpty(uzPath)) {
				File file1 = new File(uzPath);
				if (file1.exists()) {
					file1.delete();
				}
			}
		}
	}
}
