package yem.wmc.imc.formplugin.form;
import kd.bos.bill.OperationStatus;
import kd.bos.cache.CacheFactory;
import kd.bos.cache.TempFileCache;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.control.AttachmentPanel;
import kd.bos.form.control.events.UploadEvent;
import kd.bos.form.control.events.UploadListener;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import yem.wmc.imc.api.InvoiceRecognitionController;
import yem.wmc.imc.utils.MultipartFileDto;

import java.io.*;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.util.*;

import static yem.wmc.imc.api.InvoiceRecognitionController.legalityCheck;
/*
 *       发票助手动态表单插件（手工錄入）
 *       @auth  gjt
 * */

public class BillDynamicForm extends AbstractFormPlugin implements UploadListener {
    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        AttachmentPanel panel = this.getControl("yem_cumputer");
        panel.addUploadListener(this);// 监听附件面板上传
    }

    // 动态表单关闭事件
    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        if (actionId.equals("yem_submitbutton")) { //手工录入

            Map<String, Object> returnData = (Map<String, Object>) e.getReturnData();
            if (returnData == null) {
                return;
            }
            //发票代码
            String invoicecodeHand = (String) returnData.get("yem_invoicecode");
            //发票号码
            String invoicenoHand = (String) returnData.get("yem_invoiceno");
            //开票日期
            String invoicedateHand = (String) returnData.get("yem_invoicedate");
            //开具金额
            BigDecimal invoiceamountHand = (BigDecimal) returnData.get("yem_invoiceamount");
            //过滤
            QFilter qFilterno = new QFilter("yem_invoice_no", QCP.equals, invoicenoHand);
            QFilter qFiltercode = new QFilter("yem_invoice_code", QCP.equals, invoicecodeHand);
            //数据库查询
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("yem_imc_electric", new QFilter[]{qFilterno, qFiltercode});

            if (dynamicObject != null) {
                Creatyementryentity(dynamicObject);
            } else {
                CustomApiResult<DynamicObject> dynamicObjectCustomApiResult = null;
                try {
                    dynamicObjectCustomApiResult = InvoiceRecognitionController.nvoiceInformationDynamicHand(invoicecodeHand, invoicenoHand, invoicedateHand, invoiceamountHand);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                DynamicObject data = dynamicObjectCustomApiResult.getData();
//        int index = this.getModel().createNewEntryRow("yem_entryentity");
//        this.getModel().setValue("", ,index);
                Creatyementryentity(data);
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        super.afterDoOperation(afterDoOperationEventArgs);
        String key = afterDoOperationEventArgs.getOperateKey();
        if ("donothing".equals(key)) {
            // 创建弹出动态表单页面对象
            FormShowParameter showParameter = new FormShowParameter();
            // 设置弹出页面的标识
            showParameter.setFormId("yem_imc_collect_enter");
            showParameter.setStatus(OperationStatus.ADDNEW);
            // 设置弹出页面打开方式
            showParameter.getOpenStyle().setShowType(ShowType.Modal);
            showParameter.setCloseCallBack(new CloseCallBack(this, "yem_submitbutton"));
            // 打开动态表单
            this.getView().showForm(showParameter);
        }
    }

    public static MultipartFile fileToMultipartFile(File file) {
        FileItem fileItem = creatFileItem(file);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }

    public static FileItem creatFileItem(File file) {
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(16, null);
        FileItem fileItem = diskFileItemFactory.createItem("textField", "application/zip", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            OutputStream outputStream = fileItem.getOutputStream();
            while ((bytesRead = fileInputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            Files.copy(file.toPath(), outputStream);
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileItem;
    }

    @Override
    public void upload(UploadEvent evt) {
        UploadListener.super.upload(evt);
        Object[] urls = evt.getUrls();
        for (Object urla : urls) {
            LinkedHashMap<String, Object> map=  (LinkedHashMap<String, Object>)urla;
            String url = (String) map.get("url");
            TempFileCache cache = CacheFactory.getCommonCacheFactory().getTempFileCache();
            InputStream in = cache.getInputStream(url);
            try {
                MultipartFile multipartFile = new MultipartFileDto((String) map.get("name"), (String) map.get("name"), (String) map.get("type"), in);
                CustomApiResult<DynamicObject> dynamicObjectCustomApiResult = InvoiceRecognitionController.nvoiceInformationDynamic(multipartFile);
                DynamicObject data = dynamicObjectCustomApiResult.getData();
                Creatyementryentity(data);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
//        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) evt.getUrls()[0];
    }

    /**
     * 将数据更新到发票信息分录上
     * @param data
     */
    public void Creatyementryentity(DynamicObject data) {
        if (data == null) {
            return;
        }

        // 判断分录上是否有这行,没有就添加
        DynamicObjectCollection entryentityCols = this.getModel().getDataEntity(true).getDynamicObjectCollection("yem_entryentity");
        if (entryentityCols !=null && entryentityCols.size()>0){
            for (DynamicObject entryentityCol : entryentityCols) {
                String yemInvoicecode = entryentityCol.getString("yem_invoicecode");//发票代码
                String yemInvoiceno = entryentityCol.getString("yem_invoiceno");//发票号码
                if (data.getString("yem_invoice_code").equals(yemInvoicecode) && data.getString("yem_invoice_no").equals(yemInvoiceno)){ //如果存在
                    return;
                }
            }
        }
        String dataname = data.getDataEntityType().getName();
//        DynamicObjectCollection entryentityCols = this.getModel().getDataEntity(true).getDynamicObjectCollection("yem_entryentity");
        DynamicObject entryCol = entryentityCols.addNew();
        entryCol.set("yem_invoicetype", data.get("yem_invoice_type"));//发票类型   ***
        entryCol.set("yem_invoicecode", data.get("yem_invoice_code"));//发票代码
        entryCol.set("yem_invoiceno", data.get("yem_invoice_no"));//发票号码
        entryCol.set("yem_invoicedate", data.get("yem_invoice_date"));//发票日期
        entryCol.set("yem_totalamount", data.get("yem_total_amount"));//价税合计
        entryCol.set("yem_validatemessage", legalityCheck(data));//发票校验结果
        //税率（%）
        if (dataname.equals("yem_imc_air")) {
            entryCol.set("yem_alltaxrate", data.getBigDecimal("yem_tax_rate"));
        }
        //火车高铁
        if (dataname.equals("yem_imc_trains")) {
            entryCol.set("yem_alltaxrate", data.getBigDecimal("yem_tax_rate"));
        }
        //增值税电子专用发票
        if (dataname.equals("yem_imc_esinvoice")) {
            DynamicObjectCollection dynamicObjectCollection = data.getDynamicObjectCollection("yem_items");
            for (DynamicObject dynamicObject : dynamicObjectCollection) {
                //税率
                BigDecimal yemTaxRate = dynamicObject.getBigDecimal("yem_tax_rate");
                //税率
                entryCol.set("yem_alltaxrate", yemTaxRate);
            }
        }
        //增值税电子普通发票
        if (dataname.equals("yem_imc_eoinvoice")) {
            DynamicObjectCollection dynamicObjectCollection = data.getDynamicObjectCollection("yem_imc_eoinvoice_p");
            for (DynamicObject dynamicObject : dynamicObjectCollection) {
                //税率
                BigDecimal yemTaxRate = dynamicObject.getBigDecimal("yem_tax_rate");
                //税率
                entryCol.set("yem_alltaxrate", yemTaxRate);
            }
        }
        //全电
        if (dataname.equals("yem_imc_electric")) {
            DynamicObjectCollection dynamicObjectCollection = data.getDynamicObjectCollection("yem_imc_electric_sp");
            for (DynamicObject dynamicObject : dynamicObjectCollection) {
                //税率
                BigDecimal yemTaxRate = dynamicObject.getBigDecimal("yem_taxrate");
                //税率
                entryCol.set("yem_alltaxrate", yemTaxRate);
            }
        }
        entryCol.set("yem_taxamountinvoice", data.get("yem_total_tax_amount"));//发票税额
//        entryCol.set("yem_validatemessage",data.get("yem_check_result"));//发票校验结果 1.4金亮注
        entryCol.set("yem_isvalidatest", data.get("yem_check_status"));//查验状态
        //增值税专用发票
        if (dataname.equals("yem_imc_esinvoice")) {
            entryCol.set("yem_invoicegoodsname", data.get("yem_main_goods_name"));//商品名称
        }
        //全电发票
        if (dataname.equals("yem_imc_electric")) {
            entryCol.set("yem_invoicegoodsname", data.get("yem_main_goods_name"));//商品名称
        }
        if (dataname.equals("yem_imc_eoinvoice")) {
            entryCol.set("yem_invoicegoodsname", data.get("yem_main_goods_name"));//商品名称
        }
        if (dataname.equals("yem_imc_esinvoice") ||
                dataname.equals("yem_imc_electric") ||
                dataname.equals("yem_imc_eoinvoice")) {
            entryCol.set("yem_buyerorgname", data.get("yem_buyer_name"));//收票公司
            entryCol.set("yem_buyertaxno", data.get("yem_buyer_tax_no"));//收票方税号
            entryCol.set("yem_makeoutcompname", data.get("yem_saler_name"));//开票公司
            entryCol.set("yem_salertaxno", data.get("yem_saler_tax_no"));//开票方税号
        }

        entryCol.set("yem_billcreatetime", new Date());//采集时间
        entryCol.set("yem_invoicefrom", data.get("yem_resource"));//发票来源

        if (dataname.equals("yem_imc_air")) {
            //备注
            entryCol.set("yem_remark",
                    "顾客姓名：" + data.getString("yem_customer_name") + ";" +
                            "身份证号：" + data.getString("yem_customer_id_no") + ";" +
                            "座位等级：" + data.getString("yem_seat_grade") + ";" +
                            "车次航班：" + data.getString("yem_flight_num") + ";" +
                            "出发地：" + data.getString("yem_place_of_departure") + ";" +
                            "目的地：" + data.getString("yem_dest_area") + ";");
        }
        if (dataname.equals("yem_imc_trains")) {
            //备注
            entryCol.set("yem_remark",
                    "顾客姓名：" + data.getString("yem_passenger_name") + ";" +
                            "身份证号：" + data.getString("yem_customer_id_no") + ";" +
                            "座位等级：" + data.getString("yem_seat_grade") + ";" +
                            "车次：" + data.getString("yem_train_num") + ";" +
                            "出发地：" + data.getString("yem_station_get_on") + ";" +
                            "目的地：" + data.getString("yem_station_get_off") + ";");
        }
        if (dataname.equals("yem_imc_taxi")) {
            //里程
            BigDecimal mileage = data.getBigDecimal("yem_mileage");
            String mileageString = String.valueOf(mileage);
            //备注
            entryCol.set("yem_remark",
                    "发票源地区：" + data.getString("yem_source_area") + ";" +
                            "上车时间：" + data.getString("yem_time_get_on") + ";" +
                            "下车时间：" + data.getString("yem_time_get_off") + ";" +
                            "里程：" + mileageString + "km" + ";");
        }
        entryCol.set("yem_serialno", data.get("yem_check_status"));//发票序列号
        this.getView().updateView("yem_entryentity");
    }

}
