package com.engine.secret.util;

import com.engine.secret.exception.CustomizeRunTimeException;
import com.weaver.formmodel.data.manager.FormInfoManager;
import com.weaver.formmodel.data.model.Formfield;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.IOUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.docs.docs.*;
import weaver.file.ImageFileManager;
import weaver.formmode.IgnoreCaseHashMap;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author:dxfeng
 * @createTime: 2025/03/26
 * @version: 1.0
 */
public class ModeUtil {

    /**
     * 生成附件ID
     *
     * @param inputStream
     * @param filename
     * @return
     */
    public static int generateImageFileId(InputStream inputStream, String filename) {
        int imageFileId;
        try {
            byte[] bytes = IOUtils.toByteArray(inputStream);
            ImageFileManager ifm = new ImageFileManager();
            ifm.setData(bytes);
            ifm.setImagFileName(filename);
            imageFileId = ifm.saveImageFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return imageFileId;
    }

    /**
     * 附件imageFieldId生成docId
     *
     * @param secCategory
     * @param imageFieldId
     * @param user
     * @return
     * @throws Exception
     */
    public static int createDocId(int secCategory, int imageFieldId, User user) throws Exception {
        ImageFileManager manager = new ImageFileManager();
        manager.getImageFileInfoById(imageFieldId);
        String filenameqc = manager.getImageFileName();
        String filenamebc = filenameqc.substring(0, filenameqc.lastIndexOf("."));
        RecordSet rs = new RecordSet();
        DocManager dm = new DocManager();
        DocImageManager imgManger = new DocImageManager();

        imgManger.setDocfiletype("2");

        int docId = dm.getNextDocId(rs);
        imgManger.setDocid(docId);
        imgManger.setImagefileid(imageFieldId);
        imgManger.setImagefilename(filenameqc);
        imgManger.setIsextfile("1");
        imgManger.AddDocImageInfo();

        String date = TimeUtil.getCurrentDateString();
        String time = TimeUtil.getOnlyCurrentTimeString();
        dm.setId(docId);
        dm.setMaincategory(0);
        dm.setSubcategory(0);
        dm.setSeccategory(secCategory);
        dm.setLanguageid(user.getLanguage());

        dm.setDocstatus("1");
        dm.setDocsubject(filenamebc);
        dm.setDoccreaterid(user.getUID());
        dm.setDocCreaterType(user.getLogintype());
        dm.setUsertype(user.getLogintype());
        dm.setOwnerid(user.getUID());
        dm.setOwnerType(user.getLogintype());
        dm.setDoclastmoduserid(user.getUID());
        dm.setDocLastModUserType(user.getLogintype());
        dm.setDoccreatedate(date);
        dm.setDoclastmoddate(date);
        dm.setDoccreatetime(time);
        dm.setDoclastmodtime(time);
        dm.setDoclangurage(user.getLanguage());
        dm.setKeyword(filenameqc);
        dm.setIsapprover("0");
        dm.setIsreply("");
        dm.setDocdepartmentid(user.getUserDepartment());
        dm.setDocreplyable("1");
        dm.setAccessorycount(1);
        dm.setParentids("" + docId);
        dm.setUserid(user.getUID());
        DocCoder docCoder = new DocCoder();
        dm.setDocCode(docCoder.getDocCoder("" + secCategory));
        dm.setDocEditionId(dm.getNextEditionId(rs));
        dm.setDocEdition(1);
        dm.AddDocInfo();
        dm.AddShareInfo();
        DocViewer DocViewer = new DocViewer();
        DocViewer.setDocShareByDoc("" + docId);
        DocComInfo dc = new DocComInfo();
        dc.addDocInfoCache("" + docId);
        return docId;
    }

    /**
     * 获取单个记录映射
     *
     * @param rs RecordSet
     * @return
     */
    public static IgnoreCaseHashMap<String, Object> getSingleRecordMap(RecordSet rs) {
        IgnoreCaseHashMap<String, Object> dataMap = new IgnoreCaseHashMap<>();
        if (rs.next()) {
            String[] columnNames = rs.getColumnName();
            for (String columnName : columnNames) {
                dataMap.put(columnName, parseBlankToNull(rs.getString(columnName)));
            }
        }
        return dataMap;
    }

    public static List<Map<String, Object>> getRecordMapList(RecordSet rs) {
        List<Map<String, Object>> list = new ArrayList<>();
        while (rs.next()) {
            String[] columnNames = rs.getColumnName();
            Map<String, Object> dataMap = new HashMap<String, Object>();
            for (String columnName : columnNames) {
                dataMap.put(columnName.toLowerCase(), parseBlankToNull(rs.getString(columnName)));
            }
            list.add(dataMap);
        }
        return list;
    }

    /**
     * 插入数据
     *
     * @param dataMap   数据集合
     * @param tableName 表名
     */
    public static void insertData(Map<String, Object> dataMap, String tableName) {
        List<String> fieldList = new ArrayList<>();
        List<String> dataList = new ArrayList<>();
        List<String> paramList = new ArrayList<>();

        dataMap.forEach((key, value) -> {
            if (null != value) {
                String valueStr = String.valueOf(value);
                if (StringUtils.isNotBlank(valueStr)) {
                    fieldList.add(key);
                    dataList.add(valueStr);
                    paramList.add("?");
                }
            }
        });
        String insertSql = " insert into " + tableName + "(" + StringUtils.join(fieldList, ",") + ") values (" + StringUtils.join(paramList, ",") + ")";
        RecordSet rs = new RecordSet();
        rs.executeUpdate(insertSql, dataList);
        if (StringUtils.isNotBlank(rs.getExceptionMsg())) {
            throw new CustomizeRunTimeException(rs.getExceptionMsg());
        }
    }

    public static void insertData(RecordSetTrans rs,Map<String, Object> dataMap, String tableName) throws Exception {
        List<String> fieldList = new ArrayList<>();
        List<String> dataList = new ArrayList<>();
        List<String> paramList = new ArrayList<>();

        dataMap.forEach((key, value) -> {
            if (null != value) {
                String valueStr = String.valueOf(value);
                if (StringUtils.isNotBlank(valueStr)) {
                    fieldList.add(key);
                    dataList.add(valueStr);
                    paramList.add("?");
                }
            }
        });
        String insertSql = " insert into " + tableName + "(" + StringUtils.join(fieldList, ",") + ") values (" + StringUtils.join(paramList, ",") + ")";
        rs.executeUpdate(insertSql, dataList);
    }

    /**
     * 根据ID更新数据
     *
     * @param dataMap
     * @param tableName
     */
    public static void updateDataById(Map<String, Object> dataMap, String tableName) {
        List<String> fieldList = new ArrayList<>();
        List<Object> dataList = new ArrayList<>();
        String id = Util.null2String(dataMap.get("id"));
        dataMap.remove("id");

        dataMap.forEach((key, value) -> {
            fieldList.add(key + " = ? ");
            dataList.add(value);
        });
        dataList.add(id);
        String updateSql = "update " + tableName + " set " + StringUtils.join(fieldList, ",") + " where id = ? ";
        RecordSet rs = new RecordSet();
        rs.executeUpdate(updateSql, dataList);
        if (StringUtils.isNotBlank(rs.getExceptionMsg())) {
            throw new CustomizeRunTimeException(rs.getExceptionMsg());
        }
    }

    /**
     * 根据ID更新数据
     *
     * @param dataMap
     * @param tableName
     */
    public static void updateDataById(RecordSetTrans rs,Map<String, Object> dataMap, String tableName) throws Exception {
        List<String> fieldList = new ArrayList<>();
        List<Object> dataList = new ArrayList<>();
        String id = Util.null2String(dataMap.get("id"));
        dataMap.remove("id");

        dataMap.forEach((key, value) -> {
            fieldList.add(key + " = ? ");
            dataList.add(value);
        });
        dataList.add(id);
        String updateSql = "update " + tableName + " set " + StringUtils.join(fieldList, ",") + " where id = ? ";
        rs.executeUpdate(updateSql, dataList);
    }

    /**
     * 更新数据
     *
     * @param dataMap
     * @param tableName
     * @param whereSql
     */
    public static void updateData(Map<String, Object> dataMap, String tableName, String whereSql) {
        List<String> fieldList = new ArrayList<>();
        List<Object> dataList = new ArrayList<>();
        dataMap.forEach((key, value) -> {
            fieldList.add(key + " = ? ");
            dataList.add(value);
        });
        String updateSql = "update " + tableName + " set " + StringUtils.join(fieldList, ",") + whereSql;
        RecordSet rs = new RecordSet();
        rs.executeUpdate(updateSql, dataList);
        if (StringUtils.isNotBlank(rs.getExceptionMsg())) {
            throw new CustomizeRunTimeException(rs.getExceptionMsg());
        }
    }

    /**
     * 删除数据
     *
     * @param deleteSql
     */
    public static void deleteData(String deleteSql) {
        RecordSet rs = new RecordSet();
        rs.executeUpdate(deleteSql);
        if (StringUtils.isNotBlank(rs.getExceptionMsg())) {
            throw new CustomizeRunTimeException(rs.getExceptionMsg());
        }
    }


    /**
     * 构建建模表基本数据
     *
     * @param mainDataMap 参数集合
     */
    public static void buildModeInsertFields(Map<String, Object> mainDataMap, int userId) {
        String dateTime = DateUtil.getFullDate();
        String[] dateSplit = dateTime.split(" ");
        mainDataMap.put("modedatacreater", userId);
        mainDataMap.put("modedatacreatedate", dateSplit[0]);
        mainDataMap.put("modedatacreatetime", dateSplit[1]);
        mainDataMap.put("modedatacreatertype", "0");
    }

    /**
     * 构建建模表基本数据
     *
     * @param mainDataMap 参数集合
     */
    public static void buildModeUpdateFields(Map<String, Object> mainDataMap, int userId) {
        String dateTime = DateUtil.getFullDate();
        mainDataMap.put("modedatamodifier", userId);
        mainDataMap.put("modedatamodifydatetime", dateTime);
    }

    /**
     * 建模表数据权限重构
     *
     * @param uuid
     * @param modeTable
     * @param formModeId
     */
    public static int refreshRight(String uuid, String modeTable, int formModeId, int creator) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from " + modeTable + " where modeuuid='" + uuid + "'");
        if (rs.next()) {
            //建模数据的id
            int bid = Util.getIntValue(rs.getString("id"));
            ModeRightInfo modeRightInfo = new ModeRightInfo();
            modeRightInfo.setNewRight(true);
            //新建的时候添加共享
            modeRightInfo.editModeDataShare(creator, formModeId, bid);
            return bid;
        }
        return -1;
    }


