package org.nl.system.service.generator.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.nl.common.domain.query.PageQuery;
import org.nl.common.exception.BadRequestException;
import org.nl.common.utils.FileUtil;
import org.nl.common.utils.GenUtil;
import org.nl.system.service.generator.ICodeGeneratorService;
import org.nl.system.service.generator.dao.CodeColumnConfig;
import org.nl.system.service.generator.dao.CodeGenConfig;
import org.nl.system.service.generator.dao.mapper.CodeColumnConfigMapper;
import org.nl.system.service.generator.dto.ColumnInfo;
import org.nl.system.service.generator.dto.TablesInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 列的数据信息表 服务实现类
 * </p>
 *
 * @author lyd
 * @since 2023-05-03
 */
@Service
public class CodeGeneratorServiceImpl extends ServiceImpl<CodeColumnConfigMapper, CodeColumnConfig> implements ICodeGeneratorService {

    @Autowired
    private CodeColumnConfigMapper columnConfigMapper;

    @Override
    public IPage<TablesInfo> getTables(String name, PageQuery pageQuery) {
        IPage<TablesInfo> pages = new Page<>();
        int page = pageQuery.getPage();
        int pageSize = pageQuery.getSize();
        int offset = page * pageSize;
        List<TablesInfo> tableInfos = columnConfigMapper.getTables(name, pageSize, offset);
        long num = columnConfigMapper.getTablesTotal(name);
        pages.setRecords(tableInfos);
        pages.setCurrent(page + 1);
        pages.setSize(pageSize);
        pages.setTotal(num);
        return pages;
    }

    @Override
    public IPage<CodeColumnConfig> getColumns(String tableName) {
        IPage<CodeColumnConfig> pages = new Page<>();
        // 查找行列数据表
        List<CodeColumnConfig> codeColumnConfigs = columnConfigMapper
                .selectList(new LambdaQueryWrapper<CodeColumnConfig>()
                        .eq(CodeColumnConfig::getTable_name, tableName));
        if (ObjectUtil.isEmpty(codeColumnConfigs)) {
            // 为空查找全新的数据
            codeColumnConfigs = query(tableName);
            // 保存
            this.saveBatch(codeColumnConfigs);
        }
        pages.setRecords(codeColumnConfigs);
        return pages;
    }

    @Override
    public List<CodeColumnConfig> query(String tableName) {
        List<ColumnInfo> columnConfigList = columnConfigMapper.getTablesByTableName(tableName);
        // 设置默认值
        List<CodeColumnConfig> columnInfos = columnConfigList.stream()
                .map(config -> CodeColumnConfig
                        .builder()
                        .column_id(IdUtil.getSnowflake(1,1).nextIdStr())
                        .table_name(tableName)
                        .column_name(config.getColumn_name())
                        .column_type(config.getColumn_type())
                        .key_type(config.getKey_type())
                        .extra(config.getExtra())
                        .not_null((ObjectUtil.isNotEmpty(config.getKey_type())
                                &&ObjectUtil.isNotEmpty(config.getExtra())
                                &&GenUtil.PK.equalsIgnoreCase(config.getKey_type())
                                &&GenUtil.EXTRA.equalsIgnoreCase(config.getExtra()))
                                ?false:ObjectUtil.isNotEmpty(config.getNot_null())?config.getNot_null():false)
                        .remark(ObjectUtil.isNotEmpty(config.getRemark())?config.getRemark():null)
                        .list_show(true)
                        .form_show(true)
                        .build())
                .collect(Collectors.toList());
        return columnInfos;
    }

    @Override
    public void sync(IPage<CodeColumnConfig> columnInfos, List<CodeColumnConfig> columnInfoList) {
        List<CodeColumnConfig> records = columnInfos.getRecords();
        // 第一种情况，数据库类字段改变或者新增字段
        for (CodeColumnConfig columnInfo : columnInfoList) {
            // 根据字段名称查找
            List<CodeColumnConfig> columns = records.stream().filter(c -> c.getColumn_name().equals(columnInfo.getColumn_name())).collect(Collectors.toList());
            // 如果能找到，就修改部分可能被字段
            if (CollectionUtil.isNotEmpty(columns)) {
                CodeColumnConfig column = columns.get(0);
                column.setColumn_type(columnInfo.getColumn_type());
                column.setExtra(columnInfo.getExtra());
                column.setKey_type(columnInfo.getKey_type());
                if (StrUtil.isEmpty(column.getRemark())) {
                    column.setRemark(columnInfo.getRemark());
                }
                columnConfigMapper.updateById(column);
            } else {
                // 如果找不到，则保存新字段信息
                columnConfigMapper.insert(columnInfo);
            }
        }
        // 第二种情况，数据库字段删除了
        for (CodeColumnConfig columnInfo : records) {
            // 根据字段名称查找
            List<CodeColumnConfig> columns = columnInfoList.stream().filter(c -> c.getColumn_name().equals(columnInfo.getColumn_name())).collect(Collectors.toList());
            // 如果找不到，就代表字段被删除了，则需要删除该字段
            if (CollectionUtil.isEmpty(columns)) {
                columnConfigMapper.deleteById(columnInfo.getColumn_id());
            }
        }
    }

    @Override
    public ResponseEntity<Object> preview(CodeGenConfig genConfig, IPage<CodeColumnConfig> columns) {
        List<CodeColumnConfig> columnsRecords = columns.getRecords();
        if (genConfig.getConfig_id() == null) {
            throw new BadRequestException("请先配置生成器");
        }
        List<Map<String, Object>> genList = GenUtil.preview(columnsRecords, genConfig);
        return new ResponseEntity<>(genList, HttpStatus.OK);
    }

    @Override
    public void download(CodeGenConfig genConfig, IPage<CodeColumnConfig> columnsPage, HttpServletRequest request, HttpServletResponse response) {
        List<CodeColumnConfig> columns = columnsPage.getRecords();
        if (genConfig.getConfig_id() == null) {
            throw new BadRequestException("请先配置生成器");
        }
        try {
            File file = new File(GenUtil.download(columns, genConfig));
            String zipPath = file.getPath() + ".zip";
            ZipUtil.zip(file.getPath(), zipPath);
            FileUtil.downloadFile(request, response, new File(zipPath), true);
        } catch (IOException e) {
            throw new BadRequestException("打包失败");
        }
    }

    @Override
    public void generator(CodeGenConfig genConfig, IPage<CodeColumnConfig> columnsPage) {
        List<CodeColumnConfig> columns = columnsPage.getRecords();
        if (genConfig.getConfig_id() == null) {
            throw new BadRequestException("请先配置生成器");
        }
        try {
            GenUtil.generatorCode(columns, genConfig);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new BadRequestException("生成失败，请手动处理已生成的文件");
        }
    }
}
