package com.njzscloud.common.gen;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.core.tuple.Tuple2;
import com.njzscloud.common.core.tuple.Tuple3;
import com.njzscloud.common.gen.support.DbMetaData;
import com.njzscloud.common.gen.support.Generator;
import com.njzscloud.common.gen.support.TemplateEngine;
import com.njzscloud.common.gen.support.Tpl;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 代码模板
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TplService extends ServiceImpl<TplMapper, TplEntity> implements IService<TplEntity> {

    /**
     * 新增
     *
     * @param tplEntity 数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(TplEntity tplEntity) {
        String tplName = tplEntity.getTplName();
        Assert.notBlank(tplName, () -> Exceptions.clierr("模板名称不能为空"));
        boolean exists = this.exists(Wrappers.lambdaQuery(TplEntity.class).eq(TplEntity::getTplName, tplName));
        Assert.isFalse(exists, () -> Exceptions.clierr("模板：{} 已存在", tplName));
        Tpl tpl = tplEntity.getTpl();
        if (tpl == null) {
            tplEntity.setTpl(new Tpl());
        }

        Map<String, Object> modelData = tplEntity.getModelData();
        if (modelData == null) {
            tplEntity.setModelData(MapUtil.empty());
        }
        this.save(tplEntity);
    }

    /**
     * 修改
     *
     * @param tplEntity 数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void modify(TplEntity tplEntity) {
        String tplName = tplEntity.getTplName();
        Assert.notBlank(tplName, () -> Exceptions.clierr("模板名称不能为空"));
        Long id = tplEntity.getId();
        boolean exists = this.exists(Wrappers.lambdaQuery(TplEntity.class)
            .eq(TplEntity::getTplName, tplName)
            .ne(TplEntity::getId, id)
        );
        Assert.isFalse(exists, () -> Exceptions.clierr("模板：{} 已存在", tplName));
        TplEntity oldData = this.getById(id);
        Assert.notNull(oldData, () -> Exceptions.clierr("未找到要修改数据"));
        TemplateEngine.rmEngine(oldData.getTplName());
        this.updateById(tplEntity);
    }

    /**
     * 删除
     *
     * @param ids Ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 详情
     *
     * @param id Id
     * @return SysTplEntity 结果
     */
    public TplEntity detail(Long id) {
        return this.getById(id);
    }

    /**
     * 分页查询
     *
     * @param tplEntity 筛选条件
     * @param pageParam 分页参数
     * @return PageResult&lt;SysTplEntity&gt; 分页结果
     */
    public PageResult<TplEntity> paging(PageParam pageParam, TplEntity tplEntity) {
        return PageResult.of(this.page(pageParam.toPage(), Wrappers.query(tplEntity)));
    }

    private final DbMetaData dbMetaData;

    public PageResult<Map<String, Object>> tablePaging(PageParam pageParam, String tableSchema, String tableName) {
        pageParam.setOrders("TABLE_NAME");
        if (StrUtil.isBlank(tableSchema)) {
            tableSchema = dbMetaData.getDatabaseName();
        }
        Assert.notBlank(tableSchema, () -> Exceptions.exception("数据库名称获取失败"));
        return PageResult.of(baseMapper.tablePaging(pageParam.toPage(), Wrappers.query()
            .eq("TABLE_SCHEMA", tableSchema)
            .like(StrUtil.isNotBlank(tableName), "TABLE_NAME", tableName)
        ));
    }

    public Map<String, Map<String, String>> preview(String lang, String tableName, Map<String, Object> data) {
        Map<String, Map<String, String>> map = MapUtil.newHashMap();
        List<String> tplNames = this.list(Wrappers.lambdaQuery(TplEntity.class)
                .eq(TplEntity::getLang, lang))
            .stream()
            .map(TplEntity::getTplName)
            .toList();

        for (String tplName : tplNames) {

            Tuple2<String, String> res = generate(tplName, tableName, data);

            map.put(tplName, MapUtil.<String, String>builder()
                .put("path", res.get_0())
                .put("content", res.get_1())
                .build());
        }
        return map;
    }

    public ByteArrayOutputStream download(String lang, String tableName, Map<String, Object> data) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        List<String> tplNames = this.list(Wrappers.lambdaQuery(TplEntity.class)
                .eq(TplEntity::getLang, lang))
            .stream()
            .map(TplEntity::getTplName)
            .toList();
        if (tplNames.isEmpty()) {
            return out;
        }
        int size = tplNames.size();
        String[] paths = new String[size];
        InputStream[] ins = new InputStream[size];
        for (int i = 0; i < size; i++) {
            String tplName = tplNames.get(i);
            Tuple2<String, String> res = generate(tplName, tableName, data);
            paths[i] = res.get_0();
            ins[i] = new ByteArrayInputStream(res.get_1().getBytes());
        }
        ZipUtil.zip(out, paths, ins);

        return out;
    }

    private Tuple2<String, String> generate(String tplName, String tableName, Map<String, Object> data) {
        Tuple3<String, String, String> res = Generator.generate(tplName, tableName, data);
        String res0 = res.get_0();
        String res1 = res.get_1();
        String res2 = res.get_2();
        StringBuilder pathBuilder = new StringBuilder();
        if (StrUtil.isNotBlank(res0)) {
            pathBuilder.append(res0.trim());
            if (!res0.endsWith("/")) pathBuilder.append("/");
        }
        if (StrUtil.isNotBlank(res1)) pathBuilder.append(res1.trim());
        else pathBuilder.append(IdUtil.fastSimpleUUID()).append(".txt");
        return Tuple2.of(pathBuilder.toString(), res2);
    }
}
