package com.kingdee.eas.custom.recuritment.utils;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.ctrl.swing.StringUtils;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemCollection;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.base.attachment.*;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.shr.attachment.*;
import com.kingdee.shr.attachment.AttachmentTypeEnum;
import com.kingdee.shr.recuritment.ResumeBaseRecInfo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author qingwu
 * @date 2025/7/3
 * @apiNote
 */
public class AttachmentUtils {

    /**
     * 删除附件信息
     *
     * @param ctx
     * @param sql 条件
     * @throws BOSException
     * @throws EASBizException
     */
    public static void deleteAttachment(Context ctx, String sql) throws BOSException, EASBizException {
        //查询附件扩展表
        ISHRAttachmentExt ishrAttachmentExt = SHRAttachmentExtFactory.getLocalInstance(ctx);
        SHRAttachmentExtCollection shrAttachmentExtCollection = ishrAttachmentExt.getSHRAttachmentExtCollection(sql);
        Set delAtt = new HashSet();
        for (int i = 0; i < shrAttachmentExtCollection.size(); i++) {
            SHRAttachmentExtInfo shrAttachmentExtInfo = shrAttachmentExtCollection.get(i);
            AttachmentInfo attachment = shrAttachmentExtInfo.getAttachment();
            ishrAttachmentExt.delete(new ObjectUuidPK(shrAttachmentExtInfo.getId()));
            delAtt.add(attachment.getId());
        }
        if (delAtt.size() > 0) {
            //删除附件主表数据
            FilterInfo delAttFilter = new FilterInfo();
            delAttFilter.getFilterItems().add(new FilterItemInfo("id", delAtt, CompareType.INCLUDE));
            IAttachment iAttachment = AttachmentFactory.getLocalInstance(ctx);
            iAttachment.delete(delAttFilter);
            //删除附件扩展表和关联关系表数据
            FilterInfo dleExFilter = new FilterInfo();
            dleExFilter.getFilterItems().add(new FilterItemInfo("attachment.id", delAtt, CompareType.INCLUDE));
            BoAttchAssoFactory.getLocalInstance(ctx).delete(dleExFilter);
        }
    }

    /***
     * 保存附件
     * @param filename
     * @param data
     * @throws BOSException
     * @throws EASBizException
     */
    public static void insertAttachment(Context ctx, String filename, ResumeBaseRecInfo resumeInfo, byte[] data, String oldfileName) {
        try {
            //if (data.length > 20971520) {
            //    throw new BOSException("保存附件失败，附件大小超过20MB！");
            //}

            //if (StringUtils.isEmpty(filename) || null == resumeInfo.getId() || data.length <= 0) {
            //    throw new BOSException("保存附件失败，参数格式不正确！");
            //}
            String boId = resumeInfo.getId().toString();
//            String boId = "njRU7qn9RyKlGA2FG+hdCMXc5i4=";
            SHRAttachmentExtInfo attchExt = new SHRAttachmentExtInfo();
            AttachmentInfo ai = new AttachmentInfo();
            ai.setName(filename.substring(0, filename.lastIndexOf('.')));
            ai.setSimpleName(filename.substring(filename.lastIndexOf(".") + 1));
            ai.setDescription("");
            ai.setFile(data);
            ai.setIsShared(false);
            ai.setSharedDesc("否");
            ai.setAttachID("" + System.currentTimeMillis());
            ai.setType(getFileType(filename));
            AttachmentFactory.getLocalInstance(ctx).addnew(ai);
            attchExt.setAttachment(ai);
            attchExt.setName(filename);
            attchExt.setPropertyName("null0");
            attchExt.setType(AttachmentTypeEnum.FORM);
//            attchExt.setBunding(userId + "#" + uipk);
            attchExt.setBoID(boId);
            attchExt.setState(AttachmentState.SAVE);
            attchExt.setSimpleName(oldfileName);
            SHRAttachmentExtFactory.getLocalInstance(ctx).addnew(attchExt);

            BoAttchAssoInfo boAttchAssoInfo = new BoAttchAssoInfo();
            boAttchAssoInfo.setBoID(boId);
            boAttchAssoInfo.setAssoBusObjType(String.valueOf(BOSUuid.getBOSObjectType(boId, true)));
            boAttchAssoInfo.setAssoType("Added Accessories");
            boAttchAssoInfo.setAttachment(ai);
            BoAttchAssoFactory.getLocalInstance(ctx).addnew(boAttchAssoInfo);

        } catch (EASBizException e) {
            e.printStackTrace();
        } catch (BOSException e) {
            e.printStackTrace();
        }
    }


    private static String getFileType(String fullname) {
        String extname = fullname.substring(fullname.lastIndexOf(".") + 1, fullname.length());
        if (!"doc".equalsIgnoreCase(extname) && !"docx".equalsIgnoreCase(extname)) {
            if (!"xls".equalsIgnoreCase(extname) && !"xlsx".equalsIgnoreCase(extname) && !"xlsm".equalsIgnoreCase(extname) && !"xlsb".equalsIgnoreCase(extname)) {
                if (!"ppt".equalsIgnoreCase(extname) && !"pptx".equalsIgnoreCase(extname) && !"pptm".equalsIgnoreCase(extname)) {
                    return "txt".equalsIgnoreCase(extname) ? "TEXT 文本文件" : "未知文件类型(." + extname + ")";
                } else {
                    return "Microsoft PowerPoint 幻灯片";
                }
            } else {
                return "Microsoft Excel 表格";
            }
        } else {
            return "Microsoft Word 文档";
        }
    }


    /***
     * 根据文件下载地址读取字节流
     * @param urlStr
     * @return
     * @throws IOException
     */
    public static byte[] getBytesByNetURL(String urlStr) throws IOException {
//		RestTemplate restTemplate = new RestTemplate();
//		ResponseEntity<byte[]> responseEntity = restTemplate.exchange(urlStr, HttpMethod.GET, null, byte[].class);
//		byte[] fileContent = responseEntity.getBody();
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//		//设置超时时间
        conn.setConnectTimeout(5 * 1000);
//		//通过输入流获取图片数据
        InputStream in = conn.getInputStream();
//		//得到图片的二进制数据
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        in.close();
        return outputStream.toByteArray();
//		return fileContent;
    }

    /**
     * 从路径中提取文件名
     */
    public static String extractFileNameFromPath(String path) {
        return path.substring(path.lastIndexOf('/') + 1);
    }

    /**
     * 提取文件扩展名
     */
    public static String extractFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf('.') + 1);
    }
}
