package com.yihu.hos.resource.service;

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.core.http.HttpClientKit;
import com.yihu.hos.resource.dao.*;
import com.yihu.hos.resource.model.*;
import com.yihu.hos.resource.viewresult.ResourceAuthorizeDGModel;
import com.yihu.hos.resource.viewresult.RsResourceDeatilModel;
import com.yihu.hos.resource.viewresult.RsResourceDimensionModel;
import com.yihu.hos.system.dao.AppDao;
import com.yihu.hos.system.model.SystemApp;
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.model.TreeResult;
import com.yihu.hos.web.framework.util.PKUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("resourceService")
public class RsResourceServiceImpl {

    public static final String BEAN_ID = "resourceService";

    @Resource(name = RsResourceCategoryDaoImpl.BEAN_ID)
    private RsResourceCategoryDaoImpl rsResourceCategoryDao;
    @Resource(name = RsResourceDaoImpl.BEAN_ID)
    private RsResourceDaoImpl rsResourceDao;
    @Resource(name = RsResourceDatasetDaoImpl.BEAN_ID)
    private RsResourceDatasetDaoImpl resourceDatasetDao;
    @Resource(name = RsResourceMetadataDaoImpl.BEAN_ID)
    private RsResourceMetadataDaoImpl resourceMetadataDao;
    @Resource(name = AppDao.BEAN_ID)
    private AppDao appDao;
    @Resource(name = RsAppResourceDaoImpl.BEAN_ID)
    private RsAppResourceDaoImpl appResourceDao;
    @Resource(name = RsAppResourceDetailDaoImpl.BEAN_ID)
    private RsAppResourceDetailDaoImpl rsAppResourceDetailDao;
    @Resource(name = RsResourceDimensionDaoImpl.BEAN_ID)
    private RsResourceDimensionDaoImpl resourceDimensionDao;

