package com.mortals.xhx.common.utils;


import cn.hutool.core.util.StrUtil;
import com.mortals.framework.common.code.YesNo;
import com.mortals.xhx.base.framework.config.GenConfig;
import com.mortals.xhx.base.system.gentable.model.GentableColumnEntity;
import com.mortals.xhx.base.system.gentable.model.GentableEntity;
import com.mortals.xhx.common.code.HtmlTypeEnum;
import com.mortals.xhx.common.key.GenConstants;
import org.apache.commons.lang3.RegExUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * 代码生成器 工具类
 *
 * @author: zxfei
 * @date: 2021/9/28 15:35
 */
public class GenUtils {
    /**
     * 初始化表信息
     */
    public static void initTable(GentableEntity genTable, String operName) {
        genTable.setClassName(convertClassName(genTable.getTableName()));
        //packageName
        genTable.setPackageName(GenConfig.getPackageName());
        genTable.setModuleName(GenConfig.getModuleName());
        genTable.setBusinessName(getBusinessName(genTable.getTableName()));
        genTable.setFunctionName(replaceText(genTable.getTableComment()));
        genTable.setFunctionAuthor(GenConfig.getAuthor());
        genTable.setCreateUser(operName);
        genTable.setCreateTime(new Date());
    }

    /**
     * 初始化列属性字段
     */
    public static void initColumnField(GentableColumnEntity column, GentableEntity table) {
        String dataType = getDbType(column.getColumnType());
        String columnName = column.getColumnName();
        column.setTableId(table.getId());
        column.setCreateUser(table.getCreateUser());
        column.setCreateTime(new Date());
        column.setIsSerialize(0);
        if(column.getIsExport()==null){
            column.setIsExport(0);
        }
        column.setQueryType("=");
        // 设置java字段名
        column.setJavaField(StrUtil.toCamelCase(columnName));
        // 设置默认类型
        column.setJavaType(GenConstants.TYPE_STRING);

        if (arraysContains(GenConstants.COLUMNTYPE_STR, dataType) || arraysContains(GenConstants.COLUMNTYPE_TEXT, dataType)) {
            // 字符串长度超过255设置为文本域
            Integer columnLength = getColumnLength(column.getColumnType());
            Integer htmlType = columnLength >= 255 || arraysContains(GenConstants.COLUMNTYPE_TEXT, dataType) ? HtmlTypeEnum.HTML_TEXTAREA.getValue() : HtmlTypeEnum.HTML_INPUT.getValue();
            column.setHtmlType(htmlType);
        } else if (arraysContains(GenConstants.COLUMNTYPE_TIME, dataType)) {
            column.setJavaType(GenConstants.TYPE_DATE);

            column.setHtmlType(HtmlTypeEnum.HTML_DATETIME.getValue());
        } else if (arraysContains(GenConstants.COLUMNTYPE_NUMBER, dataType)) {
            column.setHtmlType(HtmlTypeEnum.HTML_INPUT.getValue());
            // 如果是浮点型 统一用BigDecimal
            String[] str = StringUtils.split(StringUtils.substringBetween(column.getColumnType(), "(", ")"), ",");
            if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) {
                column.setJavaType(GenConstants.TYPE_BIGDECIMAL);
            }
            // 如果是整形
            else if (str != null && str.length == 1 && Integer.parseInt(str[0]) <= 10) {
                column.setJavaType(GenConstants.TYPE_INTEGER);
            }
            // 长整形
            else {
                column.setJavaType(GenConstants.TYPE_LONG);
            }
        }

        // 插入字段（默认所有字段都需要插入）
        column.setIsInsert(GenConstants.REQUIRE);

