package baseclass;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.krysalis.barcode4j.impl.upcean.EAN13Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;
import p2.application.doclink.Doclinks;
import p2.p2server.P2Server;
import p2.pao.PaoRemote;
import p2.pao.PaoSetRemote;
import p2.util.P2AppException;
import p2.util.P2Exception;
import p2.webclient.system.beans.AppBean;
import p2.webclient.system.beans.DataBean;
import p2.webclient.system.controller.RequestHandler;
import p2.webclient.system.controller.UploadFile;
import p2.webclient.system.controller.Utility;
import p2.webclient.system.controller.WebClientEvent;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;

public class AppBeanCust extends AppBean {

    public void byrefresh() {
        this.reloadTable();
        this.refreshTable();
        this.sessionContext.queueRefreshEvent();
    }

    public boolean msgDialogIsNotOpen()  {
        return sessionContext.getCurrentEvent().getMessageReturn() == -1;
    }

    public void msgDialogOpen(String msg) throws P2Exception {
        // 弹出确认对话框
        throw new P2AppException("system", "comwarm", new String[]{msg});
    }

    public boolean msgDialogIsCheckOk()  {
        return sessionContext.getCurrentEvent().getMessageReturn() == 8;
    }

    public void dialogClose()  {
        Utility.sendEvent(new WebClientEvent("dialogclose", this.app.getCurrentPageId(), null, this.sessionContext));
    }

    public void dialogOpen(String dialogid) {
        // 弹出dialog
        RequestHandler.showDialog(this.sessionContext, dialogid);
    }

    /**
     * 启用
     *
     * @return
     * @throws P2Exception
     */
    public int USED() throws P2Exception {
        return 1;
    }

    /**
     * 停用
     *
     * @return
     * @throws P2Exception
     */
    public int UNUSED() throws P2Exception {
        return 1;
    }

    /**
     * 红冲
     *
     * @return
     * @throws P2Exception
     */
    public int HONG() throws P2Exception {
        PaoCust paoCust = (PaoCust) getPao();
        paoCust.hongvalidate();
        moveToUniqueId(paoCust.hong().getUniqueIDValue());
        return 1;
    }

    /**
     * 审核
     *
     * @return
     * @throws P2Exception
     */
    public int CHECK() throws P2Exception {
        return 1;
    }

    /**
     * 反审核
     *
     * @return
     * @throws P2Exception
     */
    public int UNCHECK() throws P2Exception {
        return 1;
    }

    /**
     * 复核
     *
     * @return
     * @throws P2Exception
     */
    public int RECHECK() throws P2Exception {
        return 1;
    }

    /**
     * 反复核
     *
     * @return
     * @throws P2Exception
     */
    public int UNRECHECK() throws P2Exception {
        return 1;
    }

    /**
     * 提交
     *
     * @return
     * @throws P2Exception
     */
    public int SUBMIT() throws P2Exception {
        return 1;
    }

    /**
     * 反提交
     *
     * @return
     * @throws P2Exception
     */
    public int UNSUBMIT() throws P2Exception {
        return 1;
    }

    /**
     * 确认
     *
     * @return
     * @throws P2Exception
     */
    public int CONFIRM() throws P2Exception {
        return 1;
    }

    /**
     * 反确认
     *
     * @return
     * @throws P2Exception
     */
    public int UNCONFIRM() throws P2Exception {
        return 1;
    }

    /**
     * 关闭
     *
     * @return
     * @throws P2Exception
     */
    public int CLOSE() throws P2Exception {
        return 1;
    }

    /**
     * 复制
     */
    @Override
    public int DUPLICATE() throws P2Exception {
        return super.DUPLICATE();
    }

    public int CloseApp() throws P2Exception {
        Utility.sendEvent(new WebClientEvent("closeappwin", app.getApp().toLowerCase(), app.getApp().toLowerCase(), "",
                "", 0, sessionContext));
        return 1;
    }

