package com.hotent.portal.controller;

import java.io.File;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

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

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hotent.base.constants.SQLConst;
import com.hotent.base.query.Direction;
import com.hotent.base.query.FieldSort;
import com.hotent.base.util.*;
import com.hotent.sys.vo.SaveAndPublishModuleVo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
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.query.PageList;
import com.hotent.base.query.QueryFilter;
import com.hotent.base.util.time.DateFormatUtil;
import com.hotent.sys.persistence.manager.SysModuleDetailManager;
import com.hotent.sys.persistence.manager.SysModuleManager;
import com.hotent.sys.persistence.model.SysModule;
import com.hotent.sys.persistence.model.SysModuleDetail;

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


@RestController
@RequestMapping("/sys/sysModule/v1")
@Api(tags = "系统模块")
@ApiGroup(group= {ApiGroupConsts.GROUP_PORTAL})
public class SysModuleController extends BaseController<SysModuleManager, SysModule> {

    @Resource
    SysModuleManager sysModuleManager;
    @Resource
    SysModuleDetailManager sysModuleDetailManager;


    @RequestMapping(value = "listJson", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "模块列表(分页条件查询)数据", httpMethod = "POST", notes = "模块列表(分页条件查询)数据")
    public @ResponseBody
    PageList<SysModule> listJson(@ApiParam(name = "queryFilter", value = "通用查询对象") @RequestBody QueryFilter<SysModule> queryFilter) {
        queryFilter.getSorter().add(new FieldSort("updateTime", Direction.DESC));
        return sysModuleManager.query(queryFilter);
    }


    @RequestMapping(value = "getJson", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "模块明细页面", httpMethod = "GET", notes = "模块明细页面")
    public CommonResult<SysModule> getJson(@ApiParam(name = "id", value = "主键", required = false) @RequestParam String id) {
        if (StringUtil.isEmpty(id) ) {
            return new CommonResult<>(true, "获取成功", new SysModule());
        }
        SysModule sysModule =  sysModuleManager.get(id);
        if (BeanUtils.isEmpty(sysModule)) {
            return new CommonResult<>(true, "获取成功",new SysModule());
        }
        //Oracle数据库插入""字符串，会直接插入NULL，所以返回来的menu是NULL而不是"";Mysql则不会出现。
        String dbType = SQLUtil.getDbType();
        if(StringUtil.isEmpty(sysModule.getMenu())&& dbType.equals(SQLConst.DB_ORACLE)){
            sysModule.setMenu("");
        }
        List<SysModuleDetail> details = sysModuleDetailManager.getModuleDetail(sysModule.getId(), null);
        sysModule.setModuleDetail(details);
        return new CommonResult<>(true, "获取成功", sysModule);
    }

    @RequestMapping(value = "save", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "保存模块信息", httpMethod = "POST", notes = "保存模块信息")
    public CommonResult<String> save(@ApiParam(name = "sysModule", value = "模块信息对象") @RequestBody SysModule sysModule) {
        CommonResult<String> res=sysModuleManager.saveSysModule(sysModule);
        return res;
    }

    @RequestMapping(value = "saveModule", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "保存模块信息", httpMethod = "POST", notes = "保存模块信息")
    public CommonResult<String> saveModule(@ApiParam(name = "sysModule", value = "模块信息对象") @RequestBody SysModule sysModule) {
        CommonResult<String> resultMsg = null;
        String id = sysModule.getId();
        sysModuleManager.saveModule(sysModule);
        if (StringUtil.isEmpty(id)) {
            resultMsg = new CommonResult<String>(true,"添加模块信息成功",sysModule.getId());
        } else {
            resultMsg = new CommonResult<String>(true,"更新模块信息成功",sysModule.getId());
        }

        return resultMsg;
    }

    @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(required = false) String... ids) {
        CommonResult<String> message = null;
        try {

            sysModuleManager.removeByIds(ids);
            message = new CommonResult<String>("删除模块成功");
        } catch (Exception e) {
            message = new CommonResult<String>(false, "删除模块失败");
        }
        return message;
    }

    @RequestMapping(value = "isExist", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "判断模块编号是否存在", httpMethod = "GET", notes = "判断模块编号是否存在")
    public boolean isExist(@ApiParam(name = "code", value = "模块编码", required = false) @RequestParam String code) throws Exception {
        boolean res=false;
        if (StringUtil.isNotEmpty(code)) {
            SysModule temp = sysModuleManager.getModuleByCode(code);
            res =BeanUtils.isNotEmpty(temp);
        }
        return res;
    }


    @RequestMapping(value = "exportModule", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "导出格式为*.zip的模块对象，zip文件包含一个xml文件，xml文件都是多个模块对象;", httpMethod = "GET", notes = "导出格式为*.zip的模块对象，zip文件包含一个xml文件，xml文件都是多个模块对象;")
    public void exportModule(HttpServletRequest request, HttpServletResponse response, @ApiParam(name = "ids", value = "主键集合") @RequestParam String... ids) throws Exception {
        if (BeanUtils.isEmpty(ids)) return;
        List<String> idList = Arrays.asList(ids);
        Map map = sysModuleManager.exportModules(idList); // 输出xml
        String fileName = "ht_module_" + DateFormatUtil.format(LocalDateTime.now(), "yyyy_MMdd_HHmm");
        HttpUtil.downLoadFile(request, response, map, fileName);

    }


    private final static String ROOT_PATH = "attachFiles" + File.separator + "tempZip"; // 导入和导出的文件操作根目录

    @RequestMapping(value = "importModule", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "导入模块对象", httpMethod = "POST", notes = "导入模块对象")
    public CommonResult<String> importModule( @ApiParam(name="cacheFileId",value="缓存的模块对象文件id") @RequestParam Optional<String> cacheFileId) throws Exception {
        return sysModuleManager.importModule(cacheFileId);
    }

    @RequestMapping(value = "importModuleCheck", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "检查导入模块对象是否重复", httpMethod = "POST", notes = "检查导入模块对象是否重复")
    public CommonResult<String> importModuleCheck(@ApiParam(name="file",value="导入的zip文件",required=true) @RequestBody MultipartFile file) throws Exception {
        return sysModuleManager.importModuleCheck(file);
    }


    @PostMapping("saveAndPublishModule")
    @ApiOperation(value = "保存并发布流程模块", httpMethod = "POST", notes = "保存并发布流程模块")
    public CommonResult<String> saveAndPublishModule(@ApiParam(name = "saveAndPublishModuleVo" , value = "流程模块保存并发布参数") @RequestBody SaveAndPublishModuleVo saveAndPublishModuleVo,
                                                     @ApiParam(name = "type", value = "发布类型 manage：管理端，front：应用端，app：应用中心 ") @RequestParam("type") String type){
        CommonResult<String> res=sysModuleManager.saveAndPublishModule(saveAndPublishModuleVo,type);
        return res;
    }

    @RequestMapping(value = "updateSysModuleByCustomId", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "通过图表id修改系统模块相关信息", httpMethod = "GET", notes = "通过图表id修改系统模块相关信息")
    public CommonResult<String> updateSysModuleByCustomId(@ApiParam(name = "code", value = "图表id", required = true) @RequestParam String customChartId,
                                             @ApiParam(name = "objectNode", value = "图表信息", required = true) @RequestBody ObjectNode objectNode) throws Exception {
        return sysModuleManager.updateSysModuleByCustomId(customChartId,objectNode);
    }

}
