package yem.wmc.imc.formplugin.form;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.plugin.AbstractFormPlugin;
import yem.wmc.imc.utils.CommonUtils;
import yem.wmc.imc.utils.HttpUtils;
import yem.wmc.imc.utils.JsonToDataUtils;

import javax.json.JsonObject;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 金亮
 * @date 2024/5/30 15:36
 * @relevantfile 开票申请单插件（yem_imc_original）
 * @description 同步开票（按钮）调用第三方接口生成开票单
 * @versions 1.0 测试阶段代码
 */
public class OriginalEdit extends AbstractFormPlugin {
    private static final String url = "https://huisuiyun.com/api/v2/agent/cdk/agent-settlement/add/sync"; //同步接口-结算单新增并同步开票

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String key = e.getOperateKey();
        if (key.equals("syncoutinvoice")) { //同步开票
            DynamicObject bill = this.getModel().getDataEntity(true);
            //请求头Map
            Map<String, String> headMap = new HashMap<>();
            headMap.put("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.24");
            headMap.put("ContentType", "application/json;charset=UTF-8");
            String Token = CommonUtils.getToken();
            headMap.put("X-Access-Token", Token);

            // 获取请求参数
            JSONObject paramJson = new JSONObject();
            // 发票类型*
            String invoiceType = bill.getString("yem_invoicetype");
            if (invoiceType.isEmpty()) {
                this.getView().showTipNotification("发票类型不能为空");
                return;
            }
            paramJson.put("invoiceType", invoiceType);

            //销方税号(纳税人识别号)*
            String taxNo = bill.getString("yem_salertaxno");
            if (taxNo.isEmpty()) {
                this.getView().showTipNotification("纳税人识别号不能为空");
                return;
            }
            paramJson.put("taxNo", taxNo);

            //地址(销方)
            String sellerAddress = bill.getString("yem_addresssell");
            if (!sellerAddress.isEmpty()) {
                paramJson.put("sellerAddress", sellerAddress);
            }

            //电话 (销方)
            String sellerTel = bill.getString("yem_phonesell");
            if (!sellerTel.isEmpty()) {
                paramJson.put("sellerTel", sellerTel);
            }

            //销方银行名称
            String sellerBankName = bill.getString("yem_banksell");
            if (!sellerBankName.isEmpty()) {
                paramJson.put("sellerBankName", sellerBankName);
            }

            //销方银行账号
            String sellerBankAccount = bill.getString("yem_accountsell");
            if (!sellerBankAccount.isEmpty()) {
                paramJson.put("sellerBankAccount", sellerBankAccount);
            }

            //订单号*
            String externalDocumentNo = bill.getString("yem_orderno");
            if (externalDocumentNo.isEmpty()) {
                this.getView().showTipNotification("订单号不能为空");
                return;
            }
            paramJson.put("externalDocumentNo", externalDocumentNo);

            //是否邮寄*
            String logisticsFlag = bill.getString("yem_logisticsflag");
            if (logisticsFlag.isEmpty()) {
                this.getView().showTipNotification("是否邮寄不能为空");
                return;
            }
            paramJson.put("logisticsFlag", logisticsFlag);

            // 购方名称*
            String purchaserName = bill.getString("yem_buyername");
            if (purchaserName.isEmpty()) {
                this.getView().showTipNotification("购方名称不能为空");
                return;
            }
            paramJson.put("purchaserName", purchaserName);
            // todo ...

            // 明细
            JSONArray jsonArray = new JSONArray();
            paramJson.put("details", jsonArray);
            DynamicObjectCollection yemImcOriginalItem = bill.getDynamicObjectCollection("yem_imc_original_item");
            for (DynamicObject row : yemImcOriginalItem) {
                JSONObject rowJson = new JSONObject();

                //商品编码(物料编码)
                DynamicObject yemMaterielfield = row.getDynamicObject("yem_materielfield");
                if (yemMaterielfield != null) {
                    String goodsCode = yemMaterielfield.getString("number");
                    rowJson.put("goodsCode", goodsCode);
                }
                //商品名称
                String goodsName = row.getString("yem_goodsname");
                if (!goodsName.isEmpty()) {
                    rowJson.put("goodsName", goodsName);
                }
                //含税金额(金额(含税))
                BigDecimal amountWithTax = row.getBigDecimal("yem_taxamount");
                rowJson.put("amountWithTax", amountWithTax);

                //不含税金额金额(不含税)
                BigDecimal amount = row.getBigDecimal("yem_amount");
                rowJson.put("amount", amount);

                //税额
                BigDecimal taxAmount = row.getBigDecimal("yem_tax");
                rowJson.put("taxAmount", taxAmount);

                //单价含税标识

                //税率
                BigDecimal taxRate = row.getBigDecimal("yem_taxrate");
                rowJson.put("taxRate", taxRate);

                //数量
                BigDecimal quantity = row.getBigDecimal("yem_num");
                rowJson.put("quantity", quantity);

                //单价(单价(含税))
                BigDecimal unitPrice = row.getBigDecimal("yem_taxunitprice");
                rowJson.put("unitPrice", unitPrice);

                //税收分类编码

                //简称
                String shortName = row.getString("yem_goodssimplename");
                if (!shortName.isEmpty()) {
                    rowJson.put("shortName", shortName);
                }

                //规格
                String specification = row.getString("yem_specification");
                if (!specification.isEmpty()) {
                    rowJson.put("specification", specification);
                }

                //是否享受优惠政策
                String taxPre = row.getString("yem_policylogo");
                if (!taxPre.isEmpty()) {
                    rowJson.put("taxPre", taxPre);
                }
                //优惠政策类型

                //特殊征税管理

                //单位(计量单位)
                String unit = row.getString("yem_unit");
                if (!unit.isEmpty()) {
                    rowJson.put("unit", unit);
                }

                //零税率标识

                //折扣行标记

                //折扣含税金额

                //折扣不含税金额

                //折扣税额

                //扣除额

                jsonArray.add(rowJson);
            }

            try {
                //暂时使用测试数据
//                String returnStr = HttpUtils.doPostWithHeader(url, String.valueOf(paramJson), headMap);
                String testParameter = getTestRequestParameter();
                String returnStr = HttpUtils.doPostWithHeader(url, testParameter, headMap);
                returnStr =  getTestReturnParameter();
                JSONObject returnJson = JSONObject.parseObject(returnStr);
                if (returnJson.getString("code").equals("200")){
                    // 将数据插入数据库
                    DynamicObject data = JsonToDataUtils.jsonToData("yem_imc_invoices", returnJson.getJSONObject("data"), null);
                    if (data !=null){
                        this.getView().showSuccessNotification("同步开票成功，单据编号为："+data.getString("billno"));
                    }else {
                        this.getView().showErrorNotification("同步开票失败");
                    }
                    return;
                }else if(!returnJson.getString("code").equals("200")){
                    this.getView().showErrorNotification(returnJson.getString("message"));
                    return;
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }


    /**
     * 慧穗云中给出的请求实例参数
     * @return
     */
    private  String getTestRequestParameter(){
        String parameter = "{\"invoiceType\":3,\"taxNo\":\"490202991999000\",\"deviceNo\":\"769520000000\",\"externalDocumentNo\":\"pyjinvoicetest\",\"logisticsFlag\":0,\"purchaserName\":\"慧穗数字科技（上海）有限公司\",\"purchaserAddress\":\"0 0\",\"purchaserBankName\":\"0 0\",\"purchaserPhone\":\"电票短信接收电话\",\"purchaserEmail\":\"电票接收电子邮箱\",\"reviewer\":\"管理员reviewer\",\"drawer\":\"饺子drawer\",\"payee\":\"饺子payee\",\"levyingType\":0,\"exten1\":\"pyjpushTest\",\"details\":[{\"goodsName\":\"万兆单模LC全双工接口SFP+光模块，1310nm波长, 10km传输距离, 支持DDM，XG-LR-SM1310\",\"amountWithTax\":\".01\",\"quantity\":\"1\",\"taxRate\":\"0.03\",\"taxSign\":\"1\",\"unitPrice\":\".01\",\"revenueCode\":\"1090510030000000000\",\"shortName\":\"\",\"specification\":\"\",\"taxPre\":\"\",\"taxPreType\":\"\",\"unit\":\"台\",\"zeroTax\":\"\",\"deduction\":0,\"extend1\":\"pyjpushTest\"}]}";
   return parameter;
    }

    /**
     * 慧穗云中正确访问输出示例json
     */
    private  String getTestReturnParameter(){
        String returnStr = "{\"code\":\"200\",\"message\":\"开具成功\",\"serialNo\":\"2bcdb1d6-72c9-47ec-9b3c-3e27e9ed12ed\",\"data\":{\"purchaserBankAccount\":\"\",\"exten10\":\"\",\"listFlag\":0,\"purchaserPhone\":\"\",\"createUserName\":\"饺子\",\"handlerName\":\"\",\"sellerAddress\":\"地址123yyyyyyy\",\"drewDate\":1682524800000,\"payee\":\"饺子paye\",\"oldInvoiceNo\":\"\",\"externalDocumentNo\":\"123wefeferfervre112233\",\"invoiceType\":3,\"invoiceDrewDate\":\"2023-04-27 00:00:00\",\"invoiceNo\":\"72121113\",\"settlementNo\":\"JS230427394124\",\"machineCode\":\"769510000000\",\"invoiceCode\":\"321103111816\",\"purchaserName\":\"慧穗数字科技（上海）123有限公司\",\"checkCode\":\"70475469242198150479\",\"purchaserBankName\":\"\",\"serialNo\":\"836213985186426881\",\"sellerTaxNo\":\"490202991999000\",\"purchaserEmail\":\"\",\"purchaserTaxNo\":\"91310117MA1J30X297\",\"specialFlag\":0,\"taxAmount\":0.01,\"sellerBankName\":\"银行456\",\"resultMatchFlag\":0,\"exten4\":\"\",\"exten5\":\"\",\"exten2\":\"\",\"exten3\":\"\",\"exten8\":\"\",\"exten9\":\"\",\"handlerCertificateCode\":\"\",\"oldInvoiceCode\":\"\",\"exten6\":\"\",\"exten7\":\"\",\"sellerName\":\"虚拟通道\",\"remark\":\"\",\"exten1\":\"\",\"purchaserAddress\":\"杭州市万达广场\",\"sid\":836213985899458600,\"billingType\":0,\"sellerTel\":\"15867192962\",\"redApplicationNo\":\"\",\"ctrlSerMachineCode\":\"22\",\"amount\":0.99,\"ciphertext\":\"14*+34+34&gt;6+27-&gt;4-15&gt;6550924&lt;4*6&lt;/7950-+1+60570*//5361/05*70283092+81899997758&gt;0472566*6*22&lt;0944-&gt;8+7*013187\",\"handlerCertificateNo\":\"\",\"handlerTaxNo\":\"\",\"drawer\":\"饺子draw\",\"purchaserTel\":\"\",\"reviewer\":\"管理员re\",\"ofdUrl\":\"https://fpjr.zhejiang.chinatax.gov.cn:9999/api?action=getDoc&amp;code=033002100211_88271606_20210902_F1C7E4I6&amp;type=3\",\"sellerBankAccount\":\"ddddd1\",\"amountWithTax\":1,\"invoiceStatus\":10,\"levyingType\":0,\"detailList\":[{\"invoiceLineType\":0,\"createUserName\":\"饺子\",\"categoryName\":\"\",\"extend10\":\"\",\"id\":836213995647029200,\"goodsName\":\"年度维护费\",\"revenueCode\":\"3040201030000000000\",\"unitPrice\":0.99,\"amount\":0.99,\"quantity\":1,\"taxPreType\":0,\"zeroTax\":0,\"specification\":\"\",\"extend7\":\"\",\"extend6\":\"\",\"taxRate\":0.01,\"extend9\":\"\",\"unit\":\"套\",\"extend8\":\"\",\"deduction\":0,\"extend3\":\"\",\"extend2\":\"\",\"extend5\":\"\",\"extend4\":\"\",\"taxPre\":1,\"extend1\":\"\",\"goodsCode\":\"\",\"amountWithTax\":1,\"shortName\":\"*信息技术服务*\",\"taxAmount\":0.01}],\"specificElements\":[]}}";
    return returnStr;
    }






}