    /**
     * 转换空字符串为null
     *
     * @param str 字符串
     * @return 转换后的字符串
     */
    public static Object parseBlankToNull(String str) {
        return StringUtils.isBlank(str) ? null : str;
    }

    /**
     * 转换空字符串为null
     *
     * @param obj 对象
     * @return 转换后的字符串
     */
    public static String parseBlankToNull(Object obj) {
        return Objects.isNull(obj) ? null : StringUtils.isBlank(obj.toString()) ? null : obj.toString();
    }

    /**
     * 根据建模表名,获取建模ID
     *
     * @param modeTable
     * @return
     */
    public static int getModeIdByTableName(String modeTable) {
        int formModeId = -1;
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from modeinfo where formid =( select id from workflow_bill where tablename = ? ) and isdelete = 0 order by id", modeTable);
        if (rs.next()) {
            formModeId = rs.getInt("id");
        }
        return formModeId;
    }

    public static List<Formfield> getFieldList(String tableName) {
        int formId = getFormIdByTableName(tableName);
        return FormInfoManager.getInstance().getAllField(formId);
    }

    public static List<Formfield> getFieldList(int formId) {
        return FormInfoManager.getInstance().getAllField(formId);
    }

    /**
     * 根据表名，获取表单ID
     *
     * @param modeTable
     * @return
     */
    public static int getFormIdByTableName(String modeTable) {
        int formId = -1;
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from workflow_bill where tablename = ? ", modeTable);
        if (rs.next()) {
            formId = rs.getInt("id");
        }
        return formId;
    }