    /**
     * 打开一个网址连接
     *
     * @return
     * @throws P2Exception
     */
    public void OPENURL(String url) throws P2Exception {
        Utility.sendEvent(new WebClientEvent("openurl", app.getApp().toLowerCase(), url, "", "", 0, sessionContext));
    }

    /**
     * 註銷
     */
    public void SIGNOUT() {
        Utility.sendEvent(new WebClientEvent("signout", app.getApp().toLowerCase(), "", "", "", 0, sessionContext));
    }

    /**
     * 弹出右下角提示对话框
     *
     * @param msgtitle
     * @param msgurl
     * @param msgscript
     * @param msgcontent
     */
    public void OPENMSGDIALOG(String msgtitle, String msgurl, String msgscript, String msgcontent, boolean isautohide) {
        if ("".equals(msgscript)) {
            // 打开对应app
            // Ext.p2.sendEvent({event : 'opennewapp',appid : 'myportal',targetid :
            // 'myportal',value : '<%=appid %>',uniqueid : '<%=uniqueid %>'});
            // 点击内容关闭对话框
            msgscript = "Ext.p2.MSG_SHOW_ACTIVE = false;var msgwin = Ext.getCmp('systemMessageBox');msgwin.hide();";
        }
        HashMap<String, String> map = new HashMap<String, String>(16);
        map.put("msgtitle", msgtitle);
        map.put("msgurl", "".equals(msgurl) ? "#" : msgurl);
        map.put("msgautohide", isautohide ? "true" : "false");
        map.put("msgscript", msgscript);
        map.put("msgcontent", msgcontent);
        Utility.sendEvent(
                new WebClientEvent("openmsgdialog", app.getApp().toLowerCase(), map, "", "", 0, sessionContext));
    }

    public int YLREPORT() throws P2Exception {
        String appname = app.getApp();
        String objectname = getPaoSet().getName();
        PaoSetRemote sqlquery = P2Server.getP2Server().getPaoSet("sqlquery", getPaoSet().getUserInfo());
        if (sessionContext.getCurrentApp().onListTab()) {
            sqlquery.setWhere(" objectname='" + objectname + "' and reporttype='报表' and (agentclient='" + appname
                    + "' or isnull(agentclient,'')='' )");
        } else {
            sqlquery.setWhere(" objectname='" + objectname + "' and (agentclient='" + appname + "' or isnull(agentclient,'')='' )");
        }
        sqlquery.reset();
        if (sqlquery.count() == 1) {
            String url = sqlquery.getPao(0).getString("datatableiframeurl");
            String reporttype = sqlquery.getPao(0).getString("reporttype");
            url = !"打印".equals(reporttype) ? url
                    : url + "&" + getPaoSet().getName() + "." + getUniqueIdName() + "=" + getUniqueIdValue();
            OPENURL(url);
        }
        return 1;
    }


    private void setPrintFlag(PaoRemote pao, String[] fieldsname) throws P2Exception {
        if (Arrays.asList(fieldsname).contains("PRINTBY")) {
            pao.setValue("PRINTBY", pao.getUserName(), 11L);
        }
        if (Arrays.asList(fieldsname).contains("PRINTCOUNT")) {
            pao.setValue("PRINTCOUNT", pao.getInt("PRINTCOUNT") + 1, 11L);
        }
        if (Arrays.asList(fieldsname).contains("PRINTDATE")) {
            pao.setValue("PRINTDATE", Calendar.getInstance().getTime(), 11L);
        }
    }

    // 二维码生成
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void createQcode(String fielname, String contents, String description, String objectname, long objectid,
                            int width, int height) throws P2Exception, WriterException, IOException {

        HashMap map = new HashMap(16);
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        map.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        map.put(EncodeHintType.MARGIN, 1);
        MultiFormatWriter formatWriter = new MultiFormatWriter();
        BitMatrix bitMatrix = formatWriter.encode(contents, BarcodeFormat.QR_CODE, width, height, map);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);

        StringBuffer stringBuffer = new StringBuffer(
                P2Server.getP2Server().getConfig().getProperty("p2.attachment.defaultpath"));

