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

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.base.attachment.AttachmentFactory;
import com.kingdee.eas.base.attachment.AttachmentInfo;
import com.kingdee.eas.base.attachment.BoAttchAssoFactory;
import com.kingdee.eas.base.attachment.BoAttchAssoInfo;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.hr.emp.IPersonPhoto;
import com.kingdee.eas.hr.emp.PersonPhotoCollection;
import com.kingdee.eas.hr.emp.PersonPhotoFactory;
import com.kingdee.eas.hr.emp.PersonPhotoInfo;
import com.kingdee.shr.attachment.AttachmentState;
import com.kingdee.shr.attachment.AttachmentTypeEnum;
import com.kingdee.shr.attachment.SHRAttachmentExtFactory;
import com.kingdee.shr.attachment.SHRAttachmentExtInfo;

import java.awt.image.BufferedImage;
import java.io.*;


/**
 * Shr附件上传工具类
 *
 * @Classname HRAttachmentUpload
 * @Description TODO
 * @Date 2022/10/26 14:29
 * @Created by Heyuan
 */
public class HRAttachmentUploadUtil {

    /**
     * 将字节数组文件上传到shr系统附件表
     *
     * @param ctx
     * @param byteArray 附件字节数组
     * @param type      文件类型
     * @param fileName  文件标题
     * @param id        单据id
     * @param pk        表单uipk
     * @throws BOSException
     * @throws EASBizException
     */
    public static void uploadAttachment(Context ctx, byte[] byteArray,
                                        String type, String fileName,
                                        String id, String pk, String propertyName) throws BOSException {
        try {
            UserInfo userInfo = (UserInfo) ctx.get("UserInfo");
            String userId = userInfo.getId().toString();
            //附件扩展
            SHRAttachmentExtInfo attchExt = new SHRAttachmentExtInfo();
            AttachmentInfo ai = new AttachmentInfo();//附件
            ai.setName(fileName);//不包含扩展名
            ai.setSimpleName(type);
            ai.setFile(byteArray);
            ai.setIsShared(false);
            ai.setSharedDesc("否");
            ai.setAttachID("" + System.currentTimeMillis());
            ai.setType(type);
            ai.setBeizhu(pk);
            ai.setDescription("附件");
            //ai.setDescription(id);
            //附件扩展
            attchExt.setAttachment(ai);
            attchExt.setName(fileName + "." + type);//包含扩展名
            attchExt.setPropertyName(propertyName);
            attchExt.setType(AttachmentTypeEnum.FORM);
            attchExt.setDescription("");
            attchExt.setBunding(userId + "#" + pk);   //绑定  USERID+"#"  uipk(页面uipk)
            attchExt.setBoID(id);
            attchExt.setState(AttachmentState.SAVE);
            AttachmentFactory.getLocalInstance(ctx).addnew(ai);
            attchExt.setState(AttachmentState.SAVE);
            BoAttchAssoInfo boAttchAssoInfo = new BoAttchAssoInfo();//附件与业务对象关联
            boAttchAssoInfo.setBoID(id);//单据id
            boAttchAssoInfo.setAssoBusObjType(String.valueOf(BOSUuid.getBOSObjectType(id, true)));
            boAttchAssoInfo.setAssoType("Added Accessories");
            boAttchAssoInfo.setAttachment(ai);
            BoAttchAssoFactory.getLocalInstance(ctx).addnew(boAttchAssoInfo);
            SHRAttachmentExtFactory.getLocalInstance(ctx).addnew(attchExt);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BOSException("附件上传报错：" + e.getMessage());
        }

    }

