package com.tofly.codegen.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tofly.codegen.entity.GenConfig;
import com.tofly.codegen.service.GeneratorService;
import com.tofly.codegen.util.DataSourceUtil;
import com.tofly.codegen.util.DataTypeSqlInfo;
import com.tofly.codegen.util.GenUtils;
import com.tofly.codegen.util.IOUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * @author Administrator
 * @date 2019/9/26  10:52
 */
@Service
@AllArgsConstructor
@Slf4j
public class GeneratorServiceImpl implements GeneratorService {

    private final String TABLENAME="TABLENAME";
    private final String COMMENTS="COMMENTS";
    @Override
    public Map  querytable(String tableName){
        JdbcTemplate jdbcTemplate= DataSourceUtil.getJdbcTemplate();
        Map stringObjectMap = jdbcTemplate.queryForMap(DataSourceUtil.getDataTypeSqlInfo().getTABLE_COMMENT_SQL(), tableName);
        return stringObjectMap;
    }

    @Override
    @SneakyThrows
    public List queryColumns(String tableName){
        JdbcTemplate jdbcTemplate= DataSourceUtil.getJdbcTemplate();
        DataTypeSqlInfo dataTypeSqlInfo=DataSourceUtil.getDataTypeSqlInfo();
        List<Map<String,Object>> list = jdbcTemplate.queryForList(dataTypeSqlInfo.getTABLECOLUM_COMMENT_SQL(), tableName);
        try{
            List<Map<String,Object>> list1=jdbcTemplate.queryForList(dataTypeSqlInfo.getTABLEGEN_DETAIL_QUERY_SQL(),tableName);
            if(list1!=null && list1.size()>0){
                list.forEach(m->{
//                list1.stream().anyMatch(tableDetailGen ->tableDetailGen.getColumnName().equalsIgnoreCase((String)m.get("COLUMNNAME")));
                    for(Map tableDetailGen:list1){
                        if(((String)tableDetailGen.get("COLUMN_NAME")).equalsIgnoreCase((String)m.get("COLUMNNAME"))){
                            m.put("TYPE",tableDetailGen.get("TYPE"));
                            m.put("DEFAULTVALUE",tableDetailGen.get("DEFAULT_VALUE"));
                            m.put("QUERYLIKE",tableDetailGen.get("QUERY_LIKE"));
                            m.put("CODEKEY",tableDetailGen.get("CODE_KEY"));
                            m.put("CUSTOMSQL",tableDetailGen.get("CUSTOMSQL"));
                            break;
                        }
                    }
                });
            }
        }catch (Exception e){

        }

        return list;
    }

    @Override
    public List getTables() {
        JdbcTemplate jdbcTemplate= DataSourceUtil.getJdbcTemplate();
        List<Map<String, Object>> list = jdbcTemplate.queryForList(DataSourceUtil.getDataTypeSqlInfo().getTABLE_COMMENT_ALL_SQL());
        return list;
    }

    @Override
    @SneakyThrows
    public byte[] generatorCode(GenConfig genConfig) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        //多张表
        /*Map<String,String> map=new HashMap(){
            {
                put("TF_SMPN_DEPT_X","部门信息表");
                put("TF_SMPN_MENU_X","菜单信息表");
            }
        };*/
        String tables=genConfig.getTables();
        if(!StringUtils.isEmpty(tables)){
            JSONArray jsonArray= JSON.parseArray(tables);
            jsonArray.forEach(
                    V->{
                        JSONObject jsonObject=(JSONObject)V;
                        String tableName=jsonObject.getString(TABLENAME);
                        //查询表信息
                        Map<String, String> table = querytable(tableName);
                        //查询列信息
                        List columns = queryColumns(tableName);
                        //生成代码
                        genConfig.setComments(jsonObject.getString(COMMENTS));
                        try {
                            GenUtils.generatorCode(genConfig, table, columns, zip);
                        }catch (Exception e){
                            log.info("导出错误：{}",e.getMessage());
                        }

                    }
            );
        }else{
            //        //查询表信息
            Map<String, String> table = querytable(genConfig.getTableName());
            //查询列信息
            List columns = queryColumns(genConfig.getTableName());
            //生成代码
            GenUtils.generatorCode(genConfig, table, columns, zip);
        }





//        //查询表信息
//        Map<String, String> table = querytable(genConfig.getTableName()).get(0);
//        //查询列信息
//        List<Map<String, String>> columns = queryColumns(genConfig.getTableName());
//        //生成代码
//        GenUtils.generatorCode(genConfig, table, columns, zip);
        IOUtil.close(zip);
        return outputStream.toByteArray();
    }
}
