package weaver.formmode.recruit.modeexpand.util;

import com.api.mobilemode.util.FieldHandler;
import com.cloudstore.dev.api.bean.MessageBean;
import com.cloudstore.dev.api.bean.MessageType;
import com.cloudstore.dev.api.util.Util_Message;
import com.engine.recruit.conn.ApplicantCommonInfo;
import com.weaver.formmodel.data.manager.FormInfoManager;
import com.weaver.formmodel.data.model.Formfield;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.IOUtils;
import weaver.conn.RecordSet;
import weaver.docs.docs.*;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author:dxfeng
 * @createTime: 2023/09/26
 * @version: 1.0
 */
public class RecruitModeUtil {
    /**
     * 邮件、短信发送，替换内容正则表达式
     */
    private static final Pattern EMAIL_PATTERN = Pattern.compile(Pattern.quote("{") + "(.*?)" + Pattern.quote("}"));
    /**
     * 消息中心，替换内容正则表达式
     */
    private static final Pattern MSG_PATTERN = Pattern.compile(Pattern.quote("$") + "(.*?)" + Pattern.quote("$"));


    /**
     * 消息推送
     *
     * @param messageType 消息来源
     * @param title       消息标题
     * @param context     消息内容
     * @param userIdList  接收人ID集合
     * @param creater     消息创建者
     */
    public static void messagePush(String messageType, String title, String context, Set<String> userIdList, Integer creater) {
        messagePush(messageType, title, context, userIdList, creater, "", "");
    }

    /**
     * @param messageType   消息来源
     * @param title         消息标题
     * @param context       消息内容
     * @param userIdList    接收人ID集合
     * @param creater       消息创建者
     * @param linkUrl       待办跳转地址
     * @param linkMobileUrl 移动端跳转地址
     */
    public static void messagePush(String messageType, String title, String context, Set<String> userIdList, Integer creater, String linkUrl, String linkMobileUrl) {
        MessageType message = MessageType.newInstance(Integer.parseInt(messageType));
        try {
            MessageBean messageBean = Util_Message.createMessage(message, userIdList, title, context, linkUrl, linkMobileUrl);
            messageBean.setCreater(creater);
            Util_Message.store(messageBean);
        } catch (IOException e) {
            new BaseBean().writeLog(e);
            e.printStackTrace();
        }
    }

    /**
     * 获取人员姓名
     *
     * @param ids 人员ID
     * @return 人员姓名
     */
    public static String getResourceNames(String ids) {
        try {
            return new ResourceComInfo().getLastnames(ids);
        } catch (Exception e) {
            new BaseBean().writeLog(e);
            throw new RuntimeException(e);
        }
    }


    /**
     * 转换空字符串为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 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;
    }

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

    public static String getFieldShowName(Formfield formfield, String fieldValue) {
        User user = new User(1);
        return FieldHandler.getFieldValue(fieldValue, formfield, true, user);
    }

    public static String getReplaceContent(String content, Map<String, List<Formfield>> fieldMapList, Map<String, Object> paramsData) {
        Matcher matcher = EMAIL_PATTERN.matcher(content);
        // 指定要匹配的字符串
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String replace = matcher.group(1);

            List<Formfield> formFieldList = fieldMapList.get(replace);
            if (CollectionUtils.isEmpty(formFieldList)) {
                continue;
            }
            // 多个相同名称的字段，只取第一个
            Formfield formfield = formFieldList.get(0);
            String replaceValue = Util.null2String(paramsData.get(formfield.getFieldname().toLowerCase()));
            String fieldShowName = RecruitModeUtil.getFieldShowName(formfield, replaceValue).replaceAll("<[^>]*>", "");
            matcher.appendReplacement(sb, Util.null2String(fieldShowName));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 消息中心，替换消息内容
     *
     * @param content
     * @param fieldMap
     * @param paramsData
     * @return
     */
    public static String getMsgReplaceStr(String content, Map<String, Formfield> fieldMap, Map<String, Object> paramsData) {
        Matcher matcher = MSG_PATTERN.matcher(content);
        // 指定要匹配的字符串
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String replace = matcher.group(1);

            Formfield formfield = fieldMap.get(replace);
            String replaceValue = Util.null2String(paramsData.get(formfield.getFieldname().toLowerCase()));
            String fieldShowName = RecruitModeUtil.getFieldShowName(formfield, replaceValue).replaceAll("<[^>]*>", "");
            matcher.appendReplacement(sb, Util.null2String(fieldShowName));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 附件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;
    }

    public static String getImageFileIdsByDocIds(String docId) {
        if (StringUtils.isBlank(docId)) {
            return "";
        }
        List<String> imageFileIds = new ArrayList<>();
        String[] split = docId.split(",");
        try {
            for (String s : split) {
                if (StringUtils.isBlank(s)) {
                    continue;
                }
                DocImageManager imgManger = new DocImageManager();
                imgManger.setDocid(Integer.parseInt(s));

                imgManger.selectDocImageInfo();
                imgManger.next();
                imageFileIds.add(imgManger.getImagefileid());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        return StringUtils.join(imageFileIds, ",");
    }

    /**
     * 获取邮件模板主题
     *
     * @param id
     */
    public static String getEmailTitle(String id) {
        RecordSet recordSet = new RecordSet();
        String emailTitle = "";
        recordSet.executeQuery("select yjzt from uf_jcl_yjtzmb where id = ?", id);
        if (recordSet.next()) {
            emailTitle = recordSet.getString("yjzt");
        }
        return emailTitle;
    }

}
