package yem.wmc.ca.chart;


import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
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.mvc.cache.PageCache;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.threads.ThreadPool;
import kd.bos.threads.ThreadPools;
import yem.wmc.ca.utils.DateUtils;
import yem.wmc.ca.utils.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.EventObject;

/**
 * @author zhouc
 * @date 2023/7/10 14:26
 * @className CustomsErrorRate
 * @description 报关差错率图表取数插件
 */
public class CustomsErrorRate extends AbstractBillPlugIn implements ProgresssListener {
    private final static String KEY_PROGRESSBAR = "yem_errorrate";

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

    @Override
    public void afterCreateNewData(EventObject e) {
        //获取当前登录组织
        long userOrgid = RequestContext.get().getOrgId();
        //1.查询删单数据 申请单类型=撤销申请//删单  yem_decmodtypename yem_ca_repairnote
        QFilter deletqFilter = new QFilter("yem_decmodtypename", QCP.equals, "撤销申请");
        deletqFilter.and(new QFilter("org.id", "=", userOrgid));
        DynamicObject[] deleterepairnote = BusinessDataServiceHelper.load("yem_ca_repairnote",
                "id,billno", new QFilter[]{deletqFilter}, null);
        if (deleterepairnote.length > 0) {
            ((Label) this.getControl("yem_deletemonad")).setText(String.valueOf(deleterepairnote.length));
        }
        //2.查询改单数据 申请单类型=修改申请//改单
        QFilter changeqFilter = new QFilter("yem_decmodtypename", QCP.equals, "修改申请");
        changeqFilter.and(new QFilter("org.id", "=", userOrgid));
        DynamicObject[] changerepairnote = BusinessDataServiceHelper.load("yem_ca_repairnote",
                "id,billno", new QFilter[]{changeqFilter}, null);
        if (changerepairnote.length > 0) {
            ((Label) this.getControl("yem_changemonad")).setText(String.valueOf(changerepairnote.length));
        }
        ((Label) this.getControl("yem_totalerror")).setText(String.valueOf(deleterepairnote.length + changerepairnote.length));
        start();
    }

    @Override
    public void onProgress(ProgressEvent arg0) {
        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();
        }
        if (progress >= 100) {
            progress = 99;
            stop();
        }
        if (startProgress.equals("false")) {
        }
        arg0.setProgress(progress);
    }

    public int getProgress() {
        //获取当前登录组织
        long userOrgid = RequestContext.get().getOrgId();
        //1.获取当前第一天与最后一天
        Date StartDate = DateUtils.getCurrentFirstOfYear();
        Date EndDate = DateUtils.getCurrentLastOfYear();
        int progress = 0;
        //1.查询报关单当年总数
        QFilter cusdecqFilter = new QFilter("org.id", "=", userOrgid);
        cusdecqFilter.and(new QFilter("yem_fddatets", ">=", StartDate));
        cusdecqFilter.and(new QFilter("yem_fddatets", "<=", EndDate));
        DynamicObject[] cusdec = BusinessDataServiceHelper.load("yem_ca_cusdec",
                "id,billno,yem_entryid", new QFilter[]{cusdecqFilter}, null);//报关单
        if (cusdec.length > 0) {
            int sumcusdec = cusdec.length;
            //2.查询修撤单当年总数（包含删单、改单）
            QFilter repairqFilter = new QFilter("org.id", "=", userOrgid);
            repairqFilter.and(new QFilter("yem_ddate", ">=", StartDate));
            repairqFilter.and(new QFilter("yem_ddate", "<=", EndDate));
            DynamicObject[] repairnote = BusinessDataServiceHelper.load("yem_ca_repairnote",
                    "id,billno,yem_decmodtypename", new QFilter[]{repairqFilter}, null);//修撤单
            if (repairnote.length > 0) {
                int sumrepairnote = repairnote.length;
                DecimalFormat df = new DecimalFormat("0.00");
                String maerialRatio = df.format((float) sumrepairnote / (float)sumcusdec * 100);
                BigDecimal maerialRat=new BigDecimal(maerialRatio);
                String bd1 = maerialRat.setScale(0, BigDecimal.ROUND_HALF_UP).toString();
                progress =Integer.valueOf(bd1).intValue();
            }
        }
        return progress;
    }

    @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");

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

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

    private RequestContext rc;
    String pageId;

    public MyTask(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"));
    }

}
