package cn.com.capcloud.api.action.myself.system.data;

import cn.com.capcloud.api.action.service.ApiService;
import cn.com.capcloud.ccui.core.common.json.JackJSONArray;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.core.noentitydb.BaseService;
import cn.com.capcloud.core.noentitydb.DefaultAction;
import cn.com.capcloud.core.system.user.UserService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DataPageAction extends DefaultAction {
    @Autowired
    private BaseService baseService;
    @Autowired
    private UserService userService;
    @Autowired
    private ApiService apiService;
    private static DataPageAction action;
    @PostConstruct
    public void init(){
        action=this;
        action.baseService=this.baseService;
        action.userService=this.userService;
        action.apiService =this.apiService;
    }
    public Map<String,Object> getAllRoleByPageId(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        JackJSONObject json= JackJSONObject.fromObject(jsonStr);
        String pageId= String.valueOf(json.get("pageId"));
        String sql="select * from tbl_data_page_role where page_id="+pageId;
        List<Map<String, Object>> list= this.getJdbcTemplate().queryForList(sql);
        String roleStr="";
        for (int i = 0; i < list.size(); i++) {
            roleStr+=list.get(i).get("role_id")+",";
        }
        if(roleStr!=""){
            roleStr=roleStr.substring(0,roleStr.length()-1);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("message","查询成功");
        map.put("data",roleStr);
        return map;
    }

    public JackJSONArray saveBeforePageRole(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array){
        JackJSONObject json =array.getJackJSONObject(0);
        String pageId=String.valueOf(json.get("page_id"));
        String roles=String.valueOf(json.get("role_id"));
        action.getJdbcTemplate().execute("delete from tbl_data_page_role where page_id="+pageId);
        if(!roles.equals("")){
            String[] arr = roles.split(",");
            for (int i = 0; i < arr.length; i++) {
                if(!arr[i].equals("")){
                    Map<String,Object> map=new HashMap<>();
                    map.put("role_id",arr[i]);
                    map.put("page_id",pageId);
                    action.baseService.save("tbl_data_page_role",map);
                }
            }
        }
        retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("ok")));
        return new JackJSONArray();
    }
}

