package yem.base.common.module.meta.api;

import com.alibaba.fastjson.JSONObject;
import kd.bos.algo.DataSet;
import kd.bos.bill.AbstractBillWebApiPlugin;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.metadata.clr.DataEntityPropertyCollection;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.entity.api.ApiResult;
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.sdk.plugin.Plugin;
import yem.base.common.module.meta.report.DataDictionaryRptQuery;
import yem.base.common.utils.YEM;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * @author longh
 * @description 数据查询接口（api 1.0）
 * @date 2023年12月27日
 */
public class BillDataGetApi extends AbstractBillWebApiPlugin implements Plugin {

    @Override
    public ApiResult doCustomService(Map<String, Object> params) {
        String billKey = (String) params.get("billKey");
        Long billId = (Long) params.get("billId");
        String billno = (String) params.get("billno");
        Boolean attach = (Boolean) params.getOrDefault("attach", false);
        Boolean token = (Boolean) params.getOrDefault("token", true);
        Boolean base64 = (Boolean) params.getOrDefault("base64", false);
        String attachKey = (String) params.getOrDefault("attachKey", "attachmentpanel");
        if (YEM.isEmpty(billKey)) {
            return ApiResult.fail("【billKey】单据标识参数未传");
        }
        if (YEM.isNotEmpty(billno) || YEM.isNotEmpty(billId)) {
            DynamicObject bill;
            if (YEM.isNotEmpty(billId) && billId > 0) {
                bill = BusinessDataServiceHelper.loadSingle(billId, billKey);
            } else {
                bill = BusinessDataServiceHelper.loadSingle(billKey, "id", new QFilter("billno", QCP.equals, billno).toArray());
                if (bill != null) {
                    bill = BusinessDataServiceHelper.loadSingle(bill.getPkValue(), billKey);
                }
            }
            if (bill != null) {
                if (attach) {
                    List<Map<String, Object>> attachments = AttachmentServiceHelper.getAttachments(billKey, bill.getPkValue(), attachKey, token);
                    if (base64) {
                        for (Map<String, Object> attachment : attachments) {
                            String url = (String) attachment.get("url");
                            String base64Str = getBase64Str(url);
                            attachment.put("base64", base64Str);
                        }
                    }
                    return ApiResult.success(attachments);
                }
                String billJson = SerializationUtils.toJsonString(bill);
                return ApiResult.success(JSONObject.parseObject(billJson));
            } else {
                return ApiResult.fail("未查询到数据");
            }
        }
        DataSet dataSet = DataDictionaryRptQuery.queryDataBill(billKey);
        DynamicObjectCollection dynamicObjects = ORM.create().toPlainDynamicObjectCollection(dataSet);
        List<Map<String, Object>> allData = new ArrayList<>();
        for (DynamicObject obj : dynamicObjects) {
            Map<String, Object> map = new HashMap<>();
            DataEntityPropertyCollection properties = obj.getDynamicObjectType().getProperties();
            for (IDataEntityProperty property : properties) {
                String key = property.getName();
                map.put(key, obj.get(key));
            }
            allData.add(map);
        }
        return ApiResult.success(allData);
    }

    private String getBase64Str(String url) {
        String base64Str = "";
        if (YEM.isNotEmpty(url)) {
            try {
                URLConnection urlConnection = new URL(url).openConnection();
                HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setConnectTimeout(1000 * 5);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
                httpURLConnection.setRequestProperty("Charset", "UTF-8");
                httpURLConnection.connect();
                InputStream inputStream = httpURLConnection.getInputStream();
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, length);
                }
                byte[] bytes = outputStream.toByteArray();
                base64Str = Base64.getEncoder().encodeToString(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return base64Str;
    }

}