package yem.wm.cm.htqs.form;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.github.dreamhead.moco.resource.ResourceReader;
import kd.bos.ext.form.control.CustomControl;
import kd.bos.form.events.CustomEventArgs;
import kd.bos.form.plugin.AbstractFormPlugin;

/**
 * 手动签署页面的插件
 */

public class SignClientEdit extends AbstractFormPlugin {

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        initData();
    }

    private void initData() {
        Map<String, Object> dataMap = new HashMap<>();
        // dataMap.put("pdfUrl", "");

        String content = "";

        try {
            InputStream fis= ResourceReader.class.getClassLoader().getResourceAsStream("s.txt");
            byte[] buffer = new byte[10];
            StringBuilder sb = new StringBuilder();
            while (fis.read(buffer) != -1) {
                sb.append(new String(buffer));
                buffer = new byte[10];
            }
            fis.close();
            content = sb.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        dataMap.put("base64", content);
        CustomControl customcontrol = this.getView().getControl("yem_customcontrolap");
        customcontrol.setData(dataMap);
    }

    @Override
    public void customEvent(CustomEventArgs e) {
        super.customEvent(e);
        String key = e.getKey();
        String eventName = e.getEventName();
        String eventArgs = e.getEventArgs();
        if ("yem_customcontrolap".equals(key) && "confirmSign".equals(eventName)) {
            String positionInfo = eventArgs;
            JSONArray parseArray = JSON.parseArray(eventArgs);
            if (parseArray != null && parseArray.size() > 0) {
                JSONArray jsonArray = parseArray.getJSONArray(0);
                if (jsonArray != null && jsonArray.size() > 0) {
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    if (jsonObject != null) {
                        jsonObject.remove("sealImage");
                        positionInfo = jsonObject.toJSONString();
                    }
                }
            }
            this.getView().showMessage(positionInfo);
        }
    }

}
