package nckd.base.helper;


import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.ext.fi.bei.util.EmptyUtil;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.list.BillList;
import kd.bos.list.IListView;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.metadata.dao.MetaCategory;
import kd.bos.metadata.dao.MetadataDao;
import kd.bos.metadata.form.ControlAp;
import kd.bos.metadata.form.FormMetadata;
import kd.bos.metadata.form.control.AttachmentPanelAp;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.util.StringUtils;
import kd.sdk.plugin.Plugin;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 标准单据列表插件
 */
public class AttachmentDownloadListPlugin extends AbstractListPlugin implements Plugin {
    private static final Log logger = LogFactory.getLog(AttachmentDownloadListPlugin.class);

    public void afterDoOperation(AfterDoOperationEventArgs args) {
        super.afterDoOperation(args);
        String operateKey = args.getOperateKey();
        OperationResult operationResult = args.getOperationResult();

        BillList billList = (BillList)this.getControl("billlistap");
        String billForm = ((IListView)this.getView()).getBillFormId();
        String attForm = getAttachmentPanelName(billForm);
        ListSelectedRowCollection selectedRows = billList.getSelectedRows();
        Object billid = null;
        if (!selectedRows.isEmpty()) {
            if(selectedRows.size() > 1 ){
                this.getView().showErrorNotification("请选择一条数据！");
                return;
            }
            List<Object>  payBillIdList = Arrays.asList(selectedRows.getPrimaryKeyValues());
            billid = payBillIdList.get(0);
        }else{
            return;
        }

        if (operationResult != null && operationResult.isSuccess() && "downloadfile".equals(operateKey)) {

            if (StringUtils.isEmpty(attForm) && EmptyUtil.isEmpty(billid)) {
                this.getView().showErrorNotification("没有附件可下载！");
                return;
            }
            List<Map<String, Object>> list = AttachmentServiceHelper.getAttachments(billForm, billid, attForm);

            for (Map map : list) {
                //String url = map.get("url").toString();//获取到url
                String realUrl = map.get("relativeUrl").toString();
                String filename = map.get("name").toString();
                logger.info("SEC relativeUrl:" + realUrl);
                FileService fileService = FileServiceFactory.getAttachmentFileService();
                //String path = FileServiceExtFactory.getAttachFileServiceExt().getRealPath(realUrl);
                logger.info("SEC path:" + filename);
                InputStream inputStream = fileService.getInputStream(realUrl);
                //String filePath = "C:\\Users\\turbo_i49t4d3\\Downloads\\副本经理人周会数据.xlsx";
                //File file = new File(filePath);
                //InputStream inputStream = new FileInputStream(filePath);
                String downloadUrl = FileSECUtils.getFileUrlByEncodeSEC(filename, inputStream);
                logger.info("SEC downloadUrl:" + downloadUrl);
                this.getView().download(downloadUrl);
            }
        }

    }


    public String getAttachmentPanelName(String billformId ) {
        MainEntityType entityType = EntityMetadataCache.getDataEntityType(billformId);
        FormMetadata taskMeta = (FormMetadata) MetadataDao.readRuntimeMeta(MetadataDao.getIdByNumber(entityType.getName(), MetaCategory.Form), MetaCategory.Form);
        // 元数据所有字段内容
        List<ControlAp<?>> items = taskMeta.getItems();
        for (ControlAp<?> item: items) {
            // 判断元素类型是否是附件面板控件
            if (item instanceof AttachmentPanelAp) {
                String key = item.getKey();
                return key;
            }
        }
        return null;
    }

}