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

import kd.bos.bill.BillShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.list.BillList;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.ORM;
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.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.bos.url.UrlService;
import kd.bos.util.StringUtils;
import kd.fi.cas.util.EmptyUtil;
import kd.sdk.plugin.Plugin;

import java.util.*;

/**
 * 改造付款单列表查询 查询银行回单、交易明细
 *
 * @author turborao
 * @date 2025/6/3
 */
public class PayBillSearchListPlugin extends AbstractListPlugin implements Plugin {

    private static final Log logger = LogFactory.getLog(PayBillSearchListPlugin.class);
    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args) {
        super.afterDoOperation(args);
        String operateKey = args.getOperateKey();
        OperationResult operationResult = args.getOperationResult();

        BillList billList = (BillList)this.getControl("billlistap");
        ListSelectedRowCollection selectedRows = billList.getSelectedRows();
        List<Object> payBillIdList = null;
        if (!selectedRows.isEmpty()) {
            payBillIdList = Arrays.asList(selectedRows.getPrimaryKeyValues());
            logger.info("选中付款单ID:" + payBillIdList);
        }else{
            return;
        }
        BillShowParameter showParameter = new BillShowParameter();
        if (operationResult != null && operationResult.isSuccess() && "transdetail".equals(operateKey)) {
            logger.info("-- 付款单联查交易明细开始 --");
            if(EmptyUtil.isNoEmpty(payBillIdList)){
                String billId = payBillIdList.get(0).toString();
                Long  tranbillId = getTransdetailID(billId);
                String formId= "bei_transdetail";
                showParameter.setFormId(formId);
                showParameter.setPkId(tranbillId);
                showParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                showParameter.setStatus(OperationStatus.VIEW);
                this.getView().showForm(showParameter);
            }
        }
        if (operationResult != null && operationResult.isSuccess() && "elecreceipt".equals(operateKey)) {
            logger.info("-- 付款单联查电子回单附件开始 --");
            if(EmptyUtil.isNoEmpty(payBillIdList)){
                String billId = payBillIdList.get(0).toString();
                Map<String,Object>  fileMap = getElecreceiptByFile(billId);
                if (fileMap == null) {
                    this.getView().showSuccessNotification("没有相应的电子回单！");
                    return ;
                }
                this.getView().previewAttachment(fileMap);
            }
        }
    }


    public Long getTransdetailID(String payBillId){
        Long billId = Long.parseLong(payBillId);
        QFilter qf = new QFilter("id", QCP.equals, billId);
        DynamicObject billDyn = BusinessDataServiceHelper.loadSingle("cas_paybill", new QFilter[]{qf});
        String transdetailId = billDyn.getString("detailseqid");
        QFilter qf1 = new QFilter("billno", QCP.equals, transdetailId);
        DynamicObject transdetailDyn = BusinessDataServiceHelper.loadSingle("bei_transdetail", new QFilter[]{qf1});
        return transdetailDyn.getLong("id");
    }

    /**
     * 获取电子回单ID
     * 通过付款单ID获取交易明细ID，再通过交易明细ID获取电子回单ID
     * @param payBillId
     * @return
     */
    public Map<String,Object> getElecreceiptByFile(String payBillId){
        Long billId = Long.parseLong(payBillId);
        QFilter qf = new QFilter("id", QCP.equals, billId);
        DynamicObject billDyn = BusinessDataServiceHelper.loadSingle("cas_paybill", new QFilter[]{qf});
        String transdetailId = billDyn.getString("detailseqid");
        if(StringUtils.isEmpty(transdetailId)) return null;
        QFilter qf1 = new QFilter("billno", QCP.equals, transdetailId);
        DynamicObject transdetailDyn = BusinessDataServiceHelper.loadSingle("bei_transdetail", new QFilter[]{qf1});
        if(EmptyUtil.isEmpty(transdetailDyn)) return null;
        String elecreceiptNo = transdetailDyn.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;
    }
}