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.ccui.core.common.utils.UUIDUtils;
import cn.com.capcloud.core.cache.KHCRedisCache;
import cn.com.capcloud.core.cache.BaseConfigStaticCache;
import cn.com.capcloud.core.noentitydb.BaseService;
import cn.com.capcloud.core.noentitydb.DefaultAction;
import cn.com.capcloud.core.system.user.UserService;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import org.springframework.stereotype.Component;

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

@Component
public class DataBaseConfigAction extends DefaultAction {
    @Autowired
    private BaseService baseService;
    @Autowired
    private UserService userService;
    @Autowired
    private ApiService apiService;
    @Autowired
    private KHCRedisCache khcRedisCache;
    //PDF初始化的模板
    private static final String SYSTEM_SETTINGS_DS_FORM_PDF_TEMPLATE_INIT="system.settings.ds.form.pdf.template.init";
    //PDF需要展示的字段
    private static final String SYSTEM_SETTINGS_DS_FORM_PDF_SHOWTYPE="system.settings.ds.form.pdf.show_type";
    private static DataBaseConfigAction action;
    @PostConstruct
    public void init(){
        action=this;
        action.baseService=this.baseService;
        action.userService=this.userService;
        action.apiService =this.apiService;
        action.khcRedisCache =this.khcRedisCache;
    }