    /**
     * 传服务器文件地址,获取文件上传到shr系统附件表
     *
     * @param context
     * @param type     文件类型
     * @param fileName 文件标题
     * @param id       单据id
     * @param pk       表单uipk
     * @throws BOSException
     * @throws EASBizException
     */
    public static void uploadAttachment(Context context, String filePath, String type, String fileName, String id, String pk) throws BOSException, IOException {
        InputStream is = null;
        ByteArrayOutputStream bos = null;
        try {
            UserInfo userInfo = (UserInfo) context.get("UserInfo");
            String userId = userInfo.getId().toString();
            File file = new File(filePath);
            is = new FileInputStream(file);
            bos = new ByteArrayOutputStream();
            byte[] b = new byte[8096];
            int len = 0;
            while ((len = is.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            byte[] temp = bos.toByteArray();
            //附件扩展
            SHRAttachmentExtInfo attchExt = new SHRAttachmentExtInfo();
            AttachmentInfo ai = new AttachmentInfo();//附件

            ai.setName(fileName);//不包含扩展名
            ai.setSimpleName(type);
            ai.setFile(temp);
            ai.setIsShared(false);
            ai.setSharedDesc("否");
            ai.setAttachID("" + System.currentTimeMillis());
            ai.setType(type);
            ai.setBeizhu(pk);
            ai.setDescription("附件");
            //ai.setDescription(id);
            //附件扩展
            attchExt.setAttachment(ai);

            attchExt.setName(fileName + "." + type);//包含扩展名
            attchExt.setPropertyName("null0");
            attchExt.setType(AttachmentTypeEnum.FORM);
            attchExt.setDescription("");
            attchExt.setBunding(userId + "#" + pk);   //绑定  USERID+"#"  uipk(页面uipk)
            attchExt.setBoID(id);
            attchExt.setState(AttachmentState.SAVE);

            AttachmentFactory.getLocalInstance(context).addnew(ai);
            attchExt.setState(AttachmentState.SAVE);
            BoAttchAssoInfo boAttchAssoInfo = new BoAttchAssoInfo();//附件与业务对象关联
            boAttchAssoInfo.setBoID(id);//单据id
            boAttchAssoInfo.setAssoBusObjType(String.valueOf(BOSUuid.getBOSObjectType(id, true)));
            boAttchAssoInfo.setAssoType("Added Accessories");
            boAttchAssoInfo.setAttachment(ai);
            BoAttchAssoFactory.getLocalInstance(context).addnew(boAttchAssoInfo);
            SHRAttachmentExtFactory.getLocalInstance(context).addnew(attchExt);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BOSException("附件上传报错：" + e.getMessage());
        } finally {
            if (is != null) {
                is.close();
            }
            if (bos != null) {
                bos.close();
            }
        }

    }

    /**
     * 上传员工头像
     *
     * @param context
     * @param person
     * @param imgType
     * @throws BOSException
     * @throws EASBizException
     */
//    public static void uploadPersonHeardPhoto1(Context context, PersonInfo person, String filePath, String imgType) throws BOSException, IOException {
//        InputStream is = null;
//        BufferedImage src = null;
//        ByteArrayOutputStream bos = null;
//        try {
//            File file = new File(filePath);
//            is = new FileInputStream(file);
//            src = javax.imageio.ImageIO.read(is);
//            int height = src.getHeight(null); // 得到源图高
//            int width = src.getWidth(null); // 得到源图宽
//
//            bos = new ByteArrayOutputStream();
//            byte[] b = new byte[8096];
//            int len = 0;
//            while ((len = is.read(b)) != -1) {
//                bos.write(b, 0, len);
//            }
//            byte[] temp = bos.toByteArray();
//            IPersonPhoto localInstance = PersonPhotoFactory.getLocalInstance(context);
//            PersonPhotoCollection personPhotoCollection = localInstance.getPersonPhotoCollection("where person ='" + person.getId().toString() + "'");
//            boolean isUpdate = false;
//            PersonPhotoInfo personPhotoInfo = null;
//            if (personPhotoCollection.size() > 0) {
//                personPhotoInfo = personPhotoCollection.get(0);
//                isUpdate = true;
//            } else {
//                personPhotoInfo = new PersonPhotoInfo();
//            }
//            personPhotoInfo.setPerson(person);
//            personPhotoInfo.setImageData(temp);//照片数据
//            personPhotoInfo.setImageDataSource(temp);//未裁剪的照片数据
//            personPhotoInfo.setSourceImageWidth(width);//原图宽度
//            personPhotoInfo.setSourceImageHeight(height);//原图高度
//            personPhotoInfo.setImageContentType("image/" + imgType);//照片类型
//            if (isUpdate) {
//                localInstance.update(new ObjectUuidPK(personPhotoInfo.getId()), personPhotoInfo);
//            } else {
//                localInstance.save(personPhotoInfo);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BOSException("上传头像失败！" + e.getMessage());
//        } finally {
//            if (is != null) {
//                is.close();
//            }
//            if (bos != null) {
//                bos.close();
//            }
//        }
//    }

    /**
     * 上传员工头像
     *
     * @param context
     * @param person
     * @throws BOSException
     * @throws EASBizException
     */
    public static void uploadPersonHeardPhoto(Context context, PersonInfo person, String filePath, String imgType) throws BOSException, IOException {
        InputStream is = null;
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            is = new FileInputStream(file);
            BufferedImage src = javax.imageio.ImageIO.read(is);
            int height = src.getHeight(null); // 得到源图高
            int width = src.getWidth(null); // 得到源图宽
            //文件转byte[]
            //需要创建两个FileInputStream对象
            fis = new FileInputStream(file);
            byte[] fileBytes = new byte[(int) file.length()];
            fis.read(fileBytes);

            for (int he = 0; he < fileBytes.length; ++he) {
                if (fileBytes[he] < 0) {
                    fileBytes[he] = (byte) (fileBytes[he] + 256);
                }
            }

            IPersonPhoto localInstance = PersonPhotoFactory.getLocalInstance(context);
            PersonPhotoCollection personPhotoCollection = localInstance.getPersonPhotoCollection("where person ='" + person.getId().toString() + "'");
            boolean isUpdate = false;
            PersonPhotoInfo personPhotoInfo = null;
            if (personPhotoCollection.size() > 0) {
                personPhotoInfo = personPhotoCollection.get(0);
                isUpdate = true;
            } else {
                personPhotoInfo = new PersonPhotoInfo();
            }
            personPhotoInfo.setPerson(person);
            personPhotoInfo.setImageData(fileBytes);//照片数据
            personPhotoInfo.setSourceImageWidth(width);//原图宽度
            personPhotoInfo.setSourceImageHeight(height);//原图高度
            personPhotoInfo.setImageContentType("image/" + imgType);//照片类型
            personPhotoInfo.setImageDataSource(fileBytes);//未裁剪的照片数据

            if (isUpdate) {
                localInstance.update(new ObjectUuidPK(personPhotoInfo.getId()), personPhotoInfo);
            } else {
                localInstance.save(personPhotoInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BOSException("上传头像失败！" + e.getMessage());
        } finally {
            if (is != null) {
                is.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }
}
