package com.yem.tws.chart;

import com.yem.tws.common1.StringUtils;
import kd.bos.context.RequestContext;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.control.Label;
import kd.bos.form.control.ProgressBar;
import kd.bos.form.control.events.ProgressEvent;
import kd.bos.form.control.events.ProgresssListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.mvc.cache.PageCache;
import kd.bos.threads.ThreadPool;
import kd.bos.threads.ThreadPools;

import java.math.BigDecimal;
import java.util.EventObject;

/**
 * @author zhouc
 * @date 2023/9/9 15:48
 * @className AvailabilityEdit
 * @description 授信可用率图表插件
 */
public class AvailabilityEdit extends AbstractFormPlugin implements ProgresssListener {

    private final static String KEY_PROGRESSBAR = "yem_progressbarap";

    public final static String CACHEKEY_PROGRESS = "progress";
    public final static String CACHEKEY_STARTPROPGRESS = "startprogress";
    private static ThreadPool threadPool = ThreadPools.newFixedThreadPool("AvailabilityEdit", 1);

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        IDataModel model = this.getModel();
        String yem_sumamoun = (String) model.getValue("yem_sumamoun");
        String yem_occupyamt = (String) model.getValue("yem_occupyamt");
        String yem_colour = (String) model.getValue("yem_colour");

        Label yem_labelap2 = this.getControl("yem_labelap2");
        yem_labelap2.setText(yem_sumamoun.toString());
        Label yem_labelap3 = this.getControl("yem_labelap3");
        yem_labelap3.setText(yem_occupyamt.toString());
        start();
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        ProgressBar progressBar = this.getView().getControl(KEY_PROGRESSBAR);
        progressBar.addProgressListener(this);
//        this.addClickListeners(KEY_BTNSTART, KEY_BTNSTOP);
    }

    /**
     * 开始进度
     */
    private void start() {
        // 设置当前进度
        ProgressBar progressBar = this.getView().getControl(KEY_PROGRESSBAR);
        progressBar.start();
        // 标记任务已经开始
        this.getPageCache().put(CACHEKEY_STARTPROPGRESS, "true");
        this.getPageCache().put(CACHEKEY_PROGRESS, "0");

        // 启动异步进程，执行任务，在任务中随时更新进度
        Task myTask = new Task(RequestContext.get(), this.getView().getPageId());
        threadPool.execute(myTask);
    }

    /**
     * 停止进度
     */
    private void stop() {
        // 更新缓存中的任务启动标志 = false：异步任务进程会定时读取这个标志，停止任务
        this.getPageCache().put(CACHEKEY_STARTPROPGRESS, "false");
    }

    @Override
    public void onProgress(ProgressEvent arg0) {
        IDataModel model = this.getModel();
        String yem_sumamoun = (String) model.getValue("yem_sumamoun");
        String yem_occupyamt = (String) model.getValue("yem_occupyamt");
        String startProgress = this.getPageCache().get(CACHEKEY_STARTPROPGRESS);
        if (StringUtils.isBlank(startProgress)) {
            // 未开始：设置进度为0
            arg0.setProgress(0);
            return;
        }
        int progress = 0;
        // 取缓存的进度：由后台任务更新
        String cacheProgress = this.getPageCache().get(CACHEKEY_PROGRESS);
        if (StringUtils.isNotEmpty(cacheProgress)) {
            progress = getProgress(yem_sumamoun,yem_occupyamt);
        }
        if (progress >= 100) {
            progress = 99;
            stop();
        }
        if (startProgress.equals("false")) {
        }
        arg0.setProgress(progress);
    }

    public int getProgress(String yem_sumamoun, String yem_occupyamt) {
        //获取当前登录组织
        int progress = 0;
        BigDecimal maerialRat = new BigDecimal(yem_occupyamt).divide(new BigDecimal(yem_sumamoun)).multiply(new BigDecimal(100));
        String bd1 = maerialRat.setScale(0, BigDecimal.ROUND_HALF_UP).toString();
        progress = Integer.valueOf(bd1).intValue();
        return progress;
    }
}

/**
 * 异步任务
 *
 * @author rd_JohnnyDing
 */
class Task implements Runnable {

    private RequestContext rc;
    String pageId;

    public Task(RequestContext rc, String pageId) {
        this.rc = rc;
        this.pageId = pageId;
    }

    @Override
    public void run() {

        // 设置登录上下文，否则无法访问数据库
        RequestContext.set(rc);

        this.doTask();
    }

    private void doTask() {

        int progress = 0;

        while (progress < 100) {
            // 暂停100ms
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 刷新进度，写入缓存中：其他进程会从缓存中定时(1s)读取进度
            progress++;

            // 把最新的进度推送到页面缓存中
            PageCache pageCache = new PageCache(this.pageId);
            pageCache.put(CustomsErrorRate.CACHEKEY_PROGRESS, String.valueOf(progress));

            // 如果主线程，要求停止任务，则主动终止循环
            if (isStop(pageCache)) {
                break;
            }
        }
    }

    private boolean isStop(PageCache pageCache) {
        String startProgress = pageCache.get(CustomsErrorRate.CACHEKEY_STARTPROPGRESS);
        return (StringUtils.isNotEmpty(startProgress)
                && startProgress.equals("false"));
    }

}
