package yem.wmc.imc.formplugin.form;

import com.alibaba.fastjson.JSONObject;
import kd.bos.bill.OperationStatus;
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.events.UploadListener;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import static yem.wmc.imc.api.InvoiceRecognitionController.*;
import static yem.wmc.imc.utils.JsonToDataUtils.collectionJsonToData;

/**
 * @author 金亮
 * @date 2024/1/4 17:06
 * @relevantfile *绑定发票助手（yem_imc_bill）*
 * @description *监控表单上 发票归集 和全电自主登录 按钮，打开动态表单（yem_imc_invocollec）*
 * @versions 1.0
 */
public class InvoiceCollecDynamicForm extends AbstractFormPlugin implements UploadListener {
    // 按钮检测事件，点击到 发票归集按钮，即可打开动态表单
    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        super.afterDoOperation(afterDoOperationEventArgs);
        String key = afterDoOperationEventArgs.getOperateKey();
        if (StringUtils.equals("invoicecollection", key)) { //发票归集
            // 创建弹出动态表单页面对象
            FormShowParameter showParameter = new FormShowParameter();
            // 设置弹出页面的标识
            showParameter.setFormId("yem_imc_invocollec");
            showParameter.setStatus(OperationStatus.ADDNEW);
            // 设置弹出页面打开方式
            showParameter.getOpenStyle().setShowType(ShowType.Modal);
            showParameter.setCloseCallBack(new CloseCallBack(this, "yem_submitbutton"));
            // 打开动态表单
            this.getView().showForm(showParameter);
        }
        if (StringUtils.equals("allelectriclogin", key)) { //全电自主登录
            // 创建弹出动态表单页面对象
            FormShowParameter showParameter = new FormShowParameter();
            // 设置弹出页面的标识
            showParameter.setFormId("yem_imc_allelectriclogin");
            showParameter.setStatus(OperationStatus.ADDNEW);
            // 设置弹出页面打开方式
            showParameter.getOpenStyle().setShowType(ShowType.Modal);
            showParameter.setCloseCallBack(new CloseCallBack(this, "allelectriclogin"));
            // 打开动态表单
            this.getView().showForm(showParameter);
        }

    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        if (StringUtils.equals("yem_submitbutton", actionId)){ //发票归集
            Map<String, Object> returnData = (Map<String, Object>) e.getReturnData();
            if (returnData == null) {
                return;
            }
            Date startDate = (Date) returnData.get("yem_startdate"); //开始时间
            Date endDate = (Date) returnData.get("yem_enddate"); //开始时间
            Integer currentPage = (Integer) returnData.get("yem_currentpage"); //当前页
            Integer pageSize = (Integer) returnData.get("yem_pagesize"); //页面查询条数
            if (startDate == null || endDate == null) {
                this.getView().showMessage("发票归集开始时间和结束时间都不允许为空");
                return;
            } else if (currentPage == null || pageSize == null || currentPage < 1 || pageSize < 1) {
                this.getView().showMessage("当前页或页面查询条不能为空并且必须大于等于1");
                return;
            }

            //1.同步接口-全电企业进项发票归集申请
            JSONObject applyForJson = null;
            try {
                applyForJson = allElectricCollect(startDate, endDate);
            } catch (IOException ex) {
                this.getView().showErrorNotification("全电企业进项发票归集申请失败，请重试!");
                return;
            }
            String applyForCode = applyForJson.getString("code");
            if (!applyForCode.equals("200")) {
                this.getView().showErrorNotification(applyForJson.getString("message"));
                return;
            }
            // 注意这里 data才是 归集任务流水号
            Long serialNo = applyForJson.getLong("data");
            //2.同步接口-全电企业进项发票归集结果查询
            JSONObject resultJson = null;
            try {
                resultJson = allElectricCollectResult(currentPage, pageSize, serialNo);
            } catch (IOException ex) {
                this.getView().showErrorNotification("电企业进项发票归集结果查询失败，请重试!");
                return;
            }
            String code = resultJson.getString("code");
            if (!code.equals("200")) {
                if (code.contains("发票归集失败")){ //  这个时候需要调用：同步接口-全电同步自主登录
                    this.getView().showErrorNotification("登录超时，请重新登录");
                    // 1. 弹出全电同步自主登录动态表单
                    FormShowParameter showParameter = new FormShowParameter();
                    showParameter.setFormId("yem_imc_allelectriclogin");
                    showParameter.setStatus(OperationStatus.ADDNEW);
                    showParameter.getOpenStyle().setShowType(ShowType.Modal);
                    showParameter.setCloseCallBack(new CloseCallBack(this, "allelectriclogin"));
                    this.getView().showForm(showParameter);
                    return;
                }
                this.getView().showErrorNotification(resultJson.getString("message"));
                return;
            }
            //3.发票归集数据插入底表
            ArrayList<DynamicObject> ultimatelyResult = collectionJsonToData(resultJson);
            if (ultimatelyResult == null || ultimatelyResult.size() == 0) {
                this.getView().showErrorNotification("发票归集数据插入数据库失败，请重试!");
                return;
            }
            //绿色提示信息
            this.getView().showSuccessNotification("发票归集数据插入底表成功!，共插入或更新" + ultimatelyResult.size() + "条数据!");
            for (DynamicObject data : ultimatelyResult) {
                if (!data.containsProperty("billno")) {
                    return;
                }
                String billno = data.getString("billno");
                String entityName = data.getDynamicObjectType().getName();
                QFilter qFilter = new QFilter("billno", QFilter.equals, billno);
                data = BusinessDataServiceHelper.loadSingle(entityName, new QFilter[]{qFilter});
                if (data == null) {
                    return;
                }
                data = BusinessDataServiceHelper.loadSingle(data.getPkValue(), entityName);
                Creatyementryentity(data);
            }
        }
    }

    /**
     * 给发票信息分录赋值
     * @param data
     */
    public void Creatyementryentity(DynamicObject data) {
        // 判断分录上是否有这行,没有就添加
        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();
        if (data.containsProperty("yem_invoice_type")) {
            entryCol.set("yem_invoicetype", data.get("yem_invoice_type"));//发票类型   ***
        }
        if (data.containsProperty("yem_invoice_code")) {
            entryCol.set("yem_invoicecode", data.get("yem_invoice_code"));//发票代码
        }
        if (data.containsProperty("yem_invoice_no")) {
            entryCol.set("yem_invoiceno", data.get("yem_invoice_no"));//发票号码
        }
        if (data.containsProperty("yem_invoice_date")) {
            entryCol.set("yem_invoicedate", data.get("yem_invoice_date"));//发票日期
        }
        if (data.containsProperty("yem_total_amount")) {
            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") || dataname.equals("yem_imc_eoinvoice")) {//增值税电子专用发票/增值税电子普通发票（取分录最后一行）
            DynamicObjectCollection dynamicObjectCollection = null;
            if (data.containsProperty("yem_items")) {
                dynamicObjectCollection = data.getDynamicObjectCollection("yem_items");
            } else if (data.containsProperty("yem_imc_eoinvoice_p")) {
                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);
            }
        }
        if (data.containsProperty("yem_total_tax_amount")) {
            entryCol.set("yem_taxamountinvoice", data.get("yem_total_tax_amount"));//发票税额
        }
        if (data.containsProperty("yem_check_status")) {
            entryCol.set("yem_isvalidatest", data.get("yem_check_status"));//查验状态
        }
        //增值税专用发票/增值税专用发票/全电发票 （使用的是主要商品名称）
        if (dataname.equals("yem_imc_esinvoice") || dataname.equals("yem_imc_eoinvoice") || dataname.equals("yem_imc_electric")) {
            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());//采集时间
        if (data.containsProperty("yem_resource")) {
            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");
    }
}
