package yem.base.common.module.attach.util;


import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.control.AttachmentPanel;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
 * 附件工具类
 * @BelongsProject: yem-cosmic
 * @BelongsPackage: yem.base.common.utils
 * @ClassName AccessoryToolsUtil
 * @Author: LiuHB
 * @CreateTime: 2025-01-14  17:15
 */
public class AccessoryToolsUtil {

    /**
     * @param form
     * @param attachmentpanelKey
     * @Description 增加/更新附件
     */
    public static void addAttachmentContext(AbstractBillPlugIn form,  List<String> attachmentpanelKey) {

        for (String s : attachmentpanelKey) {

            attachmentForm(form,"yem_attachmentdetail", s);
        }
    }

    /**
     * @param form
     * @param attachmentpanelKey
     * @Description 删除附件
     */
    public static void removeAttachmentContext(AbstractBillPlugIn form,  List<String> attachmentpanelKey) {
        Set<String> urlSet = new HashSet<>();
        for (String s : attachmentpanelKey) {
            AttachmentPanel attachmentpanel = form.getView().getControl(s);
            List<Map<String, Object>> attachmentDatas = attachmentpanel.getAttachmentData();
            for (Map<String, Object> attachmentData : attachmentDatas) {
                String uid = (String) attachmentData.get("uid");
                urlSet.add(uid);
            }
        }
        //附件分录
        DynamicObjectCollection attachmentDetail = form.getView().getModel()
                .getDataEntity(true).
                getDynamicObjectCollection("yem_attachmentdetail");
        // 找出需要删除的记录（在urld中有但在urls中没有的记录）
        List<Integer> toDelete = new ArrayList<>();
        for (int i = 0; i < attachmentDetail.size(); i++) {
            DynamicObject attachment = attachmentDetail.get(i);
            String url = attachment.getString("yem_uid");
            if (!urlSet.contains(url)) {
                toDelete.add(i);
            }
        }
        if (!toDelete.isEmpty()) {
            int[] array = toDelete.stream().mapToInt(Integer::intValue).toArray();
            form.getView().getModel().deleteEntryRows("yem_attachmentdetail", array);
        }
    }

    /**
     * @param form
     * @param entityName
     * @Description 附件表格赋值
     */
    public static void attachmentForm(AbstractBillPlugIn form,  String entityName, String attachmentpanelKey) {
        Map<String, Map<String, Object>> attachmentMap = buildAttachmentMap(form, attachmentpanelKey);
        DynamicObjectCollection attachmentDetail = form.getView().getModel().getDataEntity(true).getDynamicObjectCollection(entityName);
        String billno = (String) form.getView().getModel().getValue("billno");

        // 获取现有的 UID 列表
        Set<String> existingUids = attachmentDetail.stream()
                .map(detail -> detail.getString("yem_uid"))
                .collect(Collectors.toSet());

        // 处理每个附件
        attachmentMap.forEach((uid, value) -> {
            if (existingUids.contains(uid)) {
                updateExistingAttachment(form, attachmentDetail, uid, value, billno, attachmentpanelKey);
            } else {
                createNewAttachment(form, entityName, uid, value, billno, attachmentpanelKey);
            }
        });
    }

    /**
     * @param form
     * @param attachmentpanelKey
     * @return
     * @Description 构建附件map
     */
    private static Map<String, Map<String, Object>> buildAttachmentMap(AbstractBillPlugIn form, String attachmentpanelKey) {
        Map<String, Map<String, Object>> attachmentMap = new HashMap<>();
        AttachmentPanel attachmentPanel = form.getView().getControl(attachmentpanelKey);
        List<Map<String, Object>> attachmentDatas = attachmentPanel.getAttachmentData();

        for (Map<String, Object> attachmentData : attachmentDatas) {
            String uid = (String) attachmentData.get("uid");
            String name = (String) attachmentData.get("name");
            String url = (String) attachmentData.get("url");
            Long createTime = (Long) attachmentData.get("createdate");

            // 格式化时间
            String formattedTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(createTime));

            // 获取创建人
            @SuppressWarnings("unchecked")
            Map<String, Object> creator = (Map<String, Object>) attachmentData.get("creator");
            String creatorName = creator != null ? (String) creator.get("zh_CN") : null;

            // 存储数据
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("name", name);
            dataMap.put("url", url);
            dataMap.put("createTime", formattedTime);
            dataMap.put("creator", creatorName);
            attachmentMap.put(uid, dataMap);
        }
        return attachmentMap;
    }

    /**
     * @param form
     * @param attachmentDetail
     * @param uid
     * @param data
     * @param billno
     * @param attachmentpanelKey
     * @Description 更新附件行
     */
    private static void updateExistingAttachment(AbstractBillPlugIn form, DynamicObjectCollection attachmentDetail,
                                                 String uid, Map<String, Object> data, String billno,
                                                 String attachmentpanelKey) {
        for (DynamicObject attachment : attachmentDetail) {
            if (uid.equals(attachment.getString("yem_uid"))) {
                int rowIndex = attachmentDetail.indexOf(attachment);
                setAttachmentValues(form, rowIndex, uid, data, billno, attachmentpanelKey);
                break;
            }
        }
    }

    /**
     *
     * @param form
     * @param entityName
     * @param uid
     * @param data
     * @param billno
     * @param attachmentpanelKey
     * @Description 增加新附件行
     */
    private static void createNewAttachment(AbstractBillPlugIn form, String entityName, String uid,
                                            Map<String, Object> data, String billno,
                                            String attachmentpanelKey) {
        int newRow = form.getView().getModel().createNewEntryRow(entityName);
        setAttachmentValues(form, newRow, uid, data, billno, attachmentpanelKey);
    }

    /**
     * @param form
     * @param row
     * @param uid
     * @param data
     * @param billno
     * @param attachmentpanelKey
     * @Description 附件分录赋值
     */
    private static void setAttachmentValues(AbstractBillPlugIn form, int row, String uid,
                                            Map<String, Object> data, String billno,
                                            String attachmentpanelKey) {
        form.getView().getModel().setValue("yem_attachmentname", data.get("name"), row);
        form.getView().getModel().setValue("yem_url", data.get("url"), row);
        form.getView().getModel().setValue("yem_panel", attachmentpanelKey, row);
        form.getView().getModel().setValue("yem_billno", billno, row);
        form.getView().getModel().setValue("yem_uid", uid, row);
        form.getView().getModel().setValue("yem_uploaddate", data.get("createTime"), row);
        form.getView().getModel().setValue("yem_creator", data.get("creator"), row);
    }
}
