package cn.com.capcloud.api.action.service;

import cn.com.capcloud.api.action.service.util.DictUtil;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.core.cache.KHCRedisCache;
import cn.com.capcloud.core.noentitydb.BaseService;
import cn.com.capcloud.core.system.user.User;
import cn.com.capcloud.core.system.user.UserService;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

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

@Service
public class DictService {

    //PDF默认模板
    private static final String SYSTEM_SETTINGS_DS_FORM_PDF_TEMPLATE="system.settings.ds.form.pdf.template";
    @Autowired
    private ApiService apiService;
    @Autowired
    private UserService userService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BaseService baseService;
    @Autowired
    private KHCRedisCache khcRedisCache;

    /**
     * 查询内部字典
     */
    public List<Map<String, Object>> getDictInfoByDictCodeToList(String dictCode) {
        return DictUtil.getDictInfoByDictCodeToList(dictCode,jdbcTemplate);
    }
    public Map<String, Object> getDictInfoByDictCodeToMap(String dictCode,Boolean isReversal) {
        return DictUtil.getDictInfoByDictCodeToMap(dictCode,isReversal,jdbcTemplate);
    }
    /**
     * 查询外部字典
     */
    public Map<String, Object> getOutDictInfoByDictCodeToMap(String dictCode,Boolean isReversal) {
        return DictUtil.getOutDictInfoByDictCodeToMap(dictCode,isReversal,jdbcTemplate);
    }
    /**
     * 根据前缀来判断查询内部字典还是外部字典
     */
    public Map<String, Object> getAllDictInfoByCode(String code, User user) {
        Map<String, Object> retMap=new HashMap<>();
        retMap.put("code", code);
        String userId="";
        if(user!=null){
            userId=String.valueOf(user.getId());
        }
        if(code.indexOf("tree_")==0){
            retMap.put("type", "tree");
            retMap.put("data", khcRedisCache.getTreeInfoByTreeCodeToList(code,"",userId,user));
        }else if(code.indexOf("o_")==0){//外部字典不放缓存。
            retMap.put("type", "default");
            retMap.put("data", DictUtil.getOutDictInfoByDictCodeToList(code,jdbcTemplate,user));
        }else if(code.indexOf("tp_")==0){//第三方字典不放缓存。
            retMap.put("type", "default");
            retMap.put("data", DictUtil.getTPDictInfoByDictCodeToList(code,jdbcTemplate));
        }else{
            retMap.put("type", "default");
            retMap.put("data", khcRedisCache.getDictInfoByDictCodeToList(code));
        }
        return retMap;
    }
    public Map<String, Object> getAllDictInfoByCode(String code) {
        return getAllDictInfoByCode(code,null);
    }

    public Map<String, Object> getAllOutDict(String jsonStr,JackJSONObject retJson, HttpServletRequest request){
        User user=userService.getUser(request);
        Map<String, Object> retMap=new HashMap<>();
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        String oDictCode=String.valueOf(jsonObject.get("oDictCode"));
        String queryDictInfo="SELECT * FROM tbl_data_dict_out WHERE o_dict_code='"+oDictCode+"'";
        List<Map<String, Object>> treeList=jdbcTemplate.queryForList(queryDictInfo);
        if(treeList.size()==0){
            retJson.putAll(JackJSONObject.fromObject(apiService.getReturnDataByCode("7040")));
            retJson.put("message",retJson.get("message")+"oDictCode："+oDictCode);
            return new HashMap<>();
        }
        retMap.put("oDictCode",oDictCode);
        List<Map<String, Object>> treeData=jdbcTemplate.queryForList(DictUtil.getOutDictWhereSql(oDictCode,jdbcTemplate,user));
        retMap.put("oDictData",treeData);
        return retMap;
    }

    public Map<String, Object> getAllTree(String jsonStr,JackJSONObject retJson, HttpServletRequest request){
        Map<String, Object> retMap=new HashMap<>();
        JackJSONObject queryParamJson=JackJSONObject.fromObject(jsonStr).getJackJSONObject("queryParam");
        try {
            queryParamJson.size();
        } catch (Exception e) {
            return new HashMap<>();
        }
        String treeCode=String.valueOf(JackJSONObject.fromObject(jsonStr).get("treeCode"));
        String queryTreeInfo="SELECT * FROM tbl_data_tree WHERE tree_code='"+treeCode+"'";
        List<Map<String, Object>> treeList=jdbcTemplate.queryForList(queryTreeInfo);
        if(treeList.size()==0){
            retJson.putAll(JackJSONObject.fromObject(apiService.getReturnDataByCode("7040")));
            retJson.put("message",retJson.get("message")+"treeCode："+treeCode);
            return new HashMap<>();
        }
        khcRedisCache.deleteAllTree();
        String pId=String.valueOf(queryParamJson.get("pId"));
        User user=userService.getUser(request);
        List<Map<String, Object>> treeData= khcRedisCache.getTreeInfoByTreeCodeToList(treeCode,pId,String.valueOf(user.getId()),user);
        retMap.put("treeData",treeData);
        return retMap;
    }

    public void refreshChildLevel(Map<String,Object> map){
        String pIdField=String.valueOf(map.get("pIdField"));
        String pId=String.valueOf(map.get(pIdField));
        String idField=String.valueOf(map.get("idField"));
        String tableName=String.valueOf(map.get("tableName"));
        String levelField=String.valueOf(map.get("levelField"));
        Integer level=Integer.parseInt(String.valueOf(map.get(levelField)));
        String sql="SELECT * FROM "+tableName+" WHERE "+pIdField+"='"+pId+"'";
        List<Map<String, Object>> list=jdbcTemplate.queryForList(sql);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).put(levelField,level);
            baseService.update(tableName,list.get(i));
            map.put(pIdField,String.valueOf(list.get(i).get(idField)));
            map.put(levelField,level+1);
            refreshChildLevel(map);
        }
    }

}