        PaoSetRemote PS_SYSVARS = getP2Session().getPaoSet("PS_SYSVARS");
        PS_SYSVARS.setWhere("varname='DOCUMENT_DIR_RULE'");
        PS_SYSVARS.reset();
        if (!PS_SYSVARS.isEmpty()) {
            String[] a = PS_SYSVARS.getPao(0).getString("varvalue").split("/");
            String site = getP2Session().getProfile().getInsertSite();
            stringBuffer.append(File.separator).append(site);
            for (int i = 1; i < a.length; i++) {
                if ("DOCTYPE".equalsIgnoreCase(a[i])) {
                    stringBuffer.append(File.separator).append(getString("doctype"));
                } else if ("TABLE".equalsIgnoreCase(a[i])) {
                    stringBuffer.append(File.separator).append(objectname);
                }
            }
        }
        UploadFile file = new UploadFile(fielname + ".png", "image\\png", stream);

        String filename = file.getFileName();
        file.setDirectoryName(stringBuffer.toString());
        file.writeToDisk();
        if (!Utility.isNull(file.getAbsoluteFileName())) {
            file.save();
        }
        String serialnumber = file.getFileName();
        PaoSetRemote DOCINFOSET = P2Server.getP2Server().getPaoSet("DOCINFO", getPaoSet().getUserInfo());
        PaoRemote docinfo = DOCINFOSET.addAtEnd();
        docinfo.setValue("document", filename, 11L);
        docinfo.setValue("ownertable", objectname, 11L);
        docinfo.setValue("description", description, 11L);
        docinfo.setValue("postfix", "PNG", 11L);
        docinfo.setValue("doctype", "Attachments", 11L);
        docinfo.setValue("serialnumber", serialnumber, 11L);
        DOCINFOSET.save();