        // 编辑字段
        if (ObjectUtils.isEmpty(column.getIsEdit())) {
            if (!arraysContains(GenConstants.COLUMNNAME_NOT_EDIT, columnName) && column.getIsPrimaryKey() != YesNo.YES.getValue()) {
                column.setIsEdit(GenConstants.REQUIRE);
            } else {
                column.setIsEdit(GenConstants.NOREQUIRE);
            }
        }
        // 列表字段
        if (ObjectUtils.isEmpty(column.getIsList())) {
            if (!arraysContains(GenConstants.COLUMNNAME_NOT_LIST, columnName) && column.getIsPrimaryKey() != YesNo.YES.getValue()) {
                column.setIsList(GenConstants.REQUIRE);
            } else {
                column.setIsList(GenConstants.NOREQUIRE);
            }
        }
        // 查询字段
        if (ObjectUtils.isEmpty(column.getIsQuery())) {
            if (!arraysContains(GenConstants.COLUMNNAME_NOT_QUERY, columnName) && column.getIsPrimaryKey() != YesNo.YES.getValue()) {
                column.setIsQuery(GenConstants.REQUIRE);
            } else {
                column.setIsQuery(GenConstants.NOREQUIRE);
            }
        }
        //默认都是否
        column.setIsList(GenConstants.NOREQUIRE);

        column.setIsQuery(GenConstants.NOREQUIRE);

        //拆解枚举类，格式必须为（1.啊啊啊，2.不不不）
        String temp = column.getColumnComment().replaceAll("（", "(").replaceAll("）", ")");
        String temp1 = StringUtils.substringBetween(temp, "(", ")");
        //String temp2 = StringUtils.substringBetween(column.getColumnComment(), "（", "）");
        checkDict(column, temp1);
        //checkDict(column, temp2);
        if(!ObjectUtils.isEmpty(column.getDict())){

            if(column.getDict().size()>2){
                column.setHtmlType(HtmlTypeEnum.HTML_SELECT.getValue());
            }else{
                column.setHtmlType(HtmlTypeEnum.HTML_RADIO.getValue());
            }

            //radio
        }