    @Resource(name = StdService.BEAN_ID)
    private StdService stdService;
    @Autowired
    private ObjectMapper objectMapper;

  
    public List<TreeResult> getResourceTreeList(String name) throws Exception {
        List<TreeResult> treeVOs = new ArrayList<TreeResult>();
        List<String> pidList = new ArrayList<>();
        List<String> pidList1 = new ArrayList<>();
        List<String> idList = new ArrayList<>();
        List<String> idList1 = new ArrayList<>();
        List<RsResourceCategory> rsCategorya = rsResourceCategoryDao.getAllRsResourceCategory();
        if (name != null && name.length() > 0) {
            for (int i = 0; i < rsCategorya.size(); i++) {
                RsResourceCategory r = rsCategorya.get(i);
                TreeResult treeVO = new TreeResult();
                if (r.getName().contains(name)) {
                    treeVO.setId(r.getId());
                    treeVO.setPid(r.getPid());
                    pidList.add(r.getPid());
                    idList.add(r.getId());
                    treeVO.setText(r.getName());
                    treeVO.setType("1");
                    treeVOs.add(treeVO);
                    rsCategorya.remove(r);
                    i--;
                }

            }
        }
        else {
            for (RsResourceCategory r : rsCategorya) {
                TreeResult treeVO = new TreeResult();
                treeVO.setId(r.getId());
                treeVO.setPid(r.getPid());
                treeVO.setText(r.getName());
                treeVO.setType("1");
                treeVOs.add(treeVO);
            }
        }
        while (pidList.size() > 0 || idList.size() > 0) {
            for (int i = 0; i < rsCategorya.size(); i++) {
                RsResourceCategory r1=rsCategorya.get(i);
                TreeResult treeVO = new TreeResult();
                if (pidList.contains(r1.getId())) {
                    treeVO.setId(r1.getId());
                    treeVO.setPid(r1.getPid());
                    pidList1.add(r1.getPid());
                    treeVO.setText(r1.getName());
                    treeVO.setType("1");
                    treeVOs.add(treeVO);
                    rsCategorya.remove(r1);
                    i--;
                }
                else if (idList.contains(r1.getPid())) {
                    treeVO.setId(r1.getId());
                    treeVO.setPid(r1.getPid());
                    idList1.add(r1.getId());
                    treeVO.setText(r1.getName());
                    treeVO.setType("1");
                    treeVOs.add(treeVO);
                    rsCategorya.remove(r1);
                    i--;
                }

            }
            pidList.clear();
            idList.clear();
            pidList.addAll(pidList1);
            idList.addAll(idList1);
            pidList1.clear();
            idList1.clear();
        }

            return treeVOs;
    }

  
    public List<TreeResult> resourceCategoryTreeList(String name) throws Exception {
        List<TreeResult> treeVOs = new ArrayList<TreeResult>();
        List<RsResourceCategory> rsCategorya = rsResourceCategoryDao.getAllRsResourceCategory();
        List<String > pidList=new ArrayList<>();
        List<String > pidList1=new ArrayList<>();
        List<String > idList=new ArrayList<>();
        List<String > idList1=new ArrayList<>();
        if(name!=null&&name.length()>0) {
            for (int i=0;i<rsCategorya.size();i++) {
                RsResourceCategory  r=rsCategorya.get(i);
                TreeResult treeVO = new TreeResult();
                if(r.getName().contains(name)) {
                    treeVO.setId(r.getId());
                    treeVO.setPid(r.getPid());
                    pidList.add(r.getPid());
                    idList.add(r.getId());
                    treeVO.setText(r.getName());
                    treeVO.setType("1");
                    treeVO.setIcon("../develop/lib/ligerui/skins/Aqua/images/tree/folder.gif");
                    treeVOs.add(treeVO);
                    rsCategorya.remove(r);
                    i--;
                }

            }
        }
        else{
            for (RsResourceCategory r : rsCategorya) {
                TreeResult treeVO = new TreeResult();
                treeVO.setId(r.getId());
                treeVO.setPid(r.getPid());
                treeVO.setText(r.getName());
                treeVO.setType("1");
                treeVO.setIcon("../develop/lib/ligerui/skins/Aqua/images/tree/folder.gif");
                treeVOs.add(treeVO);
            }
        }


        List<RsResource> rsResources = rsResourceDao.getAllRsResource();
        if(name!=null&&name.length()>0) {
            for (int i=0;i<rsResources.size();i++) {
                RsResource r =rsResources.get(i);
                TreeResult treeVO = new TreeResult();
                if(r.getName().contains(name)) {
                    treeVO.setId(r.getId());
                    treeVO.setPid(r.getCategory());
                    pidList.add(r.getCategory());
                    idList.add(r.getId());
                    treeVO.setText(r.getName());
                    treeVO.setType("2");
                    treeVO.setIcon("../develop/lib/ligerui/skins/Aqua/images/tree/tree-leaf.gif");
                    treeVOs.add(treeVO);
                    rsResources.remove(r);
                    i--;
                }

            }
        }
        else {
            for (RsResource r : rsResources) {
                TreeResult treeVO = new TreeResult();
                treeVO.setId(r.getId());
                treeVO.setPid(r.getCategory());
                treeVO.setText(r.getName());
                treeVO.setType("2");
                treeVO.setIcon("../develop/lib/ligerui/skins/Aqua/images/tree/tree-leaf.gif");
                treeVOs.add(treeVO);
            }
        }
        while (pidList.size()>0 || idList.size()>0) {
            for (int i=0,j=0;i<rsCategorya.size()||j<rsResources.size();i++,j++) {
                RsResourceCategory r1=new RsResourceCategory();
                RsResource r=new RsResource();
                if(i<rsCategorya.size()) {
                   r1 = rsCategorya.get(i);
                }
                if(j<rsResources.size()) {
                   r = rsResources.get(j);
                }
                TreeResult treeVO = new TreeResult();
                if(pidList.contains(r.getId()) ){
                    treeVO.setId(r.getId());
                    treeVO.setPid(r.getCategory());
                    pidList1.add(r.getCategory());
                    treeVO.setText(r.getName());
                    treeVO.setType("2");
                    treeVO.setIcon("../develop/lib/ligerui/skins/Aqua/images/tree/tree-leaf.gif");
                    treeVOs.add(treeVO);
                    rsResources.remove(r);
                    j--;
                }
                else if(idList.contains(r.getCategory())){
                    treeVO.setId(r.getId());
                    treeVO.setPid(r.getCategory());
                    idList1.add(r.getId());
                    treeVO.setText(r.getName());
                    treeVO.setType("2");
                    treeVO.setIcon("../develop/lib/ligerui/skins/Aqua/images/tree/tree-leaf.gif");
                    treeVOs.add(treeVO);
                    rsResources.remove(r);
                    j--;
                }
                else if(pidList.contains(r1.getId())){

                    treeVO.setId(r1.getId());
                    treeVO.setPid(r1.getPid());
                    pidList1.add(r1.getPid());
                    treeVO.setText(r1.getName());
                    treeVO.setType("1");
                    treeVO.setIcon("../develop/lib/ligerui/skins/Aqua/images/tree/folder.gif");
                    treeVOs.add(treeVO);
                    rsCategorya.remove(r1);
                    i--;
                }
                else if( idList.contains(r1.getPid())){
                    treeVO.setId(r1.getId());
                    treeVO.setPid(r1.getPid());
                    idList1.add(r1.getId());
                    treeVO.setText(r1.getName());
                    treeVO.setType("1");
                    treeVO.setIcon("../develop/lib/ligerui/skins/Aqua/images/tree/folder.gif");
                    treeVOs.add(treeVO);
                    rsCategorya.remove(r1);
                    i--;
                }

            }
            pidList.clear();
            idList.clear();
            pidList.addAll(pidList1);
            idList.addAll(idList1);
            pidList1.clear();
            idList1.clear();
        }
        return treeVOs;
    }

  
    public DataGridResult getResourceList(Map<String, Object> conditionMap, Integer page, Integer rows) throws Exception {

        return rsResourceDao.getResourceList(conditionMap, page, rows);
    }

  
    public int getResourceListCount(Map<String, Object> conditionMap) throws Exception {
        return rsResourceDao.getResourceListCount(conditionMap);
    }

  
    public RsResourceDeatilModel getRsResourceDeatilModel(String id) throws Exception {
        RsResourceDeatilModel rsResourceDeatilModel = new RsResourceDeatilModel();
        RsResource rsResource = rsResourceDao.getResourceById(id);
        BeanUtils.copyProperties(rsResource, rsResourceDeatilModel);
        return rsResourceDeatilModel;
    }