        if (docinfo.getPaoSet("DOCLINKS").isEmpty()) {
            PaoSetRemote DOCLINKSSET = docinfo.getPaoSet("DOCLINKS");
            PaoRemote doclinks = DOCLINKSSET.addAtEnd();
            doclinks.setValue("document", filename, 11L);
            doclinks.setValue("docinfoid", docinfo.getLong("docinfoid"), 11L);
            doclinks.setValue("ownertable", objectname, 11L);
            doclinks.setValue("DOCTYPE", "Attachments", 11L);
            doclinks.setValue("description", description, 11L);
            doclinks.setValue("OWNERID", objectid, 11L);
            docinfo.getPaoSet("DOCLINKS").save();

            PaoSetRemote DOCHISTORY = doclinks.getPaoSet("$DOCHISTORY", "DOCHISTORY", "");
            ((Doclinks) doclinks).addDochistory(DOCHISTORY, "ADD");
            DOCHISTORY.save();
        }
    }

    /**
     * 生成69条形码
     *
     * @param message
     * @param filename
     */
    public void createBarCode(String message, String filename) throws P2Exception {
        StringBuffer stringBuffer = new StringBuffer(
                P2Server.getP2Server().getConfig().getProperty("p2.attachment.defaultpath"));
        PaoSetRemote PS_SYSVARS = getP2Session().getPaoSet("PS_SYSVARS");
        PS_SYSVARS.setWhere("varname='DOCUMENT_DIR_RULE'");
        PS_SYSVARS.reset();
        if (!PS_SYSVARS.isEmpty()) {
            String[] a = PS_SYSVARS.getPao(0).getString("varvalue").split("/");
            String site = getP2Session().getProfile().getInsertSite();
            stringBuffer.append(File.separator).append(site);
            for (int i = 1; i < a.length; i++) {
                if ("DOCTYPE".equalsIgnoreCase(a[i])) {
                    stringBuffer.append(File.separator).append(getString("doctype"));
                } else if ("TABLE".equalsIgnoreCase(a[i])) {
                    stringBuffer.append(File.separator).append(getPaoSet().getName());
                }
            }
        }
        EAN13Bean bean = new EAN13Bean();// 条形码类型
        final int dpi = 150;
        final double moduleWidth = UnitConv.in2mm(2.0f / dpi);
        bean.setModuleWidth(moduleWidth);
        bean.doQuietZone(true);
        String format = "image/png";
        try {
            FileOutputStream stream = new FileOutputStream(stringBuffer.toString() + "/" + filename);
            BitmapCanvasProvider canvas = new BitmapCanvasProvider(stream, format, dpi, BufferedImage.TYPE_BYTE_BINARY,
                    false, 0);
            bean.generateBarcode(canvas, message);
            canvas.finish();
            stream.flush();
            stream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String document = filename + ".png";
        String objectname = getPaoSet().getName();
        PaoSetRemote DOCINFOSET = P2Server.getP2Server().getPaoSet("DOCINFO", getPaoSet().getUserInfo());
        PaoRemote docinfo = DOCINFOSET.addAtEnd();
        docinfo.setValue("document", document, 11L);
        docinfo.setValue("ownertable", objectname, 11L);
        docinfo.setValue("description", "69条形码", 11L);
        docinfo.setValue("postfix", "PNG", 11L);
        docinfo.setValue("doctype", "Attachments", 11L);
        docinfo.setValue("serialnumber", filename, 11L);
        DOCINFOSET.save();

        if (docinfo.getPaoSet("DOCLINKS").isEmpty()) {
            PaoSetRemote DOCLINKSSET = docinfo.getPaoSet("DOCLINKS");
            PaoRemote doclinks = DOCLINKSSET.addAtEnd();
            doclinks.setValue("document", document, 11L);
            doclinks.setValue("docinfoid", docinfo.getLong("docinfoid"), 11L);
            doclinks.setValue("ownertable", objectname, 11L);
            doclinks.setValue("DOCTYPE", "Attachments", 11L);
            doclinks.setValue("description", "69条形码", 11L);
            doclinks.setValue("OWNERID", getPao().getUniqueIDValue(), 11L);
            docinfo.getPaoSet("DOCLINKS").save();
            PaoSetRemote DOCHISTORY = doclinks.getPaoSet("$DOCHISTORY", "DOCHISTORY", "");
            ((Doclinks) doclinks).addDochistory(DOCHISTORY, "ADD");
            DOCHISTORY.save();
        }
    }

    // 选择当前页行
    public int selectCurrentPageRow() throws P2Exception {
        DataBean bean = app.getDataBean("results_showlist");
        int StartIndex = bean.getPageStartIndex();// 开始行
        boolean iselect = !bean.isSelected(StartIndex);
        int EndIndex = bean.getPageRowCount();// 结束行
        if (iselect) {
            bean.select(StartIndex, EndIndex);
        } else {
            bean.unselect(StartIndex, EndIndex);
        }
        bean.refreshTable();
        sessionContext.queueRefreshEvent();
        return 1;
    }

    /**
     * 打开进度条
     */
    public boolean runLongOp(String mathedname) throws P2Exception {
        return this.sessionContext.runLongOp(this, mathedname);
    }

    /**
     * 如果进度条执行成功
     */
    public boolean LongOpCompleted() throws P2Exception {

        return this.sessionContext.haslongOpCompleted();
    }

    /**
     * 关闭应用
     *
     * @param closeApp 关闭的应用名称
     * @throws P2Exception
     */
    public void closeApp(String closeApp) throws P2Exception {
        Utility.sendEvent(new WebClientEvent("closeappwin", app.getApp().toLowerCase(),
                closeApp.toLowerCase(), "", "", 0, sessionContext));
    }

    /**
     * 打开应用
     *
     * @param openApp 打开的应用名称
     * @param fbillid 打开数据ID
     * @throws P2Exception
     */
    public void openApp(String openApp, long fbillid) throws P2Exception {
        closeApp(openApp);
        Utility.sendEvent(new WebClientEvent("opennewapp", app.getApp().toLowerCase(),
                openApp.toLowerCase(), "", "", fbillid, sessionContext));
    }


    public void openConfirmDialog() {

    }


}