        // 状态字段设置单选框
//        if (StringUtils.endsWithIgnoreCase(columnName.toLowerCase(), "status")) {
//            column.setHtmlType(HtmlTypeEnum.HTML_RADIO.getValue());
//        }
//        // 类型&性别字段设置下拉框
//        else if (StringUtils.endsWithIgnoreCase(columnName.toLowerCase(), "type")
//                || StringUtils.endsWithIgnoreCase(columnName, "sex")) {
//            column.setHtmlType(HtmlTypeEnum.HTML_SELECT.getValue());
//        }
        // 图片字段设置图片上传控件
        else if (StringUtils.endsWithIgnoreCase(columnName.toLowerCase(), "imagepath")) {
            column.setHtmlType(HtmlTypeEnum.HTML_IMAGE_UPLOAD.getValue());
        }
        // 文件字段设置文件上传控件
        else if (StringUtils.endsWithIgnoreCase(columnName.toLowerCase(), "filepath")) {
            column.setHtmlType(HtmlTypeEnum.HTML_FILE_UPLOAD.getValue());
        }
        // 内容字段设置富文本控件
        else if (StringUtils.endsWithIgnoreCase(columnName.toLowerCase(), "content")) {
            column.setHtmlType(HtmlTypeEnum.HTML_EDITOR.getValue());
        }
    }

    public static void checkDict(GentableColumnEntity column, String temp) {

        if (StringUtils.isNotEmpty(temp)) {
            //同意替换分割符号
            temp=temp.replaceAll("，",",");
            temp=temp.replaceAll(";",",");

            //temp=temp.replaceAll("、",".");
            temp=temp.replaceAll("。",".");
            String[] split = checkSplitStr(temp, ",");

            if (split.length > 0) {
                Arrays.asList(split).stream().peek(item -> {
                    String[] vals = checkSplitStr(item, ".");
                    if (vals.length > 1) {
                        HashMap<String, String> map = new HashMap<>();
                        map.put("num", vals[0].trim());
                        map.put("value", vals[1].trim());

                        if (ObjectUtils.isEmpty(column.getDict())) {
                            column.setDict(new ArrayList<>());
                        }
                        column.getDict().add(map);
                    }
                }).count();

            }
        }
    }

    public static String[] checkSplitStr(String temp, String separator) {
        return StringUtils.split(temp, separator);
    }

    /**
     * 校验数组是否包含指定值
     *
     * @param arr         数组
     * @param targetValue 值
     * @return 是否包含
     */
    public static boolean arraysContains(String[] arr, String targetValue) {
        return Arrays.asList(arr).contains(targetValue);
    }

    /**
     * 获取模块名
     *
     * @param packageName 包名
     * @return 模块名
     */
    public static String getModuleName(String packageName) {
        int lastIndex = packageName.lastIndexOf(".");
        int nameLength = packageName.length();
        String moduleName = StringUtils.substring(packageName, lastIndex + 1, nameLength);
        return moduleName;
    }

    /**
     * 获取业务名
     *
     * @param tableName 表名
     * @return 业务名
     */
    public static String getBusinessName(String tableName) {
        //替换前缀
        boolean autoRemovePre = GenConfig.getAutoRemovePre();
        String tablePrefix = GenConfig.getTablePrefix();
        if (autoRemovePre && StringUtils.isNotEmpty(tablePrefix)) {
            String[] searchList = StringUtils.split(tablePrefix, ",");
            tableName = replaceFirst(tableName, searchList);
        }
        //分割拼接
        //String businessName = Arrays.stream(tableName.split("_")).collect(Collectors.joining("."));

        //tableName.indexOf("_")

        //默认添加第一个

//        int lastIndex = tableName.lastIndexOf("_");
//        int nameLength = tableName.length();
        String businessName =tableName;
        if(tableName.indexOf("_")!=-1){
             businessName = StringUtils.substring(tableName, 0, tableName.indexOf("_"));
        }

        return businessName;
    }

    /**
     * 获取业务名
     *
     * @param tableName 表名
     * @return 业务名
     */
    public static String getBusinessNameExt(String tableName) {
        //替换前缀
        boolean autoRemovePre = GenConfig.getAutoRemovePre();
        String tablePrefix = GenConfig.getTablePrefix();
        if (autoRemovePre && StringUtils.isNotEmpty(tablePrefix)) {
            String[] searchList = StringUtils.split(tablePrefix, ",");
            tableName = replaceFirst(tableName, searchList);
        }
        //分割拼接
        String businessName = Arrays.stream(tableName.split("_")).collect(Collectors.joining("."));
        return businessName;
    }

    /**
     * 表名转换成Java类名
     *
     * @param tableName 表名称
     * @return 类名
     */
    public static String convertClassName(String tableName) {
        boolean autoRemovePre = GenConfig.getAutoRemovePre();
        String tablePrefix = GenConfig.getTablePrefix();
        if (autoRemovePre && StringUtils.isNotEmpty(tablePrefix)) {
            String[] searchList = StringUtils.split(tablePrefix, ",");
            tableName = replaceFirst(tableName, searchList);
        }
        return StringUtils.convertToCamelCase(tableName);
    }

    /**
     * 批量替换前缀
     *
     * @param replacementm 替换值
     * @param searchList   替换列表
     * @return
     */
    public static String replaceFirst(String replacementm, String[] searchList) {
        String text = replacementm;
        for (String searchString : searchList) {
            if (replacementm.startsWith(searchString)) {
                text = replacementm.replaceFirst(searchString, "");
                break;
            }
        }
        return text;
    }

    /**
     * 关键字替换
     *
     * @param text 需要被替换的名字
     * @return 替换后的名字
     */
    public static String replaceText(String text) {
        return RegExUtils.replaceAll(text, "(?:表)", "");
    }

    /**
     * 获取数据库类型字段
     *
     * @param columnType 列类型
     * @return 截取后的列类型
     */
    public static String getDbType(String columnType) {
        if (StringUtils.indexOf(columnType, "(") > 0) {
            return StringUtils.substringBefore(columnType, "(");
        } else {
            return columnType;
        }
    }

    /**
     * 获取字段长度
     *
     * @param columnType 列类型
     * @return 截取后的列类型
     */
    public static Integer getColumnLength(String columnType) {
        if (StringUtils.indexOf(columnType, "(") > 0) {
            String length = StringUtils.substringBetween(columnType, "(", ")");

            if(ObjectUtils.isEmpty(length)) {
                return 0;
            }
            return Integer.valueOf(length);
        } else {
            return 0;
        }
    }


    public static void main(String[] args) {
        String name = "aaa";


        System.out.println(Arrays.stream(name.split("_")).collect(Collectors.joining(".")));

        System.out.println(Arrays.stream("data".split(".")).collect(Collectors.joining("/")));
    }
}
