package yem.wm.cm.htqs.util;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.file.ByteArrayOutputStream;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.ksql.util.StringUtil;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.print.core.service.PrtAttach;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import yem.base.common.utils.YEM;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 工具类。生成对应的附件信息，以及保留附件相关的信息
 */
public class DoPrint {
    /**
     * 更新目标单据的存储内容和附件内容
     *
     * @param bill          目标单据
     * @param billKey       目标单据标识
     * @param fileUid      系统打印生成的文件id
     * @param tplId         系统打印设置id
     * @param type          需要生成的附件类型名称（合同，单签，双签）
     * @return
     */
    public static void uploadFiles(DynamicObject bill, String billKey, String fileUid, String tplId,String type) {
        DynamicObject attachmenttypeSQ = BusinessDataServiceHelper.loadSingle("bos_attachment", "id,ffileid",
                new QFilter[]{new QFilter("fbilltype", QCP.equals, billKey),
                        new QFilter("finterid", QCP.equals, bill.getPkValue().toString()),
                        new QFilter("fnumber", QCP.equals, fileUid)});

        if (attachmenttypeSQ != null) {
            attachmenttypeSQ = BusinessDataServiceHelper.loadSingle(attachmenttypeSQ.getPkValue(),
                    attachmenttypeSQ.getDataEntityType().getName());
            attachmenttypeSQ.set("fdescription", "模板生成");
            SaveServiceHelper.save(new DynamicObject[]{attachmenttypeSQ});
        }

        List<Map<String, Object>> attachs = AttachmentServiceHelper.getAttachments(billKey, bill.getPkValue(),
                "attachmentpanel", false);
        String yem_attachmentcon_tag = bill.getString("yem_attachmentcon_tag");
        JSONObject json = null;
        if (!StringUtil.isEmpty(yem_attachmentcon_tag)) {
            json = JSONObject.parseObject(yem_attachmentcon_tag);
        }
        if (json == null) {
            json = new JSONObject();
        }

        // 获取单据的存储内容和附件内容
        // 更新目标单据的存储内容和附件内容
        List<QFilter> qFilters = new ArrayList<>();

        //统一点打印至附件，生成合同类型文件
        qFilters.add(new QFilter("name", QCP.equals, type));
        qFilters.add(new QFilter("yem_bill.number", QCP.equals, billKey));
        DynamicObject attachmenttype = BusinessDataServiceHelper.loadSingle("yem_bd_attachmenttype", "id",
                qFilters.toArray(new QFilter[]{}));

        List<JSONObject> attList = new ArrayList<>();

        for (Map<String, Object> attachmentData : attachs) {
            String uid = (String) attachmentData.get("uid");// 附件id
            String name = (String) attachmentData.get("name");// 附件名称

            if (uid.equals(fileUid) && attachmenttype != null) {
//                json.put(fileName, attachmenttype.getPkValue());
//                break;
                Map<?, ?> maps = (Map<?, ?>) attachmentData.get("creator");

                JSONObject attJson = json.containsKey(uid) ? json.getJSONObject(uid) : new JSONObject();
                attJson.put("name", name);
                long times = (long) attachmentData.get("createdate");
                Date date = new Date(times);
                attJson.put("createdate", date);
                String lang = YEM.requestContext().getLang().toString();
//                String uid = (String) attachmentData.get("uid");
                attJson.put("uid", uid);
                if (maps != null && maps.containsKey(lang)) {
                    attJson.put("creator", maps.get(lang));
                }
                //保留打印模板Id
                attJson.put("tplId",tplId);
                attJson.put("yem_attachmenttype", attachmenttype.getPkValue());
                json.put(uid, attJson);
                attList.add(attJson);
            }
        }

        bill.set("yem_attachmentcon_tag", json.toJSONString());
        SaveServiceHelper.save(new DynamicObject[]{bill});
    }

    /**
     * 构建附件面板信息
     */
    public static Map<String, Object> createAttInfo(PrtAttach.AttachDetail attachDetail, String billno,String settingName) {

        Map<String, Object> att = new HashMap<String, Object>();
        // 当前时间戳
        long time = new Date().getTime();

        att.put("createdate", time);
        // lastModified:时间戳
        att.put("lastModified", time);
        att.put("status", "success");
        String attType = attachDetail.getFileType();//文件类型
        att.put("type", attType);
        // name:文件名(含文件格式)
        SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
        String date = format.format(new Date());
        att.put("name", billno + date + ".pdf");
        FileService fs = FileServiceFactory.getAttachmentFileService();
        InputStream in = fs.getInputStream(attachDetail.getFilePath());
        try {
            // 附件大小
            byte[] AttByte = InputStreamToByte(in);
            att.put("size", AttByte.length);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        StringBuffer uid = new StringBuffer();
        uid.append("rc-upload-");
        uid.append(time);
        uid.append("-");
        uid.append("1");
        att.put("uid", uid.toString());
        att.put("url", attachDetail.getFilePath());
        return att;
    }

    /**
     * ImputStream输入流转二进制数据
     */
    public static byte[] InputStreamToByte(InputStream in) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = in.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }

}
