package com.hotent.portal.controller;

import java.time.LocalDateTime;
import java.util.List;

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

import com.hotent.base.query.*;
import org.springframework.beans.factory.annotation.Value;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.controller.BaseController;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.BeanUtils;
import com.hotent.base.util.HttpUtil;
import com.hotent.base.util.JsonUtil;
import com.hotent.base.util.StringUtil;
import com.hotent.base.util.ThreadMsgUtil;
import com.hotent.base.util.time.DateFormatUtil;
import com.hotent.portal.model.PortalWeixinMaterial;
import com.hotent.portal.model.SysIndexColumn;
import com.hotent.portal.persistence.manager.PortalWeixinMaterialManager;
import com.hotent.portal.persistence.manager.SysIndexColumnManager;
import com.hotent.sys.persistence.manager.SysAuthUserManager;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 首页栏目 控制器类
 *
 * @company 广州宏天软件股份有限公司
 * @author maoww
 * @email maoww@jee-soft.cn
 * @date 2018年6月14日
 */
@RestController
@RequestMapping("/portal/sysIndexColumn/sysIndexColumn/v1/")
@Api(tags="门户栏目")
@ApiGroup(group= {ApiGroupConsts.GROUP_PORTAL})
public class SysIndexColumnController extends BaseController<SysIndexColumnManager,SysIndexColumn> {
	@Resource
	SysIndexColumnManager sysIndexColumnService;
	@Resource
	SysAuthUserManager sysAuthUserManager;
    @Value("${system.saas.enable:false}")
    Boolean saasEnable;
    @Resource
    PortalWeixinMaterialManager portalWeixinMaterialManager;


	@RequestMapping(value="listJson", method=RequestMethod.POST, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "列表(分页条件查询)数据", httpMethod = "POST", notes = "列表(分页条件查询)数据")
	public PageList<SysIndexColumn> listJson(@ApiParam(name="queryFilter",value="通用查询对象") @RequestBody QueryFilter<SysIndexColumn> queryFilter) throws Exception {
        List<FieldSort> sorter = queryFilter.getSorter();
        if(BeanUtils.isEmpty(sorter)){
            sorter.add(new FieldSort("ID", Direction.DESC));
        }
        queryFilter.setSorter(sorter);
	    return sysIndexColumnService.query(queryFilter);
	}

	@RequestMapping(value="getJson", method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "明细页面", httpMethod = "GET", notes = "明细页面")
	public @ResponseBody SysIndexColumn getJson(@ApiParam(name="id", value="主键", required = true)@RequestParam String id) throws Exception {
		if (BeanUtils.isEmpty(id)) {
			return null;
		}
		return sysIndexColumnService.get(id);
	}
	@RequestMapping(value="getByAlias", method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "明细页面", httpMethod = "GET", notes = "明细页面")
	public @ResponseBody SysIndexColumn getByAlias(@ApiParam(name="alias", value="主键", required = true)@RequestParam String alias) throws Exception {
		if (BeanUtils.isEmpty(alias)) {
			return null;
		}

		return sysIndexColumnService.getByColumnAlias(alias);
	}

	@RequestMapping(value="remove", method=RequestMethod.DELETE, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "批量删除记录", httpMethod = "DELETE", notes = "批量删除记录")
	public CommonResult<String> remove(@ApiParam(name="ids", value="主键", required = true)@RequestParam String ids) throws Exception {
		try {
			String[] aryIds = StringUtil.getStringAryByStr(ids);
			sysIndexColumnService.removeByIds(aryIds);
			return new CommonResult<>(true, ThreadMsgUtil.getMessage(), null);
		} catch (Exception e) {
			e.printStackTrace();
			return new CommonResult<>(false, "删除栏目失败", null);
		}
	}

	@RequestMapping(value="save", method=RequestMethod.POST, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "添加或更新首页栏目", httpMethod = "POST", notes = "添加或更新首页栏目")
	public CommonResult<String> save(@ApiParam(name="sysIndexColumn", value="首页栏目")@RequestBody SysIndexColumn sysIndexColumn) throws Exception {
		CommonResult<String> res=sysIndexColumnService.saveSysIndexColumn(sysIndexColumn);
		return res;
	}

	@RequestMapping(value="getTemp", method=RequestMethod.POST, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "预览模版", httpMethod = "POST", notes = "预览模版")
	public String getTemp(@ApiParam(name="id", value="主键", required = true)@RequestParam String id) throws Exception {
		String html = "";
		SysIndexColumn sysIndexColumn = sysIndexColumnService.get(id);
		if(BeanUtils.isNotEmpty(sysIndexColumn)){
			html = "<div template-alias=\"" + sysIndexColumn.getAlias()
			+ "\"></div>";
		}
		return JsonUtil.toJson(html);
	}

