package com.scpyun.platform.jilinsscgsdp.utils;

import com.alibaba.fastjson.JSONObject;
import com.scpyun.base.bean.User;
import com.scpyun.base.db.service.CommonService;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class DataScopeUtil {
    public static final String TYPE_RUCS = "2"; // 刑满释放
    public static final String TYPE_PSMD = "3"; // 严重精神障碍患者
    public static final String TYPE_KM = "6"; // 重点未成年人

    private static CommonService commonService;
    private static String namespace = "com.scpyun.platform.standard.jilinsscgsdp.KeyPersonPower.";


    /**
     * 获取当前登录人机构类型
     * @param _user
     * @return
     */
    public static Map<String, Object> getOfficeType(Object _user) {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> result = new HashMap<>();
        JSONObject user = JSONObject.parseObject(JSONObject.toJSONString(_user));
        String company_id = user.getString("company_id");
        String companyName = user.getString("company_name");
        if (company_id.length() == 12) {
            result.put("office_value", "-9999");
            result.put("office_label", "综治中心");
        } else {
            params.put("type", "sys_type_office");
            List<Map<String, Object>> officeTypeList = commonService.findList(namespace + "selectDicByType", params);
            officeTypeList = officeTypeList.stream().filter(c->companyName.contains(c.get("label").toString())).collect(Collectors.toList());
            if (officeTypeList.size() ==0) {
                result.put("office_value", "-9998");
                result.put("office_label", "未获取到类型");
            } else {
                result.put("office_value", officeTypeList.get(0).get("value"));
                result.put("office_label", officeTypeList.get(0).get("label"));
            }
        }

        return result;
    }

    /**
     * 获取按钮权限
     * @param _user
     * @return  有权限即返回按钮  具体查看 dic type == "page_button" ，返回 key：按钮标识   value：按钮描述
     * 目前的按钮有：
     * rucs_rating：刑满释放人员 - 评分按钮
     * psmd_rating：严重精神障碍患者 - 评分按钮
     * km_rating：重点未成年人员 - 评分按钮
     * rucs_visit：刑满释放人员 - 回访按钮
     * psmd_visit：严重精神障碍患者 - 回访按钮
     * km_visit：重点未成年人员 - 回访按钮
     * rucs_view_rating：刑满释放人员 - 评分查询按钮
     * psmd_view_rating：严重精神障碍患者 - 评分查询按钮
     * km_view_rating：重点未成年人员 - 评分查询按钮
     */
    public static Map<String, String> getButtonPower(Object _user) {
        Map<String, String> resultMap = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        JSONObject user = JSONObject.parseObject(JSONObject.toJSONString(_user));
        String companyName = user.getString("company_name");
        params.put("conpanyName", companyName);

        //增加过滤控制，如果没查到数据，可以按原逻辑显示，如果查到数据，判断并根据当前的数据进行授权
        boolean havePower = true;
        Map<String, Object> numObj = commonService.getObject(namespace + "selectPowerOfficeNumber", params);
        try {
            int num = Integer.parseInt(String.valueOf(numObj.get("num")));
            if (num > 0) {
                Map<String, Object> _map = new HashMap<>();
                _map.put("id", user.getString("company_id"));
                List<Map<String, Object>> tlist = commonService.findList(namespace + "selectPowerOffice", _map);
                if(tlist.size() == 0){
                    havePower = false;
                }
            }
        }catch (Exception e){

        }

        if(!havePower){
            return resultMap;
        }

        List<Map<String, Object>> resultList = commonService.findList(namespace + "selectPower", params);
        for(Map<String, Object> result : resultList) {
            String[] officeNameArray = result.get("rating_visit_office").toString().split(",");
            for(String officeName : officeNameArray) {
                if(companyName.contains(officeName) && officeName.length() > 0) {
                    resultMap.put(result.get("rating_dict_value").toString(), result.get("rating_dict_label").toString());
                    break;
                }
            }
        }

        //默认综治中心可以进行评分，社区不能评分
        Map<String, String> _map = new HashMap<>();
        _map.put("id", user.getString("company_id"));
        Map retMap = commonService.getObject("com.scpyun.platform.standard.jilinsscgsdp.newgridlevel.getCompanyInfoById", _map);
        boolean isCenter = retMap.get("fax") == null;
        if(isCenter) {
            if("6".equals(user.getString("company_grade"))) {
                resultMap.put("rucs_view_rating", "刑满释放人员 - 查询评分");
                resultMap.put("psmd_view_rating", "严重精神障碍患者 - 查询评分");
                resultMap.put("km_view_rating", "重点未成年人员 - 查询评分");
            }else{
                params.put("type", "page_button");
                List<Map<String, Object>> all = commonService.findList(namespace + "selectDicByType", params);
                for(Map<String, Object> key: all ) {
                    if(key.get("value").toString().indexOf("rating")!=-1) {
                        resultMap.put(key.get("value").toString(), key.get("label").toString());
                    }
                }
            }
        }

        if ("admin".equals(user.getString("no"))) {
            params.put("type", "page_button");
            List<Map<String, Object>> all = commonService.findList(namespace + "selectDicByType", params);
            for(Map<String, Object> key: all ) {
                resultMap.put(key.get("value").toString(), key.get("label").toString());
            }
        }

        return resultMap;
    }

    /**
     * 获取当前用户组织机构区域信息
     * @param _user
     * @return
     * grade: grade=0:总机构、grade=2:吉林省 对应字段 region  、grade=3:市 对应字段 city_id、grade=4:区县 对应字段 area_id、grade=5:街道 对应字段 street_id、grade=6:社区、村 对应字段 community_id
     * area_id: 区域id
     */
    public static Map<String, String> getPosition(Object _user) {
        Map<String, Object> queryMap = new HashMap<>();
        Map<String, String> resultMap = new HashMap<>();

        JSONObject user = JSONObject.parseObject(JSONObject.toJSONString(_user));
        String company_id = user.getString("company_id");
        // 机构等级(grade=0:总机构、grade=2:吉林省、grade=3:市、grade=4:区县、grade=5:街道、grade=6:社区、村)
        String company_grade = user.getString("company_grade");

        queryMap.put("id", company_id);
        //
        Map<String, Object> result = commonService.getObject(namespace + "selectOfficeById", queryMap);

        resultMap.put("grade", company_grade);
        resultMap.put("area_id", result.get("area_id") != null ? result.get("area_id").toString() : "");

        return resultMap;
    }

    /**
     * 是否是长春
     * @param _user
     * @return true:是  false：否
     */
    public static Boolean isChanChun(Object _user) {
        Map<String, Object> queryMap = new HashMap<>();
        JSONObject user = JSONObject.parseObject(JSONObject.toJSONString(_user));
        String company_id = user.getString("company_id");
        if (company_id.length() == 12 && company_id.startsWith("2201")) {
            return true;
        } else if (company_id.length() == 12){
            return false;
        } else {
            queryMap.put("id", company_id);
            Map<String, Object> result = commonService.getObject(namespace + "selectOfficeById", queryMap);
            String area_id = result.get("area_id").toString();
            if (area_id.startsWith("2201")) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 是否是长春
     * @param _user
     * @return true:是  false：否
     */
    public static Boolean isChanChun(User _user) {
        Map<String, Object> map = new HashMap<>();
        BeanWrapper beanWrapper = new BeanWrapperImpl(_user);
        for (java.beans.PropertyDescriptor pd : beanWrapper.getPropertyDescriptors()) {
            String propertyName = pd.getName();
            // 跳过class属性
            if (!"class".equals(propertyName)) {
                Object propertyValue = beanWrapper.getPropertyValue(propertyName);
                map.put(propertyName, propertyValue);
            }
        }
        if(map.get("company_id") == null) {
            return false;
        }else{
            return isChanChun(map);
        }
    }

    public static Map<String, Object> resetUser(Map<String, Object> map) {
        Object _user = map.get("_user");
        Map<String, Object> queryMap = new HashMap<>();
        JSONObject user = JSONObject.parseObject(JSONObject.toJSONString(_user));
        String company_id = user.getString("company_id");
        if (company_id.length() == 12) {
            user.put("area_id", company_id);
            map.put("_user", user);
            return map;
        }

        queryMap.put("id", company_id);
        Map<String, Object> result = commonService.getObject(namespace + "selectOfficeById", queryMap);
        String area_id = result.get("area_id").toString();
        user.put("area_id", area_id);
        map.put("_user", user);
        return map;
    }


    public static CommonService getCommonService() {
        return commonService;
    }

    @Autowired
    public void setCommonService(CommonService commonService) {
        DataScopeUtil.commonService = commonService;
    }
}