    public JackJSONArray baseConfigSaveAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray maps) {
        BaseConfigStaticCache.init(action.khcRedisCache);
        return super.saveAfter(jsonStr, retJson, request, maps);
    }

    @Override
    public Map<String, Object> findOneAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request, Map<String, Object> map) {
        String pkId=action.apiService.getJsonValueByKey(jsonStr,retJson,"pkId");
        if(SYSTEM_SETTINGS_DS_FORM_PDF_TEMPLATE_INIT.equals(pkId)){
            String uuid=action.apiService.getJsonValueByKey(jsonStr,retJson,"uuid");
            if("-1".equals(uuid)){
                return map;
            }else{
                List<Map<String, Object>> listFormInfo= action.khcRedisCache.getFormInfoByUuid(uuid);
                return updatePdfTemplate(map,listFormInfo);
            }
        }
        return map;
    }
    /**
     * 模板动态生成
     */
    public Map<String, Object> updatePdfTemplate(Map<String, Object> map,List<Map<String, Object>> listFormInfo){
        List<String> showTypeArray= Arrays.asList(String.valueOf(BaseConfigStaticCache.get(SYSTEM_SETTINGS_DS_FORM_PDF_SHOWTYPE)).split(","));
        String html="";
        for (int i = 0; i < listFormInfo.size(); i++) {
            if (showTypeArray.contains(String.valueOf(listFormInfo.get(i).get("show_type")))) {
                html+="                    <tr>\n";
                html+="                        <td class=\"table_td_css\">"+listFormInfo.get(i).get("label_name")+"</td>\n";
                html+="                        <td>\\$\\{"+listFormInfo.get(i).get("name")+"\\}</td>\n";
                html+="                    </tr>\n";
            }
        }
        String pdfTemplateHTML=String.valueOf(map.get("base_value"));
        pdfTemplateHTML=pdfTemplateHTML.replaceAll("&nbsp;"," ");
        pdfTemplateHTML=pdfTemplateHTML.replaceAll("\\$\\{autoTemplate\\}",html);
        map.put("base_value",pdfTemplateHTML);
        return map;
    }

    public Map<String, Object> dbTableTemplateFindOneAfterExportWord(String jsonStr, JackJSONObject retJson, HttpServletRequest request, Map<String, Object> map) {
        JackJSONObject valueJson= JackJSONObject.fromObject(map.get("base_value"));
        String exportServiceTable=String.valueOf(valueJson.get("export_service_table"));
        String exportSystemTable=String.valueOf(valueJson.get("export_system_table"));
        if(exportServiceTable.equals("N")&&exportSystemTable.equals("N")){
            return map;
        }
        String querySql="SELECT * FROM tbl_data_source WHERE STATUS=0 ";
        if(exportServiceTable.equals("Y")&&exportSystemTable.equals("N")){
            querySql+=" and type='service'";
        }
        if(exportServiceTable.equals("N")&&exportSystemTable.equals("Y")){
            querySql+=" and type='system'";
        }
        querySql+=" order by type asc";
        List<Map<String, Object>> tableList=this.getJdbcTemplate().queryForList(querySql);
        List<Map<String, Object>> exportTableList=new ArrayList<>();
        for (int i = 0; i < tableList.size(); i++) {
            Map<String, Object> tableMap=tableList.get(i);
            String dsTableName=String.valueOf(tableMap.get("ds_table_name"));
            List<Map<String, Object>> fieldList= null;
            try {
                fieldList = this.getJdbcTemplate().queryForList("SHOW FULL COLUMNS FROM "+dsTableName);
            } catch (Exception e) {
                //e.printStackTrace();
                System.out.println("导出表结构设计说明时未找到 "+dsTableName+" 物理表");
                continue;
            }
            for (int j = 0; j < fieldList.size(); j++) {
                Map<String,Object> fieldMap=fieldList.get(j);
                String fieldNull=String.valueOf(fieldMap.get("Null"));
                String fieldPkKey=String.valueOf(fieldMap.get("Key"));
                String fieldDefault=String.valueOf(fieldMap.get("Default"));
                fieldMap.put("field_index",(j+1));
                if(fieldNull.equals("NO")){
                    fieldMap.put("Null","是");
                }else{
                    fieldMap.put("Null","否");
                }
                if(fieldPkKey.equals("PRI")){
                    fieldMap.put("Key","是");
                }else{
                    fieldMap.put("Key","否");
                }
                if(fieldDefault.equals("null")){
                    fieldMap.put("Default","");
                }else{
                    fieldMap.put("Default",fieldDefault);
                }
            }
            tableMap.put("field_list",fieldList);
            tableMap.put("table_index",(exportTableList.size()+1));
            exportTableList.add(tableMap);
        }
        map.put("table_list",exportTableList);
        return map;
    }

    public Map<String, Object> apiTemplateFindOneAfterExportWord(String jsonStr, JackJSONObject retJson, HttpServletRequest request, Map<String, Object> map) {
        JackJSONObject valueJson=JackJSONObject.fromObject(map.get("base_value"));
        String exportServiceTable=String.valueOf(valueJson.get("export_service_api"));
        String exportSystemTable=String.valueOf(valueJson.get("export_system_api"));
        if(exportServiceTable.equals("N")&&exportSystemTable.equals("N")){
            return map;
        }
        String querySql="SELECT dq.*,ds.ds_code,ds.TYPE FROM tbl_data_query dq JOIN (SELECT ds_code,TYPE,UUID FROM tbl_data_source WHERE STATUS=0 ";
        if(exportServiceTable.equals("Y")&&exportSystemTable.equals("N")){
            querySql+=" and type='service'";
        }
        if(exportServiceTable.equals("N")&&exportSystemTable.equals("Y")){
            querySql+=" and type='system'";
        }
        querySql+=" ) ds ON dq.page_parent_uuid=ds.uuid WHERE dq.status=0 ";
        querySql+=" order by type asc";
        List<Map<String, Object>> queryApiList=this.getJdbcTemplate().queryForList(querySql);
        List<Map<String, Object>> exportQueryApiList=new ArrayList<>();
        for (int i = 0; i < queryApiList.size(); i++) {
            Map<String, Object> queryMap=queryApiList.get(i);
            String queryUUID=String.valueOf(queryMap.get("uuid"));
            List<Map<String, Object>> queryData = this.getJdbcTemplate().queryForList("select * from tbl_data_query_info where status=0 and page_parent_uuid='"+queryUUID+"'");
            queryMap.put("queryData",queryData);
            List<Map<String, Object>> querySearchData = this.getJdbcTemplate().queryForList("select * from tbl_data_query_info where status=0 and is_query='Y' and page_parent_uuid='"+queryUUID+"'");
            queryMap.put("querySearchData",querySearchData);
            queryMap.put("table_index",(exportQueryApiList.size()+1));
            String reqJsonString= "{\n" +
                    "  \"dsCode\": \""+queryMap.get("ds_code")+"\",\n" +
                    "  \"queryCode\": \""+queryMap.get("query_code")+"\",\n" +
                    "  \"queryParam\": {\n" ;
            for (int j = 0; j < querySearchData.size(); j++) {
                String key=String.valueOf(querySearchData.get(j).get("name"));
                reqJsonString+="    \""+key+"\": \"\",\n";
            }
            reqJsonString+=
                    "    \"base_type\": \"\",\n" +
                            "    \"page\": 0,\n" +
                            "    \"pageSize\": 50\n" +
                            "  }\n" +
                            "}";
            String resJsonString = "{\n" +
                    "    \"uuid\": \""+ UUIDUtils.randomUuidWithoutHyphen() +"\",\n" +
                    "    \"message\": \"成功\",\n" +
                    "    \"status\": \"ok\",\n" +
                    "    \"data\": {\n" +
                    "        \"number\": 0,\n" +
                    "        \"numberOfElements\": 0,\n" +
                    "        \"size\": 10,\n" +
                    "        \"totalPages\": 0,\n" +
                    "        \"selectContent\": [],\n" +
                    "        \"content\": [],\n" +
                    "        \"totalElements\": 0\n" +
                    "    }\n" +
                    "}";
            queryMap.put("request_json_demo",reqJsonString);//请求json示例
            queryMap.put("response_json_demo",resJsonString);//响应json示例
            exportQueryApiList.add(queryMap);
        }
        map.put("dsApiList",exportQueryApiList);
        /**
         * 表格行循环
         * LoopRowTableRenderPolicy 是一个特定场景的插件，根据集合数据循环表格行。
         */
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        //将插件应用到这两个标签。
        Configure config = Configure.builder()
                .bind("querySearchData", policy).bind("queryData", policy).build();
        map.put("dsApiList",exportQueryApiList);
        map.put("poiConfigure",config);
        return map;
    }
}