    @Transactional
    public void
    updateRsResource(RsResource rs) throws Exception {
        RsResource rsResourceEntrty = rsResourceDao.getResourceById(rs.getId());
        rsResourceEntrty.setCategory(rs.getCategory());
        rsResourceEntrty.setServiceRate(rs.getServiceRate());
        rsResourceEntrty.setName(rs.getName());
        rsResourceEntrty.setCode(rs.getCode());
        rsResourceEntrty.setType(rs.getType());
        rsResourceEntrty.setDataSupportType(rs.getDataSupportType());
    }

    @Transactional
    public void createRsResource(RsResource rs) throws Exception {
        rsResourceDao.saveEntity(rs);
    }

    @Transactional
    public void deleteResource(String id) throws Exception {
        RsResource rs = rsResourceDao.getResourceById(id);
        String dataSetCode = rs.getDatasetCode();
        //删除资源
        rsResourceDao.deleteEntity(rs);
        //删除资源对应的数据集和数据源
        if (!StringUtils.isEmpty(dataSetCode)) {
            resourceDatasetDao.deleteEntity(resourceDatasetDao.getEntity(RsResourceDataset.class, dataSetCode));
            resourceMetadataDao.deleteMetadatasByDataSetCode(dataSetCode);
        }
    }

  
    public DataGridResult getResourceFiled(Map<String, Object> conditionMap, Integer page, Integer rows) throws Exception {
        RsResource rs = rsResourceDao.getEntity(RsResource.class, (String) conditionMap.get("resourceId"));
        conditionMap.put("datasetId", rs.getDatasetCode());
        conditionMap.put("resourceId", rs.getId());
        return rsResourceDao.getResourceFiled(conditionMap, page, rows);
    }