	@RequestMapping(value="getData", method=RequestMethod.POST, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "取得首页栏目明细", httpMethod = "POST", notes = "取得首页栏目明细")
	public String getData(@ApiParam(name="alias", value="别名", required = true)@RequestParam String alias,
			@ApiParam(name="params", value="参数", required = true)@RequestParam String params
			) throws Exception {
		return sysIndexColumnService.getData(alias,params);
	}

	@RequestMapping(value="parseByAlias", method=RequestMethod.POST, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "取得首页栏目明细", httpMethod = "POST", notes = "取得首页栏目明细")
	public String parseByAlias(@ApiParam(name="alias", value="别名", required = true)@RequestParam String alias,
			@ApiParam(name="params", value="参数", required = true)@RequestParam String params
			) throws Exception {
		return sysIndexColumnService.parseByAlias(alias,params);
	}

	@RequestMapping(value="getDatasByAlias", method=RequestMethod.POST, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "取得首页栏目明细（根据别名批量获取）", httpMethod = "POST", notes = "取得首页栏目明细（根据别名批量获取）")
	public List<SysIndexColumn> getDatasByAlias(@ApiParam(name="alias", value="别名(多个用“,”号隔开)", required = true)@RequestBody String alias) throws Exception {
		return baseService.batchGetColumnAliases(alias);
	}

	@GetMapping(value = "validateProcAnn", produces = {"application/json; charset=utf-8"})
	@ApiOperation(value = "根据流程定义key判断该流程公示列表能否访问", httpMethod = "GET", notes = "根据流程定义key判断该流程公示列表能否访问")
	public CommonResult validateProcAnn(@ApiParam(name = "defKey", value = "流程定义key") @RequestParam String defKey)throws Exception{
		return sysIndexColumnService.validateProcAnn(defKey);
	}

	@PostMapping(value = "exportColumn", produces = {"application/json; charset=utf-8"})
	@ApiOperation(value = "根据id集合导出门户栏目", httpMethod = "POST", notes = "根据id集合导出门户栏目")
	public void exportColumn(@ApiParam(name = "ids", value = "id集合") @RequestBody List<String> ids,
							 HttpServletRequest request , HttpServletResponse response) throws Exception{
		String fileName = "indexColumn_" + DateFormatUtil.format(LocalDateTime.now(),"yyyy_MM_dd_HHmm");
		String json = baseService.exportColumn(ids);
		HttpUtil.downLoadFile(request,response,json,"indexColumns.json",fileName);
	}

	@RequestMapping(value="importColumn", method=RequestMethod.POST, produces={"application/json; charset=utf-8" })
	@ApiOperation(value = "导入栏目", httpMethod = "POST", notes = "导入栏目")
	public CommonResult importColumn(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
		CommonResult res=sysIndexColumnService.importColumn(request,response);
		return res;
	}

    @RequestMapping(value="importData", method=RequestMethod.POST, produces={"application/json; charset=utf-8" })
    @ApiOperation(value = "导入栏目", httpMethod = "POST", notes = "导入栏目")
    public CommonResult<String> importData(@ApiParam(name="unZipFilePath",value="unZipFilePath", required = true)@RequestParam String unZipFilePath,
                                           @ApiParam(name="status",value="status", required = true)@RequestParam String status) throws Exception{
        CommonResult<String> res=sysIndexColumnService.importFileData(unZipFilePath,status);
        return res;
    }


    @GetMapping("getMaterial")
	@ApiOperation(value = "获取微信公众号图文素材栏目", httpMethod = "GET", notes = "获取微信公众号图文素材栏目")
	public List<PortalWeixinMaterial> getMaterial(@ApiParam(name="columnId", value="栏目id") @RequestParam String columnId,@ApiParam(name="type", value="type") @RequestParam String type,
			@ApiParam(name="offset", value="offset") @RequestParam int offset,@ApiParam(name="count", value="count") @RequestParam int count) throws Exception {
		SysIndexColumn column = baseService.getById(columnId);
		QueryFilter filter = QueryFilter.build().withPage(new PageBean(offset, count));
		filter.addFilter("appid", column.getAppid(), QueryOP.EQUAL);
		PageList<PortalWeixinMaterial> page = portalWeixinMaterialManager.query(filter);
		return page.getRows();
	}
}
