package com.yihu.hos.resource.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.hos.common.JXLUtil;
import com.yihu.hos.resource.model.*;
import com.yihu.hos.resource.service.RsResourceRestServiceImpl;
import com.yihu.hos.resource.service.RsResourceServiceImpl;
import com.yihu.hos.resource.viewresult.RsResourceDeatilModel;
import com.yihu.hos.resource.viewresult.RsResourceDimensionModel;
import com.yihu.hos.web.framework.model.ActionResult;
import com.yihu.hos.web.framework.model.DataGridResult;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.controller.BaseController;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenweida on 2015/12/15.
 */
@RequestMapping("/resource")
@Controller
public class RsResourceController extends BaseController {
    @Resource(name = RsResourceServiceImpl.BEAN_ID)
    private RsResourceServiceImpl resourceService;
    @Resource(name = RsResourceRestServiceImpl.BEAN_ID)
    private RsResourceRestServiceImpl resourceRestService;


    /**
     * 访问resourcebrowse/resource.jsp页面
     *
     * @param model
     * @param mode
     * @return
     */
    @RequestMapping("/resourcePage")
    public String resourcePage(Model model, String mode) {
        model.addAttribute("mode", mode);
        model.addAttribute("contentPage", "resource/resourcebrowse/resource");
        return "partView";
    }