    /**
     * 获取表单下拉框展示文本
     *
     * @param formId    表单ID
     * @param fieldName 字段明湖曾
     * @param value     下拉框值
     * @return
     */
    public static String getSelectName(String formId, String fieldName, String value) {
        String cancelReason = "";
        RecordSet rs = new RecordSet();
        rs.executeQuery("select selectname from workflow_selectitem where fieldid =( select id from workflow_billfield where billid = ? and fieldname = ? ) and selectvalue = ?", formId, fieldName, value);
        if (rs.next()) {
            cancelReason = rs.getString("selectname");
        }
        return cancelReason;
    }

    /**
     * 获取表单下拉框值
     *
     * @param formId     表单ID
     * @param fieldName  字段明湖曾
     * @param selectName 下拉框展示内容
     * @return
     */
    public static String getSelectValue(String formId, String fieldName, String selectName) {
        String selectValue = "";
        RecordSet rs = new RecordSet();
        rs.executeQuery("select selectvalue from workflow_selectitem where fieldid =( select id from workflow_billfield where billid = ? and fieldname = ? ) and selectname = ?", formId, fieldName, selectName);
        if (rs.next()) {
            selectValue = rs.getString("selectvalue");
        }
        return selectValue;
    }

    public static String getSelectValue(Formfield formfield, String selectName) {
        String selectValue = "";
        RecordSet rs = new RecordSet();
        String detailTable = Util.null2String(formfield.getDetailtable());
        if (StringUtils.isNotBlank(detailTable)) {
            rs.executeQuery("select selectvalue from workflow_selectitem where fieldid =( select id from workflow_billfield where billid = ? and fieldname = ? and detailtable = ? ) and selectname = ?", formfield.getBillid(), formfield.getFieldname(), Util.null2String(detailTable), selectName);
        } else {
            rs.executeQuery("select selectvalue from workflow_selectitem where fieldid =( select id from workflow_billfield where billid = ? and fieldname = ? AND (detailtable IS NULL OR detailtable = '') ) and selectname = ?", formfield.getBillid(), formfield.getFieldname(), selectName);
        }
        if (rs.next()) {
            selectValue = rs.getString("selectvalue");
        }
        return selectValue;
    }


    /**
     * 全角转半角
     *
     * @param input
     * @return
     */
    public static String ToDBC(String input) {
        if (input == null) {
            input = "";
        }
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                //全角空格为12288，半角空格为32
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375) {
                //其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
                c[i] = (char) (c[i] - 65248);
            }
        }
        return new String(c);
    }

    public static String getTableNameByCustomId(String customId) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select tablename from workflow_bill where id = (select formid from mode_customsearch where id = ?)", customId);
        if (rs.next()) {
            return rs.getString("tablename");
        }
        return "";
    }


}
