package com.yunzhupaas.base.util.fuctionFormVue3;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yunzhupaas.base.entity.VisualdevEntity;
import com.yunzhupaas.base.model.ColumnDataModel;
import com.yunzhupaas.base.model.DownloadCodeForm;
import com.yunzhupaas.base.model.Template6.BtnData;
import com.yunzhupaas.base.model.Template6.ColumnListField;
import com.yunzhupaas.base.model.Template7.Template7Model;
import com.yunzhupaas.base.util.common.*;
import com.yunzhupaas.generater.model.FormDesign.SearchTypeModel;
import com.yunzhupaas.model.visualJson.config.HeaderModel;
import com.yunzhupaas.util.JsonUtil;
import com.yunzhupaas.util.XSSEscape;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.velocity.VelocityContext;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 云筑产品开发平台组
 * @version V3.5.0
 * @copyright 深圳市乐程软件有限公司（http://www.szlecheng.cn）
 * @date 2024/5/31
 */
public class GenerateDataView implements GenerateInterface {

    @Override
    public List<String> getTemplates(String templatePath, int type, boolean hasImport) {
        List<String> templates = new ArrayList<>();
        //前端
        templates.add(templatePath + File.separator + "index.vue.vm");
        //api接口
        templates.add(File.separator + "helper" + File.separator + "api.ts.vm");
        //后端
        if (hasImport) {
            templates.add(File.separator + "java" + File.separator + "ExcelVO.java.vm");
            templates.add(File.separator + "java" + File.separator + "ExcelErrorVO.java.vm");
        }
        templates.add(File.separator + "java" + File.separator + "Pagination.java.vm");
        templates.add(File.separator + "java" + File.separator + "Constant.java.vm");
        return templates;
    }

    @Override
    public List<String> getChildTemps(boolean isChild) {
        return null;
    }