    /**
     * 通过网关获取资源数据
     */
  
    public String searchRomoteResourceList(String code, Map<String, String> params) throws Exception {
        params.put("code", code);
        String result = HttpClientKit.get("", params).getBody();
        JsonNode jsonobject = objectMapper.readValue(result,JsonNode.class);
        Object response_params = jsonobject.get("responseResult");
        if (response_params.equals("null")) {
            return "";
        }
        return (String) response_params;
    }

  
    public Result getDataSet(Map<String, Object> params) throws Exception {
        DataGridResult re = new DataGridResult();
        if (StringUtils.isEmpty(params.get("datasetId"))) {

            if (params.get("rsResourceImportDatasetDialogName") != null) {
                re.setDetailModelList(stdService.datasetVersionListByName(params.get("rsResourceImportDatasetDialogName").toString()));
            } else {
                if (params.get("name") != null) {
                    return resourceDatasetDao.getDataSet(params);
                } else {
                    re.setDetailModelList(stdService.datasetsAllVersionList());
                }
            }
        } else {
            RsResourceDataset rd = resourceDatasetDao.getEntity(RsResourceDataset.class, (String) params.get("datasetId"));
            List list = new ArrayList();
            String jsonStr = objectMapper.writeValueAsString(rd);
            ObjectNode jo = objectMapper.readValue(jsonStr,ObjectNode.class);
            jo.put("checked", "true");
            list.add(jo);
            re.setDetailModelList(list);
        }
        return re;
    }