    @RequestMapping("/resourceBrowse")
    public String resourceBrowse(Model model, String id) {
        try {
            if (!StringUtils.isEmpty(id))
                model.addAttribute("resourceModel", resourceService.getRsResourceDeatilModel(id));
            model.addAttribute("contentPage", "resource/resourceregister/resourceBrowse");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "partView";
    }

    /**
     * 查找树List
     *
     * @return
     */
    @RequestMapping("/resourceTreeList")
    @ResponseBody
    public Result resourceTreeList(String name) {

        try {
            ActionResult actionResult = new ActionResult();
            actionResult.setData(resourceService.getResourceTreeList(name));
            return actionResult;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping("/resourceCategoryTreeList")
    @ResponseBody
    public Result resourceCategoryTreeList(String name) {
        try {
            ActionResult actionResult = new ActionResult();
            actionResult.setData(resourceService.resourceCategoryTreeList(name));
            return actionResult;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }


    //跳转到列表页
    @RequestMapping("/resource/initial")
    public String initial(Model model) {
        model.addAttribute("contentPage", "/resource/resourceregister/rsResourceManage");
        return "partView";
    }

    //跳转到资源配置页
    @RequestMapping("/resource/configInitial")
    public String resourceConfigInitial(String id, Model model) {
        try {
            model.addAttribute("resourceModel", resourceService.getRsResourceDeatilModel(id));
            model.addAttribute("model", model);
            model.addAttribute("contentPage", "/resource/resourceregister/rsResourceConfig");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "partView";
    }

    //跳转到资源授权页
    @RequestMapping("/resource/authorizeInitial")
    public String rsResourceAuthorizeInitial(String id, Model model) {
        try {
            model.addAttribute("resourceModel", resourceService.getRsResourceDeatilModel(id));
            model.addAttribute("contentPage", "/resource/resourceregister/rsResourceAuthorize");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "partView";
    }

    /**
     * 跳转到资源授权的dialog
     *
     * @param model
     * @param id
     * @param mode
     * @return
     */
    @RequestMapping("/resource/rsResourceAuthorize")
    public String rsResourceAuthorize(Model model, String id, String mode) {
        try {
            model.addAttribute("resourceId", id);
            model.addAttribute("mode", mode);
            model.addAttribute("contentPage", "/resource/resourceregister/rsResourceAuthorizeDialog");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "pageView";
    }

    /**
     * 跳转到导入数据集的界面
     *
     * @param model
     * @param mode
     * @return
     */
    @RequestMapping("/resource/rsResourceImportDataset")
    public String rsResourceImportDataset(Model model, String mode, String resourceId, String datasetId) {
        try {
            model.addAttribute("mode", mode);
            model.addAttribute("resourceId", resourceId);
            RsResourceDeatilModel rrsdm = resourceService.getRsResourceDeatilModel(resourceId);
            model.addAttribute("datasetId", rrsdm.getDatasetCode());
            if (!StringUtils.isEmpty(datasetId)) {
                RsResourceDataset ds = resourceService.getLocalDataSetById(datasetId);
                model.addAttribute("datasetCode", ds.getCode());
            }
            model.addAttribute("contentPage", "/resource/resourceregister/rsResourceImportDatasetDialog");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "pageView";
    }

    /**
     * 打开新增或者编辑资源字段的界面
     *
     * @param model
     * @param id
     * @param mode
     * @return
     */
    @RequestMapping("/resource/rsResourceFieldInfo")
    public String rsResourceFieldInfo(Model model, String id, String mode, String datasetId, String resourceId) {
        try {
            RsResourceMetadata rsResourceMetadata = null;
            //mode定义：new modify view三种模式，新增，修改，查看
            if (mode.equals("view")) {
                rsResourceMetadata = resourceService.getRsResourceMetadata(id);
            } else if (mode.equals("modify")) {
                rsResourceMetadata = resourceService.getRsResourceMetadata(id);
            } else {
                rsResourceMetadata = new RsResourceMetadata();
            }
            model.addAttribute("entity", rsResourceMetadata);
            model.addAttribute("mode", mode);
            model.addAttribute("datasetId", datasetId);
            model.addAttribute("resourceId", resourceId);
            model.addAttribute("contentPage", "/resource/resourceregister/rsResourceFieldInfoDialog");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "pageView";
    }

    /**
     * 跳转到资源维度配置的dialog
     *
     * @param model
     * @param id
     * @param resourceId
     * @return
     */
    @RequestMapping("/resource/rsResourceDimension")
    public String rsResourceDimension(Model model, String id, String resourceId) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            RsAppResourceDetail rard = resourceService.getAppResourceDetailId(id);
            model.addAttribute("appResourceDetail", rard);
            model.addAttribute("metadataName", resourceService.getRsResourceMetadata(rard.getMetadataId()));

            List<RsResourceDimensionModel> rsResourceDimensionModels = resourceService.getDimensionByResourceId(resourceId);
            model.addAttribute("resultSelect", mapper.writeValueAsString(rsResourceDimensionModels));
            model.addAttribute("resourceId", resourceId);
            model.addAttribute("contentPage", "/resource/resourceregister/rsResourceDimensionDialog");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "pageView";
    }

    @RequestMapping("/resource/searchRsResource")
    @ResponseBody
    public Result getResourceList(HttpServletRequest request) {

        try {

            String page = request.getParameter("page");
            String rows = request.getParameter("rows");
            String categoryId = request.getParameter("categoryId");
            String resourceName = request.getParameter("resourceName");

            DataGridResult result = new DataGridResult(Integer.valueOf(page), Integer.valueOf(rows));
            Map<String, Object> conditionMap = new HashMap<>();
            conditionMap.put("categoryId", categoryId);
            conditionMap.put("resourceName", resourceName);
            result = resourceService.getResourceList(conditionMap, Integer.valueOf(page), Integer.valueOf(rows));
            return result;
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }

    }

    /**
     * 资源浏览界面 查找datagrid
     *
     * @param request
     * @return
     */
    @RequestMapping("/resource/searchRomoteResourceList")
    @ResponseBody
    public Result searchRomoteResourceList(HttpServletRequest request) {
        DataGridResult result = new DataGridResult();
        String id = request.getParameter("id");//资源ID
        if (StringUtils.isEmpty(id)) {
            return result;
        }
        try {
            //现在最多导出五十条数据
            String pageSize = StringUtils.isEmpty(request.getParameter("rows")) ? "10" : request.getParameter("rows");
            String currPage = StringUtils.isEmpty(request.getParameter("page")) ? "1" : request.getParameter("page");

            String queryParams = request.getParameter("queryParams");
            //得到资源对象
            RsResourceDeatilModel resource = resourceService.getRsResourceDeatilModel(id);
            //设置参数
            Map<String, String> params = new HashMap<>();
            params.put("rows", pageSize);
            params.put("page", currPage);

            if (!StringUtils.isEmpty(resource.getDatasetCode())) {
                RsResourceRestDetail rrd = resourceRestService.getResourceRestDetailByCode(resource.getCode());
                if ("resource.getMongoDBData".equals(rrd.getNamespace())) {
                    //如果是访问mongo 则加入表的参数
                    String datasetId = resource.getDatasetCode();
                    if (!StringUtils.isEmpty(datasetId)) {
                        RsResourceDataset rd = resourceService.getLocalDataSetById(datasetId);
                        params.put("tableCode", rd.getCode());
                    } else {
                        return result;
                    }
                }
            }
            if (!StringUtils.isEmpty(queryParams)) {
                params.put("condition", queryParams);
            } else {
                params.put("condition", "{}");
            }
            //访问服务得到数据
            String response_params = resourceService.searchRomoteResourceList(resource.getCode(), params);
            ObjectMapper mapper = new ObjectMapper();
            if (response_params.startsWith("[")) {
                //如果是数组
                ArrayNode jsonArray = mapper.readValue(response_params, ArrayNode.class);
                Integer count = jsonArray.size();//得到总数
                //访问服务得到元数据
                //设置动态datagrid值
                result.setDetailModelList(mapper.readValue(response_params.toString().replace(":null", ":\"\""), List.class));
                result.setTotalCount(count);
                result.setCurrPage(Integer.valueOf(currPage));
                result.setPageSize(count);
                result.setSuccessFlg(true);
            } else if (response_params.startsWith("{")) {
                ObjectNode objectNode = mapper.readValue(response_params, ObjectNode.class);
                Integer count = objectNode.get("count").asInt();//得到总数
                //访问服务得到元数据
                //设置动态datagrid值
                String s = objectNode.get("detailModelList").toString().replace(":null", ":\"\"");
                result.setDetailModelList(mapper.readValue(s, List.class));
                result.setTotalCount(count);
                result.setCurrPage(Integer.valueOf(currPage));
                result.setPageSize(Integer.valueOf(pageSize));
                result.setSuccessFlg(true);
            } else {
                result.setSuccessFlg(false);
                result.setMessage("获取数据失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccessFlg(false);
            result.setMessage("获取数据失败");
        }
        return result;
    }

    /**
     * 资源浏览界面 查找datagrid列
     *
     * @param request
     * @return
     */
    @RequestMapping("/resource/searchResourceDatagridColunm")
    @ResponseBody
    public String searchResourceDatagridColunm(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> mapParam = new HashMap<String, Object>();
        ObjectMapper mapper = new ObjectMapper();
        String id = request.getParameter("id");//资源ID
        try {
            //得到资源对象
            RsResourceDeatilModel resource = resourceService.getRsResourceDeatilModel(id);
            //得到列信息
            List<RsResourceMetadata> rsResourceMetadatas = resourceService.getResourceMetadataListColumn(resource.getId());
            List<String> colunmName = new ArrayList<String>();
            List<String> colunmCode = new ArrayList<String>();
            List<String> colunmType = new ArrayList<String>();
            List<String> colunmDict = new ArrayList<String>();
            for (RsResourceMetadata r : rsResourceMetadatas) {
                colunmName.add(r.getName());
                colunmCode.add(r.getCode());
                colunmType.add(r.getColumnType());
                colunmDict.add(r.getDictId() + "");
            }
            //设置动态datagrid值
            mapParam.put("colunmName", colunmName);
            mapParam.put("colunmCode", colunmCode);
            mapParam.put("colunmDict", colunmDict);
            mapParam.put("colunmType", colunmType);
            return mapper.writeValueAsString(mapParam);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 找出Field列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/resource/searchResourceFieldList")
    @ResponseBody
    public Result searchResourceFieldList(HttpServletRequest request) {

        try {

            String resourceId = request.getParameter("resourceId");
            String page = request.getParameter("page");
            String rows = request.getParameter("rows");
            DataGridResult result = new DataGridResult(Integer.valueOf(page), Integer.valueOf(rows));
            Map<String, Object> conditionMap = new HashMap<>();
            conditionMap.put("resourceId", resourceId);
            result = resourceService.getResourceFiled(conditionMap, Integer.valueOf(page), Integer.valueOf(rows));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }


    /**
     * 跳转到新增或者修改资源的界面
     *
     * @param model
     * @param id
     * @param mode
     * @return
     */
    @RequestMapping("/resource/rsResourceInfo")
    public String rsResourceInfoTemplate(Model model, String id, String mode, String categoryId) {
        try {
            RsResourceDeatilModel rsResource = null;
            //mode定义：new modify view三种模式，新增，修改，查看
            if (mode.equals("view")) {
                rsResource = resourceService.getRsResourceDeatilModel(id);
            } else if (mode.equals("modify")) {
                rsResource = resourceService.getRsResourceDeatilModel(id);
            } else {
                rsResource = new RsResourceDeatilModel();
            }
            model.addAttribute("entity", rsResource);
            model.addAttribute("categoryId", categoryId);
            model.addAttribute("mode", mode);
            model.addAttribute("contentPage", "/resource/resourceregister/rsResourceInfoDialog");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "pageView";
    }

    /**
     * 修改资源
     *
     * @param request
     * @return
     */
    @RequestMapping("/resource/updateRsResource")
    @ResponseBody
    public Result updateRsResource(HttpServletRequest request) {

        try {
            String category = request.getParameter("category");
            String rate = request.getParameter("rate");
            String code = request.getParameter("code");
            String name = request.getParameter("name");
            String supportType = request.getParameter("inp_resource_support_type");
            String type = request.getParameter("inp_resource_type");
            String id = request.getParameter("id");
            RsResource rs = new RsResource();
            rs.setId(id);
            rs.setCode(code);
            rs.setType(type);
            rs.setName(name);
            rs.setServiceRate(rate);
            rs.setCategory(category);
            rs.setDataSupportType(supportType);
            resourceService.updateRsResource(rs);
            return Result.success("修改成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改失败！");
        }
    }

    /**
     * 新增资源
     *
     * @param request
     * @return
     */
    @RequestMapping("/resource/createRsResource")
    @ResponseBody
    public Result createRsResource(HttpServletRequest request) {
        try {
            String category = request.getParameter("category");
            String rate = request.getParameter("rate");
            String code = request.getParameter("code");
            String name = request.getParameter("name");
            String supportType = request.getParameter("inp_resource_support_type");
            String type = request.getParameter("inp_resource_type");
            RsResource rs = new RsResource();
            rs.setCode(code);
            rs.setType(type);
            rs.setName(name);
            rs.setServiceRate(rate);
            rs.setCategory(category);
            rs.setDataSupportType(supportType);
            resourceService.createRsResource(rs);
            return Result.success("新增成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("新增失败！");
        }
    }

    @RequestMapping("/resource/deleteResource")
    @ResponseBody
    public Result deleteResource(HttpServletRequest request) {

        try {
            String id = request.getParameter("id");
            resourceService.deleteResource(id);
            return Result.success("删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败！");
        }
    }

    @RequestMapping("/resource/getDataSet")
    @ResponseBody
    public Result getDataSet(HttpServletRequest request) {
        try {
            Map<String, Object> params = new HashMap<String, Object>();
            String datasetId = request.getParameter("datasetId");
            String name = request.getParameter("name");
            String page = request.getParameter("page");
            String rsResourceImportDatasetDialogName = request.getParameter("rsResourceImportDatasetDialogName");
            String rows = request.getParameter("rows");
            params.put("datasetId", datasetId);
            params.put("name", name);
            params.put("rsResourceImportDatasetDialogName", rsResourceImportDatasetDialogName);
            params.put("page", page);
            params.put("rows", rows);
            return resourceService.getDataSet(params);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败！");
        }
    }

    @RequestMapping("/resource/getMetaData")
    @ResponseBody
    public Result getMetaData(HttpServletRequest request) {
        try {
            Map<String, Object> params = new HashMap<String, Object>();
            String id = request.getParameter("id");
            params.put("id", id);
            return resourceService.getMetaData(params);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败！");
        }
    }

    /**
     * 导入全部数据集
     *
     * @param request
     * @return
     */
    @RequestMapping("/resource/improtAllMetadata")
    @ResponseBody
    public Result improtAllMetadata(HttpServletRequest request) {
        try {
            String reourceId = request.getParameter("reourceId");//资源ID
            String datasetId = request.getParameter("datasetId");//资源ID
            System.out.println("datasetId" + datasetId);
            RsResourceDataset dataset = new RsResourceDataset();
            BeanUtils.populate(dataset, request.getParameterMap());
            return resourceService.improtAllMetadata(dataset, reourceId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 导入全部数据集
     *
     * @param request
     * @return
     */
    @RequestMapping("/resource/improtSameMetadata")
    @ResponseBody
    public Result improtSameMetadata(HttpServletRequest request) {
        try {
            String dataset = request.getParameter("dataset");//数据集
            String metaData = request.getParameter("selecrMedatata");//选中的metaData
            String reourceId = request.getParameter("reourceId");//资源ID
            String datasetId = request.getParameter("datasetId");//数据集ID
            return resourceService.improtSameMetadata(reourceId, metaData, dataset, datasetId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 导入数据集
     *
     * @param request
     * @return
     */
    @RequestMapping("/resource/deleteMetadata")
    @ResponseBody
    public Result deleteMetadata(HttpServletRequest request) {
        try {
            String id = request.getParameter("id");//资源ID
            return resourceService.deleteMetadata(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping("/resource/createMetaData")
    @ResponseBody
    public Result createMetaData(HttpServletRequest request) {
        try {
            if (StringUtils.isEmpty(request.getParameter("inp_field_is_PK"))) {
                throw new Exception("请选择是否为主键");
            }
            if (StringUtils.isEmpty(request.getParameter("inp_field_is_null"))) {
                throw new Exception("请选择是否为空");
            }
            RsResourceMetadata rmd = new RsResourceMetadata();
            rmd.setCode(request.getParameter("columnCode"));
            rmd.setColumnName(request.getParameter("columnCode"));
            rmd.setColumnLength(request.getParameter("columnLength"));
            rmd.setColumnType(request.getParameter("columnType"));
            rmd.setDefinition(request.getParameter("definition"));
            rmd.setNullable(Integer.valueOf(request.getParameter("inp_field_is_null")));
            rmd.setPrimaryKey(Integer.valueOf(request.getParameter("inp_field_is_PK")));
            rmd.setDataSupportType(2);
            rmd.setLogicDataSource(request.getParameter("logicDataSource"));
            rmd.setResourceId(request.getParameter("resourceId"));
            rmd.setName(request.getParameter("name"));
            // BeanUtils.populate(rmd, request.getParameterMap("logicDataSource"));
            return resourceService.createMetaData(rmd);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping("/resource/updateMetaData")
    @ResponseBody
    public Result updateMetaData(HttpServletRequest request) {
        try {
            RsResourceMetadata rmd = new RsResourceMetadata();
            rmd.setId(request.getParameter("id"));
            rmd.setCode(request.getParameter("columnCode"));
            rmd.setColumnName(request.getParameter("columnCode"));
            rmd.setColumnLength(request.getParameter("columnLength"));
            rmd.setColumnType(request.getParameter("columnType"));
            rmd.setDefinition(request.getParameter("definition"));
            if (StringUtils.isEmpty(request.getParameter("inp_field_is_PK"))) {
                throw new Exception("请选择是否为主键");
            }
            if (StringUtils.isEmpty(request.getParameter("inp_field_is_null"))) {
                throw new Exception("请选择是否为空");
            }
            rmd.setNullable(Integer.valueOf(request.getParameter("inp_field_is_null")));
            rmd.setPrimaryKey(Integer.valueOf(request.getParameter("inp_field_is_PK")));
            rmd.setDataSupportType(2);
            rmd.setLogicDataSource(request.getParameter("logicDataSource"));
            rmd.setResourceId(request.getParameter("resourceId"));
            rmd.setName(request.getParameter("name"));
            return resourceService.updateMetaData(rmd);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping("/resource/getMetaDataByDatasetId")
    @ResponseBody
    public Result getMetaDataByDatasetId(HttpServletRequest request) {
        try {
            String datasetCode = request.getParameter("datasetCode");
            String datasetId = request.getParameter("datasetId");
            return resourceService.getMetaDataByDatasetId(datasetCode, datasetId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping("/resource/getResourceAuthorize")
    @ResponseBody
    public Result getResourceAuthorize(HttpServletRequest request) {
        try {
            String resourceId = request.getParameter("resourceId");
            String appId = request.getParameter("appId");
            if (StringUtils.isEmpty(resourceId) || StringUtils.isEmpty(appId)) {
                return new DataGridResult();
            }
            return resourceService.getResourceAuthorize(resourceId, appId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 资源授权页面 进入应用授权时 查询授权和未授权的应用
     *
     * @param request
     * @return
     */
    @RequestMapping("/resource/getResourceApp")
    @ResponseBody
    public Result getResourceApp(HttpServletRequest request) {
        try {
            String id = request.getParameter("id");
            return resourceService.getResourceApp(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新资源授权的应用
     *
     * @param request
     * @return
     */
    @RequestMapping("/resource/updateResourceApp")
    @ResponseBody
    public Result updateResourceApp(HttpServletRequest request) {
        try {
            String ids = request.getParameter("ids");
            String resourceId = request.getParameter("resourceId");
            return resourceService.updateResourceApp(ids, resourceId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新资源授权的应用
     *
     * @param request
     * @return
     */
    @RequestMapping("/resource/getResourceAppList")
    @ResponseBody
    public Result getResourceAppList(HttpServletRequest request) {
        try {
            String resourceId = request.getParameter("resourceId");
            return resourceService.getResourceAppList(resourceId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 全部禁止1 全部允许2 选中禁止3 选中允许4
     *
     * @param request
     * @return
     */
    @RequestMapping("/resource/changeAppResource")
    @ResponseBody
    public Result changeAppResource(HttpServletRequest request) {
        try {
            String resourceId = request.getParameter("resourceId");
            String appId = request.getParameter("appId");
            String ids = request.getParameter("ids");
            String flag = request.getParameter("flag");
            return resourceService.changeAppResource(flag, appId, ids, resourceId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping("/resource/saveResourceDimension")
    @ResponseBody
    public Result saveResourceDimension(HttpServletRequest request) {
        try {
            String appResourceDeatilId = request.getParameter("appResourceDeatilId");
            String value = request.getParameter("value");
            String dimensionId = request.getParameter("dimensionId");
            RsAppResourceDetail appResourceDetail = new RsAppResourceDetail();
            appResourceDetail.setId(appResourceDeatilId);
            appResourceDetail.setDimensionValue(value);
            appResourceDetail.setDimensionId(dimensionId);
            return resourceService.saveResourceDimension(appResourceDetail);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }


    @RequestMapping("/exportAllExcel")
    public void exportAllExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            String field = request.getParameter("field");
            ObjectMapper mapper = new ObjectMapper();
            ArrayNode jsonArray = mapper.readValue(field, ArrayNode.class);
            String name = request.getParameter("name");
            Map<String, String> fieldMap = new HashMap<String, String>();
            for (JsonNode jo : jsonArray) {
                fieldMap.put(String.valueOf(jo.get("key")), String.valueOf(jo.get("value")));
            }
            Result e = this.searchRomoteResourceList(request);
            JXLUtil.listMapToExcel(((DataGridResult) e).getDetailModelList(), fieldMap, name, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/exportSomeExcel")
    public void exportSomeExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String field = request.getParameter("field");
            String data = request.getParameter("data");
            String name = request.getParameter("name");
            ArrayNode jsonArray = mapper.readValue(field, ArrayNode.class);
            Map<String, String> fieldMap = new HashMap<String, String>();
            for (JsonNode jo : jsonArray) {
                fieldMap.put(String.valueOf(jo.get("key")), String.valueOf(jo.get("value")));

            }
            JXLUtil.listMapToExcel(mapper.readValue(data, List.class), fieldMap, name, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