    /**
     * 数据视图代码生成
     *
     * @param generateParamModel
     * @throws Exception
     */
    public void generateDataView(GenerateParamModel generateParamModel) throws Exception {
        VisualdevEntity entity = generateParamModel.getEntity();
        DownloadCodeForm downloadCodeForm = generateParamModel.getDownloadCodeForm();
        String fileName = generateParamModel.getFileName();
        Template7Model template7Model = generateParamModel.getTemplate7Model();
        template7Model.setDescription(downloadCodeForm.getDescription());
        template7Model.setClassName(generateParamModel.getClassName());
        String templatesPath = generateParamModel.getTemplatesPath();
        String modelPathName = generateParamModel.getClassName().toLowerCase();

        //columnTempJson
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(entity.getColumnData(), ColumnDataModel.class);
        //app 列表对象
        ColumnDataModel appColumnDataModel = JsonUtil.getJsonToBean(entity.getAppColumnData(), ColumnDataModel.class);
        //按钮
        List<BtnData> btnPcList = JsonUtil.getJsonToList(columnDataModel.getBtnsList(), BtnData.class);
        List<BtnData> columnBtnPcList = JsonUtil.getJsonToList(columnDataModel.getColumnBtnsList(), BtnData.class);
        List<BtnData> btnAppList = JsonUtil.getJsonToList(appColumnDataModel.getBtnsList(), BtnData.class);
        List<BtnData> columnBtnAppList = JsonUtil.getJsonToList(appColumnDataModel.getColumnBtnsList(), BtnData.class);
        List<BtnData> btnDataList = new ArrayList<>(btnPcList);
        List<String> collect3 = btnPcList.stream().map(BtnData::getValue).collect(Collectors.toList());
        btnDataList.addAll(btnAppList.stream().filter(t -> !collect3.contains(t.getValue())).collect(Collectors.toList()));
        //是否有下载按钮
        boolean hasDownloadBtn = btnDataList.stream().anyMatch(btn -> btn.getValue().equals("download"));

        //列表和查询
        List<ColumnListField> columnList = JsonUtil.getJsonToList(columnDataModel.getColumnList(), ColumnListField.class);
        List<SearchTypeModel> searchList = JsonUtil.getJsonToList(columnDataModel.getSearchList(), SearchTypeModel.class);
        List<ColumnListField> columnAppList = JsonUtil.getJsonToList(appColumnDataModel.getColumnList(), ColumnListField.class);
        List<SearchTypeModel> searchAppList = JsonUtil.getJsonToList(appColumnDataModel.getSearchList(), SearchTypeModel.class);
        //查询全字段
        List<SearchTypeModel> searchListAll = new ArrayList<>(searchList);
        List<String> cSaArr = searchListAll.stream().map(SearchTypeModel::getId).collect(Collectors.toList());
        searchAppList.stream().forEach(t -> {
            if (!cSaArr.contains(t.getId())) {
                searchListAll.add(t);
                cSaArr.add(t.getId());
            }
        });
        searchListAll.stream().forEach(t -> t.setAfterVModel(t.getId()));

        Map<String, Object> map = new HashMap<>();

        //微服务标识
        map.put("isCloud", GenerateCommon.IS_CLOUD);
        map.put("isMain", true);
        map.put("package", downloadCodeForm.getModulePackageName());
        map.put("module", downloadCodeForm.getModule());
        map.put("moduleId", entity.getId());
        map.put("className", DataControlUtils.captureName(generateParamModel.getClassName()));
        map.put("genInfo", generateParamModel.getTemplate7Model());

        map.put("hasDownloadBtn", hasDownloadBtn);
        map.put("isList", true);
        map.put("webType", 4);
        map.put("hasPage", columnDataModel.getHasPage());
        map.put("groupTable", columnDataModel.getType() == 3);
        map.put("groupField", columnDataModel.getGroupField());
        //数据接口参数
        map.put("interfaceId", entity.getInterfaceId());
        map.put("interfaceParam", JSONObject.toJSONString(entity.getInterfaceParam()));
        //列表全属性
        map.put("columnDataStr", JSONObject.toJSONString(GenerateCommon.objRemoveJson(entity.getColumnData())));
        map.put("appColumnDataStr", JSONObject.toJSONString(GenerateCommon.objRemoveJson(entity.getAppColumnData())));
        map.put("columnData", JsonUtil.stringToMap(entity.getColumnData()));
        map.put("btnPcList", btnPcList);
        map.put("searchListAll", searchListAll);

        //合计
        map.put("configurationTotal", columnDataModel.isShowSummary());
        List<String> summaryList = CollectionUtils.isEmpty(columnDataModel.getSummaryField()) ? Collections.EMPTY_LIST : columnDataModel.getSummaryField();
        map.put("fieldsTotal", JsonUtil.getObjectToString(summaryList));

        //复杂表头
        List<String> complexFieldList = new ArrayList<>();
        List<Map<String, Object>> complexHeaderList = new ArrayList<>();
        if (!Objects.equals(columnDataModel.getType(), 3) && !Objects.equals(columnDataModel.getType(), 5)) {
            for (HeaderModel headerModel : columnDataModel.getComplexHeaderList()) {
                complexFieldList.addAll(headerModel.getChildColumns());
                complexHeaderList.add(JsonUtil.entityToMap(headerModel));
            }
        }
        map.put("complexHeaderList", JsonUtil.getListToJsonArray(complexHeaderList));
        map.put("complexFieldList", JsonUtil.getListToJsonArray(complexFieldList));
        //添加行参数
        Map<String, Object> columnDataJson = JsonUtil.stringToMap(entity.getColumnData());

        //最外层zip包路径名称
        String zipName = template7Model.getServiceDirectory() + fileName;
        //生成文件夹
        String htmlTSPath = XSSEscape.escapePath(zipName + File.separator + "html" + File.separator + "web" + File.separator + modelPathName + File.separator + "helper");
        File htmlJSfile = new File(htmlTSPath);
        if (!htmlJSfile.exists()) {
            htmlJSfile.mkdirs();
        }
        String colData = JSONObject.toJSONString(columnDataJson.get("columnList"), SerializerFeature.WriteMapNullValue);
        String colListJsPath = htmlTSPath + File.separator + "columnList.ts";
        SuperQueryUtil.CreateJsFile(colData, colListJsPath, "columnList");

        String searchData = JSONObject.toJSONString(columnDataJson.get("searchList"), SerializerFeature.WriteMapNullValue);
        String searchListJsPath = htmlTSPath + File.separator + "searchList.ts";
        SuperQueryUtil.CreateJsFile(searchData, searchListJsPath, "searchList");
        //生成controller代码
        this.genControllerFile(template7Model.getServiceDirectory() + fileName, map, templatesPath, downloadCodeForm);

        //生成复杂表头对象
        GenerateCommon.createComplexHeaderExcelVo(zipName, generateParamModel, entity, downloadCodeForm, map);

        //数据视图代码生成
        GenerateCommon.htmlTemplates(template7Model.getServiceDirectory() + fileName,
                map, templatesPath, 1, false, downloadCodeForm, this);
    }

    /**
     * 生成controller代码
     *
     * @param path         路径
     * @param object       模板数据
     * @param templatePath 模板路径
     */
    public static void genControllerFile(String path, Map<String, Object> object, String templatePath, DownloadCodeForm downloadCodeForm) throws Exception {
        //获取模板列表
        String controllerTem = templatePath + File.separator + "ViewController.java.vm";
        //界面模板
        VelocityContext context = new VelocityContext();
        context.put("context", object);
        String className = object.get("className").toString();

        String controllerDir = path + File.separator + "java" + File.separator + GenerateCommon.getCloudPath("-controller", downloadCodeForm)
                + File.separator + "controller";
        File controllerSrc = new File(controllerDir);
        if (!controllerSrc.exists()) {
            controllerSrc.mkdirs();
        }
        String fileNames = controllerDir + File.separator + className + "Controller.java";
        GenerateCommon.velocityWriterFile(context, controllerTem, fileNames);
    }
}

