package com.yunzhupaas.base.service.impl;

import com.google.common.base.CaseFormat;
import com.yunzhupaas.base.model.ai.VisualAiModel;
import com.yunzhupaas.base.service.VisualAiService;
import com.yunzhupaas.constant.GenerateConstant;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.constants.AiConstants;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.model.ai.AiFormFieldModel;
import com.yunzhupaas.model.ai.AiFormModel;
import com.yunzhupaas.service.OpenAiService;
import com.yunzhupaas.util.AiLimitUtil;
import com.yunzhupaas.util.StringUtil;
import com.yunzhupaas.util.UserProvider;
import com.yunzhupaas.util.visiual.YunzhupaasKeyConsts;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 在线开发ai实现
 *
 * @author 云筑产品开发平台组
 * @version v5.1.0
 * @copyright 深圳市乐程软件有限公司
 * @date 2024/12/2 10:05:25
 */
@Service
public class VisualAiServiceImpl implements VisualAiService {
    @Autowired
    private OpenAiService openAiService;

    @Override
    public VisualAiModel form(String keyword) {
        if(!AiLimitUtil.tryAcquire(UserProvider.getUser().getUserId())){
            throw new DataException(MsgCode.SYS182.get());
        }
        VisualAiModel visualAiModel = new VisualAiModel();
        List<AiFormModel> aiModelList = new ArrayList<>();
        List<AiFormModel> list = openAiService.generatorModelVO(keyword);
        if (CollectionUtils.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                AiFormModel aiFormModel = list.get(i);
                if (Objects.equals(0, i)) {
                    String enCode = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, aiFormModel.getTableName());
                    visualAiModel.setFullName(aiFormModel.getTableTitle());
                    visualAiModel.setEnCode(enCode);
                    aiFormModel.setIsMain(true);
                } else {
                    aiFormModel.setIsMain(false);
                }
                List<AiFormFieldModel> fields = new ArrayList<>();
                List<AiFormFieldModel> fieldList = aiFormModel.getFields();
                if (CollectionUtils.isNotEmpty(fieldList)) {
                    int index = 1;
                    for (int j = 0; j < fieldList.size(); j++) {
                        AiFormFieldModel aiFormFieldModel = fieldList.get(j);
                        String fieldName = aiFormFieldModel.getFieldName();
                        String yunzhupaasKey = aiFormFieldModel.getFieldComponent();
                        if (containsChinese(fieldName) || GenerateConstant.containKeyword(fieldName)) {
                            String formatIndex = String.format("%03d", index);
                            String suffix = "_num" + formatIndex;
                            aiFormFieldModel.setFieldName(yunzhupaasKey + suffix);
                            index++;
                        }
                        List<String> yunzhupaasKeyList = new ArrayList<>();
                        for (String s : AiConstants.GEN_MODEL_COMPNENT.split("-")) {
                            if (StringUtil.isNotBlank(s)) yunzhupaasKeyList.add(s.trim());
                        }
                        if (!yunzhupaasKeyList.contains(yunzhupaasKey)) {
                            aiFormFieldModel.setFieldComponent(YunzhupaasKeyConsts.COM_INPUT);
                        }
                        //子表控件处理
                        if (!aiFormModel.getIsMain()) {
                            //子表不能有单选框，多选框-调整成下拉框
                            List<String> childNotRadio = new ArrayList<>();
                            childNotRadio.add(YunzhupaasKeyConsts.RADIO);
                            childNotRadio.add(YunzhupaasKeyConsts.CHECKBOX);
                            //子表不能有的其他控件
                            List<String> childNotOther = new ArrayList<>();
                            childNotOther.add(YunzhupaasKeyConsts.TEXTAREA);
                            childNotOther.add(YunzhupaasKeyConsts.LINK);
                            childNotOther.add(YunzhupaasKeyConsts.BUTTON);
                            childNotOther.add(YunzhupaasKeyConsts.ALERT);
                            childNotOther.add(YunzhupaasKeyConsts.BARCODE);
                            childNotOther.add(YunzhupaasKeyConsts.QR_CODE);
                            childNotOther.add(YunzhupaasKeyConsts.EDITOR);
                            if (childNotRadio.contains(yunzhupaasKey)) {
                                aiFormFieldModel.setFieldComponent(YunzhupaasKeyConsts.SELECT);
                            } else if (childNotOther.contains(yunzhupaasKey)) {
                                aiFormFieldModel.setFieldComponent(YunzhupaasKeyConsts.COM_INPUT);
                            }
                        }

                        if (containsKeyWord(aiFormFieldModel.getFieldName())) {
                            fields.add(aiFormFieldModel);
                        }
                    }
                }
                aiFormModel.setFields(fields);
                aiModelList.add(aiFormModel);
            }
        }
        visualAiModel.setAiModelList(aiModelList);
        return visualAiModel;
    }

    /**
     * 判断是否包含中文（字段空或者包含中文字段名称重命名）
     *
     * @param str
     * @return
     */
    private static boolean containsChinese(String str) {
        if (StringUtil.isEmpty(str)) return true;
        Pattern pattern = Pattern.compile("[\u4E00-\u9FA5]");
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }

    /**
     * 字段是否包含特定（用于过滤掉不要的字段如：以_fk结尾是外键，本系统内已自动生成外键）
     *
     * @param str
     * @return
     */
    private static boolean containsKeyWord(String str) {
        if (str.toLowerCase().endsWith("_fk")) {
            return false;
        }
        return true;
    }
}