    @Transactional
    public Result improtAllMetadata(RsResourceDataset dataset, String reourceId) throws Exception {
        RsResource resource = rsResourceDao.getResourceById(reourceId);
        String dataSetId = null;
        if (StringUtils.isEmpty(resource.getDatasetCode())) {
            //第一次
            dataSetId = PKUtil.getUuid();
            //更新资源
            resource.setDatasetCode(dataSetId);
            dataset.setId(dataSetId);
            resourceDatasetDao.saveEntity(dataset);
        } else {
            dataSetId = resource.getDatasetCode();
            resourceMetadataDao.deleteLogicDataSupportMetaDataByLocalDataSetId(dataSetId);
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("code", dataset.getCode());

        Map<String, Object> paramsTemp = new HashMap<String, Object>();

        paramsTemp.put("condition",objectMapper.writeValueAsString(params));

        List responseParasm = stdService.metadatasAllVersionList(params);
        String jsonlist = objectMapper.writeValueAsString(responseParasm);
        ArrayNode array = objectMapper.readValue(jsonlist, ArrayNode.class);
        if (array.size() == 0) {
            throw new Exception("该数据集没有数据元");
        }
        //保存数据集
        //保存数据元
        for (int i = 0; i < array.size(); i++) {
            JsonNode jsonObject = array.get(i);
            RsResourceMetadata rsResourceMetadata = new RsResourceMetadata();
            rsResourceMetadata.setDatasetId(dataSetId);
            rsResourceMetadata.setCode(jsonObject.get("code").asText());
            rsResourceMetadata.setDeCode(jsonObject.get("deCode").asText());
            rsResourceMetadata.setResourceId(reourceId);
            rsResourceMetadata.setName(jsonObject.get("name").asText());
            rsResourceMetadata.setType(jsonObject.get("type").asText());
            rsResourceMetadata.setFormat(jsonObject.get("format").asText());
            rsResourceMetadata.setDictId( jsonObject.get("dictId").asInt());
            rsResourceMetadata.setDefinition(jsonObject.get("definition").asText());
            rsResourceMetadata.setNullable( jsonObject.get("nullable").asInt());
            rsResourceMetadata.setColumnLength(jsonObject.get("columnLength").asText());
            rsResourceMetadata.setColumnType(jsonObject.get("columnType").asText());
            rsResourceMetadata.setColumnName(jsonObject.get("columnName").asText());
            rsResourceMetadata.setPrimaryKey( jsonObject.get("primaryKey").asInt());
            rsResourceMetadata.setDataSupportType(1);
            resourceMetadataDao.saveEntity(rsResourceMetadata);
        }

        return Result.success("导入成功");
    }

    @Transactional
    public Result deleteMetadata(String id) throws Exception {
        resourceMetadataDao.deleteEntity(resourceMetadataDao.getEntity(RsResourceMetadata.class, id));
        return Result.success("删除成功");
    }

  
    public RsResourceMetadata getRsResourceMetadata(String id) throws Exception {
        return resourceMetadataDao.getEntity(RsResourceMetadata.class, id);
    }

    @Transactional
    public Result createMetaData(RsResourceMetadata rmd) throws Exception {
        RsResourceMetadata rmdTemp = resourceMetadataDao.getMetadataByCodeAndResourceId(rmd.getCode(), rmd.getResourceId());
        if (rmdTemp != null) {
            return Result.error("字段代码已经存在");
        }
        resourceMetadataDao.saveEntity(rmd);
        return Result.success("保存成功");
    }

    @Transactional
    public Result updateMetaData(RsResourceMetadata rmd) throws Exception {
        RsResourceMetadata rmdTemp = resourceMetadataDao.getMetadataByCodeAndResourceIdWithOutId(rmd.getCode(), rmd.getResourceId(), rmd.getId());
        if (rmdTemp != null) {
            return Result.error("字段代码已经存在");
        }
        rmdTemp = resourceMetadataDao.getEntity(RsResourceMetadata.class, rmd.getId());
        rmdTemp.setColumnName(rmd.getColumnName());
        rmdTemp.setColumnType(rmd.getColumnType());
        rmdTemp.setColumnLength(rmd.getColumnLength());
        rmdTemp.setNullable(rmd.getNullable());
        rmdTemp.setCode(rmd.getCode());
        rmdTemp.setPrimaryKey(rmd.getPrimaryKey());
        rmdTemp.setDefinition(rmd.getDefinition());
        rmdTemp.setDataSupportType(rmd.getDataSupportType());
        rmdTemp.setName(rmd.getName());
        rmdTemp.setLogicDataSource(rmd.getLogicDataSource());
        return Result.success("更新成功");
    }

  
    public Result getMetaDataByDatasetId(String code, String datasetId) throws Exception {
        if (StringUtils.isEmpty(code)) {
            return new DataGridResult();
        }
        DataGridResult r = new DataGridResult();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("code", code);

        //得到所有的数据元
        List responseParasm = stdService.metadatasAllVersionList(params);
        String jsonlist = objectMapper.writeValueAsString(responseParasm);
        ArrayNode jr = objectMapper.readValue(jsonlist,ArrayNode.class);
        if (!StringUtils.isEmpty(datasetId)) {
            List<RsResourceMetadata> md = resourceMetadataDao.getMetadataByLocalDatssetId(datasetId);
            for (int i = 0; i < jr.size(); i++) {
                for (int j = 0; j < md.size(); j++) {
                    if (jr.get("code").asText().equals(md.get(j).getCode())) {
                        ((ObjectNode) jr.get(i)).put("checked", "true");
                    }
                }
            }
        }
//        r.setDetailModelList(jr);
        return r;
    }

    @Transactional
    public Result improtSameMetadata(String reourceId, String metaData, String dataset, String datasetId) throws Exception {
        RsResource resource = rsResourceDao.getResourceById(reourceId);
        if (StringUtils.isEmpty(datasetId)) {
            //第一次导入
            String datasetID = PKUtil.getUuid();//得到ID
            RsResourceDataset rsResourceDataset = new RsResourceDataset();

            org.apache.commons.beanutils.BeanUtils.populate(rsResourceDataset, objectMapper.readValue(dataset, Map.class));
            rsResourceDataset.setId(datasetID);
            resourceDatasetDao.saveEntity(rsResourceDataset);
            ArrayNode array = objectMapper.readValue(metaData,ArrayNode.class);
            if (array.size() == 0) {
                throw new Exception("该数据集没有数据元");
            }
            for (int i = 0; i < array.size(); i++) {
                JsonNode jsonObject = array.get(i);
                RsResourceMetadata rsResourceMetadata = new RsResourceMetadata();
                org.apache.commons.beanutils.BeanUtils.populate(rsResourceMetadata, objectMapper.readValue(jsonObject.toString(),Map.class));
                rsResourceMetadata.setDataSupportType(1);
                rsResourceMetadata.setDatasetId(datasetID);
                rsResourceMetadata.setResourceId(reourceId);
                resourceMetadataDao.saveEntity(rsResourceMetadata);
            }
            resource.setDatasetCode(datasetID);
        } else {
            //修改
            resourceMetadataDao.deleteLogicDataSupportMetaDataByLocalDataSetId(datasetId);

            ArrayNode array = objectMapper.readValue(metaData, ArrayNode.class);
            for (int i = 0; i < array.size(); i++) {
                JsonNode jsonObject = array.get(i);
                RsResourceMetadata rsResourceMetadata = new RsResourceMetadata();
                org.apache.commons.beanutils.BeanUtils.populate(rsResourceMetadata, objectMapper.readValue(jsonObject.toString(),Map.class));
                rsResourceMetadata.setDataSupportType(1);
                rsResourceMetadata.setResourceId(reourceId);
                rsResourceMetadata.setDatasetId(resource.getDatasetCode());
                resourceMetadataDao.saveEntity(rsResourceMetadata);
            }
        }
        return Result.success("导入成功");
    }

  
    public RsResourceDataset getLocalDataSetById(String datasetId) throws Exception {
        return resourceDatasetDao.getEntity(RsResourceDataset.class, datasetId);
    }

  
    public Result getMetadataByLocalDatssetId(String datasetId) throws Exception {
        ActionResult ar = new ActionResult();
        ar.setData(resourceMetadataDao.getMetadataByLocalDatssetId(datasetId));
        return ar;
    }

  
    public Result getResourceAuthorize(String resourceId, String appId) throws Exception {
        DataGridResult dr = new DataGridResult();
        //查找该资源所对应的数据元
        RsResource rsResource = rsResourceDao.getResourceById(resourceId);
        List<RsResourceMetadata> metadatas = resourceMetadataDao.getMetadataByResourceId(rsResource.getId());
        //得到所有的细表
        RsAppResource rsAppResource = appResourceDao.getAppResourceByResourceIdAndAppId(resourceId, appId);
        List<RsAppResourceDetail> rsAppResourceDetails = rsAppResourceDetailDao.getAppResourceDetailByAppResouceId(rsAppResource.getId());

        List<ResourceAuthorizeDGModel> rdg = new ArrayList<ResourceAuthorizeDGModel>();
        if (rsAppResourceDetails.size() == 0) {
            for (int i = 0; i < metadatas.size(); i++) {
                ResourceAuthorizeDGModel resourceAuthorizeDGModel = new ResourceAuthorizeDGModel();
                resourceAuthorizeDGModel.setMetaDataId(metadatas.get(i).getId());
                resourceAuthorizeDGModel.setMetaDataName(metadatas.get(i).getName());
                rdg.add(resourceAuthorizeDGModel);
            }
        } else {
            for (int i = 0; i < metadatas.size(); i++) {
                for (int j = 0; j < rsAppResourceDetails.size(); j++) {
                    if (metadatas.get(i).getId().equals(rsAppResourceDetails.get(j).getMetadataId())) {
                        //允许的
                        ResourceAuthorizeDGModel resourceAuthorizeDGModel = new ResourceAuthorizeDGModel();
                        resourceAuthorizeDGModel.setChecked("true");
                        resourceAuthorizeDGModel.setAppResourceDeatilId(rsAppResourceDetails.get(j).getId());
                        resourceAuthorizeDGModel.setMetaDataId(metadatas.get(i).getId());
                        resourceAuthorizeDGModel.setMetaDataName(metadatas.get(i).getName());
                        if (!StringUtils.isEmpty(rsAppResourceDetails.get(j).getDimensionId())) {
                            RsDimension rd = resourceDimensionDao.getEntity(RsDimension.class, rsAppResourceDetails.get(j).getDimensionId());
                            resourceAuthorizeDGModel.setDimensionMessage(rd.getName() + rsAppResourceDetails.get(j).getDimensionValue());
                        }
                        rdg.add(resourceAuthorizeDGModel);
                        break;
                    } else {
                        if (j == rsAppResourceDetails.size() - 1) {
                            ResourceAuthorizeDGModel resourceAuthorizeDGModel = new ResourceAuthorizeDGModel();
                            resourceAuthorizeDGModel.setMetaDataId(metadatas.get(i).getId());
                            resourceAuthorizeDGModel.setMetaDataName(metadatas.get(i).getName());
                            rdg.add(resourceAuthorizeDGModel);
                        }
                    }
                }
            }
        }
        dr.setDetailModelList(rdg);
        return dr;
    }

  
    public Result getMetaData(Map<String, Object> params) throws Exception {
        DataGridResult re = new DataGridResult();
        RsResourceMetadata rd = resourceMetadataDao.getEntity(RsResourceMetadata.class, (String) params.get("id"));
        List rslist = new ArrayList();
        rslist.add(rd);
        re.setDetailModelList(rslist);
        return re;
    }

  
    public Result getResourceApp(String resourceid) throws Exception {
        ActionResult returnData = new ActionResult();
        Map<String, Object> rsMap = new HashMap<String, Object>();
        List<SystemApp> selectApps = new ArrayList<SystemApp>();//已经选中
        List<SystemApp> noSelectApps = new ArrayList<SystemApp>();//未选中

        List<SystemApp> allApps = appDao.getAllApplist();
        List<RsAppResource> selectApp = appResourceDao.getAppResourceByResourceId(resourceid);
        if (selectApp != null && selectApp.size() != 0) {
            for (int i = 0; i < allApps.size(); i++) {
                for (int j = 0; j < selectApp.size(); j++) {
                    if (allApps.get(i).getId().equals(selectApp.get(j).getAppId())) {
                        selectApps.add(allApps.get(i));
                        break;
                    }
                    if (j == selectApp.size() - 1) {
                        noSelectApps.add(allApps.get(i));
                    }
                }
            }
            rsMap.put("noSelect", noSelectApps);
            rsMap.put("select", selectApps);
        } else {
            rsMap.put("noSelect", allApps);
            rsMap.put("select", null);
        }
        returnData.setData(rsMap);
        return returnData;
    }

    @Transactional
    public Result updateResourceApp(String ids, String resourceId) throws Exception {
        // appResourceDao.deleteByResourceId(resourceId);
        List<RsAppResource> rs = appResourceDao.getAppResourceByResourceId(resourceId);
        List<RsAppResource> deleteList = new ArrayList<RsAppResource>();
        List<RsAppResource> newList = new ArrayList<RsAppResource>();
        String[] appResourceIds = ids.split(",");
        //找出需要新增的
        for (String appResourceId : appResourceIds) {
            if (rs.size() != 0) {
                for (int i = 0; i < rs.size(); i++) {
                    if (rs.get(i).getAppId().equals(appResourceId)) {
                        break;
                    }
                    if (i == (rs.size() - 1)) {
                        //添加主表
                        RsAppResource rsAppResource = new RsAppResource();
                        rsAppResource.setAppId(appResourceId);
                        rsAppResource.setResourceId(resourceId);
                        newList.add(rsAppResource);
                    }
                }
            } else {
                //第一次直接新增
                RsAppResource rsAppResource = new RsAppResource();
                rsAppResource.setAppId(appResourceId);
                rsAppResource.setResourceId(resourceId);
                newList.add(rsAppResource);
            }
        }
        //找出需要删除的
        //遍历原有的
        for (int i = 0; i < rs.size(); i++) {
            //遍历现在的
            for (int j = 0; j < appResourceIds.length; j++) {
                if (rs.get(i).getAppId().equals(appResourceIds[j])) {
                    break;
                }
                if (appResourceIds.length - 1 == j) {
                    deleteList.add(rs.get(i));
                }
            }
        }
        appResourceDao.deleteEntityList(deleteList);
        appResourceDao.saveEntityList(newList);

        return Result.success("更新成功");
    }

  
    public Result getResourceAppList(String resourceId) throws Exception {
        DataGridResult dgr = new DataGridResult();
        List<RsAppResource> rars = appResourceDao.getAppResourceByResourceId(resourceId);
        List modelList = new ArrayList();
        for (RsAppResource rar : rars) {
            modelList.add(appDao.getEntity(SystemApp.class, rar.getAppId()));
        }
        dgr.setDetailModelList(modelList);
        return dgr;
    }

    @Transactional
    public Result changeAppResource(String flag, String appId, String ids, String resourceId) throws Exception {
        RsAppResource rar = appResourceDao.getAppResourceByResourceIdAndAppId(resourceId, appId);
        switch (flag) {
            //全部禁止
            case "1": {
                rsAppResourceDetailDao.deleteByAppResourceId(rar.getId());
                break;
            }
            //全部允许
            case "2": {
                List<RsResourceMetadata> rrmd = resourceMetadataDao.getMetadataByResourceId(resourceId);
                rsAppResourceDetailDao.deleteByAppResourceId(rar.getId());
                for (RsResourceMetadata rRsResourceMetadata : rrmd) {
                    RsAppResourceDetail appResourceDetail = new RsAppResourceDetail();
                    appResourceDetail.setAppResouceId(rar.getId());
                    appResourceDetail.setMetadataId(rRsResourceMetadata.getId());
                    rsAppResourceDetailDao.saveEntity(appResourceDetail);
                }
                break;
            }
            //选中禁止
            case "3": {
                String[] idArray = ids.split(",");
                for (String id : idArray) {
                    rsAppResourceDetailDao.deleteEntity(rsAppResourceDetailDao.getEntity(RsAppResourceDetail.class, id));
                }

                break;
            }
            //选中允许
            case "4": {
                String[] idArray = ids.split(",");
                for (String id : idArray) {
                    RsResourceMetadata rrmd = resourceMetadataDao.getEntity(RsResourceMetadata.class, id);
                    RsAppResourceDetail appResourceDetail = new RsAppResourceDetail();
                    appResourceDetail.setAppResouceId(rar.getId());
                    appResourceDetail.setMetadataId(rrmd.getId());
                    rsAppResourceDetailDao.saveEntity(appResourceDetail);
                }
                break;
            }
        }
        return Result.success("修改成功");
    }

  
    public List<RsResourceDimensionModel> getDimensionByResourceId(String resourceId) throws Exception {
        return resourceDimensionDao.getDimensionByResourceId(resourceId);
    }

  
    public RsAppResourceDetail getAppResourceDetailId(String id) throws Exception {
        return rsAppResourceDetailDao.getEntity(RsAppResourceDetail.class, id);
    }

    @Transactional
    public Result saveResourceDimension(RsAppResourceDetail appResourceDetail) throws Exception {
        RsAppResourceDetail rsAppResourceDetail = rsAppResourceDetailDao.getEntity(RsAppResourceDetail.class, appResourceDetail.getId());
        rsAppResourceDetail.setDimensionValue(appResourceDetail.getDimensionValue());
        rsAppResourceDetail.setDimensionId(appResourceDetail.getDimensionId());
        return Result.success("保存成功");
    }

  
    public List<RsResourceMetadata> getResourceMetadataListColumn(String code) throws Exception {
        return resourceMetadataDao.getMetadataByResourceId(code);
    }

}
