package nckd.jimin.jyyy.fi.plugin.form;


import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.basedata.BaseDataServiceHelper;
import kd.bos.url.UrlService;
import kd.fi.cas.util.EmptyUtil;
import kd.sdk.plugin.Plugin;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 费用报销单据，通过回单查询插件
 * @author turborao
 * @date 2025/7/3
 */
public class FeiBillFileViewListPlugin extends AbstractListPlugin implements Plugin {

    private static final Log logger = LogFactory.getLog(FeiBillFileViewListPlugin.class);
    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String opKey = e.getOperateKey();

        if ("elecreceipt".equalsIgnoreCase(opKey)) {
            ListSelectedRowCollection selectedRows = this.getSelectedRows();
            Object selectId = selectedRows.get(0).getPrimaryKeyValue();

            OperationResult operationResult = e.getOperationResult();
            if (operationResult.isSuccess()) {
                logger.info("-- 报销单联查电子回单附件开始 --");
                if(EmptyUtil.isNoEmpty(selectId)){
                    Map<String,Object>  fileMap = getElecreceiptByFile(selectId.toString());
                    if (fileMap == null) {
                        this.getView().showSuccessNotification("没有相应的电子回单！");
                        return ;
                    }
                    this.getView().previewAttachment(fileMap);
                }
            }
        }
    }


    /**
     * 获取电子回单ID
     * 通过付款单ID获取交易明细ID，再通过交易明细ID获取电子回单ID
     * @param payBillId
     * @return
     */
    public Map<String,Object> getElecreceiptByFile(String payBillId){
        Long billId = Long.parseLong(payBillId);
        QFilter qf = new QFilter("sourcebillid", QCP.equals, billId);
        //QFilter qf11 =  QFilter.isNotNull("detailseqid");
        QFilter qf11 = new QFilter("detailseqid", QCP.not_equals, " ");
        DynamicObject[] billDyns = BusinessDataServiceHelper.load("cas_paybill","id,detailseqid", new QFilter[]{qf,qf11});
        if(EmptyUtil.isEmpty(billDyns)) return null;
        List<String> transdetailIds = Arrays.stream(billDyns)
                .map(dyn -> dyn.getString("detailseqid"))
                .collect(Collectors.toList());
        if(transdetailIds.size() == 0) return null;
        QFilter qf1 = new QFilter("billno", QCP.in, transdetailIds);
        DynamicObject[] transdetailDyns = BusinessDataServiceHelper.load("bei_transdetail","id,receiptno", new QFilter[]{qf1});
        if(EmptyUtil.isEmpty(transdetailDyns)) return null;
        String elecreceiptNo = transdetailDyns[0].getString("receiptno");
        QFilter qf2 = new QFilter("receiptno", QCP.equals, elecreceiptNo);
        DynamicObject elecreceiptDyn = BusinessDataServiceHelper.loadSingle("bei_elecreceipt", new QFilter[]{qf2});

        if(EmptyUtil.isEmpty(elecreceiptDyn)) return null;
        Map<String, Object> attachmentMap = getAttachmentFile(elecreceiptDyn.getLong("id"));

        if(attachmentMap == null) return null;
        String filepath = elecreceiptDyn.getString("filepath");
        /**
         * 获取持久化附件的预览url
         * @param path 持久化附件的downloadUrl相对路径
         * @return 持久化附件的预览url
         *  入参示例： /tenant_devcore_dev/1402323749146986496/202305/1683569603244172288/5b3c272f9d5a42fdbecddf2d84bcdd56/Wo rd文档.docx
         */
        String previewUrl = UrlService.getAttachmentPreviewUrl(filepath);
        String downloadUrl = UrlService.getAttachmentDownloadUrl(filepath);
        //previewUrl = previewUrl.replace("http://127.0.0.1:8881","https://d-kd.jeyoupharma.com:8022");
        //downloadUrl = downloadUrl.replace("http://127.0.0.1:8881","https://d-kd.jeyoupharma.com:8022");

        Map<String,Object> attMap = new HashMap<>();
        attMap.put("previewurl",previewUrl);
        attMap.put("url",downloadUrl);
        attMap.put("uid",attachmentMap.get("uid"));
        attMap.put("type", attachmentMap.get("type"));
        attMap.put("name",attachmentMap.get("name"));
        attMap.put("size", attachmentMap.get("size"));
        attMap.put("status","success");
        attMap.put("visible","1000");

        return attMap;
    }


    public static Map<String, Object>  getAttachmentFile(Long billId) {

        //创建一条基础资料数据-附件字段
        //获取单据信息，并查询单据中的附件字段
        QFilter qf = new QFilter("id", QCP.equals, billId);
        DynamicObject file =BusinessDataServiceHelper.loadSingle("bei_elecreceipt", "attachmentpanel",new QFilter[]{qf});
        //获取单据中附件面板信息
        List<Map<String, Object>> atts = AttachmentServiceHelper.getAttachments("bei_elecreceipt", file.getPkValue().toString(), "attachmentpanel");
        //遍历文件   电子回单只有一条
        for (Map<String, Object>  att: atts) {
            return att;
        }
        return null;
    }


}