package com.yem.tws;

import com.yem.tws.common1.BigDecimalUtils;
import com.yem.tws.common1.DateUtils;
import com.yem.tws.common1.StringUtils;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.list.BillList;
import kd.bos.list.IListColumn;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import org.joda.time.DateTime;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FruitOutPutListPlugIn extends AbstractListPlugin {

    @Override
    public void itemClick(ItemClickEvent evt) {
        super.itemClick(evt);
        if (evt.getItemKey().equals("yem_baritem")) {
            BillList billList = getControl("billlistap");
            List<IListColumn> listColumns = billList.getShowListColumns();
            ListSelectedRowCollection selectedRows = billList.getSelectedRows();
            if (selectedRows.size() == 0) {
                this.getView().showMessage("请勾选至少一条数据导出！");
                return;
            }
            //EntityType entityType = billList.getEntityType();
            String entityName = billList.getBillFormId();
            // 通过标识名称，获取单据的中文名
//            String title = MetadataServiceHelper.getDataEntityType(entityName).getDisplayName().toString();

            // 字段标识列表
            List<String> selectFieldList = new ArrayList<>();
            // excelList用于提供数据源给 excel工作簿
            List<List<Object>> excelList = new ArrayList<>();
            // 标题列表
            List<Object> captionList = new ArrayList<>();
            for (IListColumn column : listColumns) {
                if (!column.getListFieldKey().equals("fseq")) {
                    captionList.add(column.getCaption().toString());
                    selectFieldList.add(getFieldKey(entityName, column));
                }
            }
            excelList.add(captionList);
            // 查询数据
            DynamicObjectCollection dynamicObjectCollection = queryData(entityName, listColumns, selectedRows);
            // 把字段的值添加进excelList，excelList之后用来创建XSSFWorkbook
            for (DynamicObject dynamicObject : dynamicObjectCollection) {
                List<Object> list = new ArrayList<>();
                // 用字段标识列表selectFieldList 从dynamicObject中获取数据
                for (String filed : selectFieldList) {
                    if (dynamicObject.get(filed) != null) {
                        Object filedVale = dynamicObject.get(filed);
                        if (filedVale instanceof BigDecimal) {
                            if (((BigDecimal) filedVale).compareTo(BigDecimal.ZERO) == 0) {
                                list.add(0);
                            } else {
                                list.add(((BigDecimal) filedVale).doubleValue());
                            }
                        } else if (filedVale instanceof Date || filedVale instanceof DateTime) {
                            list.add(DateUtils.getData((Date) filedVale, "yyyy-MM-dd"));
                        } else {
                            list.add(dynamicObject.get(filed).toString());
                        }
                    } else {
                        list.add(null);
                    }
                }
                excelList.add(list);
            }

            // 创建excel工作簿
//            XSSFWorkbook workbook = excel(excelList, title);
            XSSFWorkbook workbook = excel(excelList);
            // 上传
            String path = upload(entityName, workbook);
            // 弹出提示框
            String url = RequestContext.get().getClientFullContextPath() + "/attachment/download.do?path=" + path;
//            getView().showMessage("下载文件链接：" +url);
            getView().openUrl(url);
            System.out.println();
        }

        if (evt.getItemKey().equals("yem_repairdata")) {
            QFilter qFilter = new QFilter("yem_exchangerate", QCP.equals, 0)
                    .and(new QFilter("yem_fiedatets", QCP.not_equals, null));
            DynamicObject[] yem_ca_billlogon_s = BusinessDataServiceHelper.load("yem_ca_cusdec",
                    "id,billno,yem_fiedatets,yem_sumdecltotal,yem_exchangerate,yem_sumlocdecltotal,yem_currencybase", new QFilter[]{qFilter}, null);
            if (yem_ca_billlogon_s.length > 0) {
                int jg = 0;
                for (int i = 0; i < yem_ca_billlogon_s.length; i++) {
                    DynamicObject yem_ca_billlogon = yem_ca_billlogon_s[i];
                    if (yem_ca_billlogon != null) {
                        Date yem_fiedatets = yem_ca_billlogon.getDate("yem_fiedatets");
                        BigDecimal yem_sumdecltotal = yem_ca_billlogon.getBigDecimal("yem_sumdecltotal");
                        Setexchangerate(yem_fiedatets, yem_ca_billlogon, yem_sumdecltotal);
                        OperationResult Operate = OperationServiceHelper.executeOperate("save",
                                yem_ca_billlogon.getDynamicObjectType().getName(), new DynamicObject[]{yem_ca_billlogon}, OperateOption.create());
                        if (Operate.isSuccess()) {
                            jg++;
                        }
                    }
                }
                if (jg > 0) {
                    this.getView().showMessage("更新成功，共更新【" + jg + "】条数据");
                }
            } else {
                this.getView().showMessage("未获取到错误数据，禁止修复！");
            }
        }

        if (evt.getItemKey().equals("yem_repairfob")) {
            QFilter qFilter = new QFilter("yem_exchangerate", ">", 0)
                    .and(new QFilter("yem_fobtotal", "=", 0));
            DynamicObject[] yem_ca_billlogon_s = BusinessDataServiceHelper.load("yem_ca_cusdec",
                    "id,billno,yem_fobtotal,yem_usdfobtotal,yem_othercutotal,yem_othermarkname,yem_othercubase,yem_otherrate" +
                            ",yem_insurcurtotal,yem_insurrate,yem_insurcurbase,yem_insurmarkname" +
                            ",yem_feecurrtotal,yem_feerate,yem_feecurrbase,yem_feemarkname,yem_sumlocdecltotal,yem_currencybase" +
                            ",yem_exchangerate,yem_fiedatets,yem_sumlocdecltotal,yem_sumdecltotal," +
                            ",yem_ca_cddetailedentry.yem_qty1,yem_ca_cddetailedentry.yem_decltotal,yem_ca_cddetailedentry.yem_fobamout" +
                            ",yem_ca_cddetailedentry.yem_fobprice,yem_ca_cddetailedentry.yem_usdfob,yem_grosswt" +
                            ",yem_ca_cddetailedentry.yem_rmbdecltotal",
                    new QFilter[]{qFilter}, null);
            int jg=0;
            if (yem_ca_billlogon_s.length > 0) {
                for (int i = 0; i < yem_ca_billlogon_s.length; i++) {
                    DynamicObject yem_ca_billlogon = yem_ca_billlogon_s[i];
                    if (yem_ca_billlogon != null) {
                        //金额合计
                        BigDecimal yem_sumdecltotal = yem_ca_billlogon.getBigDecimal("yem_sumdecltotal");
                        //金额本位币
                        BigDecimal yem_sumlocdecltotal = yem_ca_billlogon.getBigDecimal("yem_sumlocdecltotal");
                        //进出口日期
                        Date yem_fiedatets = yem_ca_billlogon.getDate("yem_fiedatets");
                        BigDecimal yem_grosswt = yem_ca_billlogon.getBigDecimal("yem_grosswt");
                        BigDecimal yem_exchangerate = yem_ca_billlogon.getBigDecimal("yem_exchangerate");//报关汇率
                        if (yem_exchangerate.equals(BigDecimal.ZERO)) {
                            //报关币别
                            DynamicObject yem_currencybase = yem_ca_billlogon.getDynamicObject("yem_currencybase");
                            if (yem_currencybase != null) {
                                yem_exchangerate = Setexchangerate(yem_fiedatets, yem_currencybase);
                                yem_sumlocdecltotal = yem_exchangerate.multiply(yem_sumdecltotal);
                                yem_ca_billlogon.set("yem_sumlocdecltotal", yem_sumlocdecltotal);
                            }
                        }
                        //当前单据运费保费杂费汇总
                        BigDecimal SumYBZ = BigDecimal.ZERO;
                        //运费标志
                        String yem_feemarkname = yem_ca_billlogon.getString("yem_feemarkname").toString();
                        if (StringUtils.isNotEmpty(yem_feemarkname) && StringUtils.isNotNull(yem_feemarkname)) {
                            DynamicObject yem_feecurrbase = yem_ca_billlogon.getDynamicObject("yem_feecurrbase");//运费币别
                            if (yem_feecurrbase != null) {
                                BigDecimal yem_feerate = yem_ca_billlogon.getBigDecimal("yem_feerate");//运费/率
                                BigDecimal feemarkAmt = YBZAmt(yem_feemarkname, yem_fiedatets, yem_feerate, yem_feecurrbase, yem_sumdecltotal,yem_grosswt);
                                SumYBZ = SumYBZ.add(feemarkAmt);
                                yem_ca_billlogon.set("yem_feecurrtotal", feemarkAmt);//运费总额（RMB）
                            }
                        }
                        //保费标志
                        String yem_insurmarkname = yem_ca_billlogon.getString("yem_insurmarkname").toString();
                        if (StringUtils.isNotEmpty(yem_insurmarkname) && StringUtils.isNotNull(yem_insurmarkname)) {
                            DynamicObject yem_insurcurbase = yem_ca_billlogon.getDynamicObject("yem_insurcurbase");//保费币别
                            if (yem_insurcurbase != null) {
                                BigDecimal yem_insurrate = yem_ca_billlogon.getBigDecimal("yem_insurrate");//保费/率
                                BigDecimal feemarkAmt = YBZAmt(yem_insurmarkname, yem_fiedatets, yem_insurrate, yem_insurcurbase, yem_sumdecltotal,yem_grosswt);
                                SumYBZ = SumYBZ.add(feemarkAmt);
                                yem_ca_billlogon.set("yem_insurcurtotal", feemarkAmt);//保费总额（RMB）
                            }
                        }
                        //杂费标志
                        String yem_othermarkname = yem_ca_billlogon.getString("yem_othermarkname").toString();
                        if (StringUtils.isNotEmpty(yem_othermarkname) && StringUtils.isNotNull(yem_othermarkname)) {
                            DynamicObject yem_othercubase =yem_ca_billlogon.getDynamicObject("yem_othercubase");//保费币别
                            BigDecimal yem_otherrate = yem_ca_billlogon.getBigDecimal("yem_otherrate");//杂费/率
                            BigDecimal feemarkAmt = YBZAmt(yem_othermarkname, yem_fiedatets, yem_otherrate, yem_othercubase, yem_sumdecltotal,yem_grosswt);
                            SumYBZ = SumYBZ.add(feemarkAmt);
                            yem_ca_billlogon.set("yem_othercutotal", feemarkAmt);//运费总额（RMB）
                        }
                        BigDecimal yem_fobtotal = BigDecimal.ZERO;
                        BigDecimal yem_fobtotalusd = BigDecimal.ZERO;
                        DynamicObjectCollection yem_ca_cddetailedentry = yem_ca_billlogon.getDynamicObjectCollection("yem_ca_cddetailedentry");
                        for (int j = 0; j < yem_ca_cddetailedentry.size(); j++) {
                            BigDecimal yem_fobamout = BigDecimal.ZERO;
                            BigDecimal yem_fobusd = BigDecimal.ZERO;
                            DynamicObject cddetailedentry = yem_ca_cddetailedentry.get(j);
                            BigDecimal yem_gqty = cddetailedentry.getBigDecimal("yem_qty1");//数量
                            BigDecimal yem_decltotal = cddetailedentry.getBigDecimal("yem_decltotal");//分录总额
                            cddetailedentry.set("yem_rmbdecltotal", yem_decltotal.multiply(yem_exchangerate));//分录总额本位币
                            if (SumYBZ.equals(BigDecimal.ZERO)) {
                                yem_fobamout = yem_decltotal.multiply(yem_exchangerate).setScale(2, BigDecimal.ROUND_HALF_UP);//FOB总价(RMB)
                                cddetailedentry.set("yem_fobamout", yem_fobamout);
                                cddetailedentry.set("yem_fobprice", yem_fobamout.divide(yem_gqty, 10, BigDecimal.ROUND_UP));//FOB单价(RMB)
                                yem_fobusd = yem_fobamout.divide(yem_exchangerate, 10, BigDecimal.ROUND_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
                                cddetailedentry.set("yem_usdfob", yem_fobusd);
                            } else {
                                BigDecimal bl = yem_decltotal.divide(yem_sumdecltotal, 10, BigDecimal.ROUND_UP);
                                BigDecimal ybzrmb = SumYBZ.multiply(bl);
                                yem_fobamout = yem_decltotal.multiply(yem_exchangerate).subtract(ybzrmb).setScale(2, BigDecimal.ROUND_HALF_UP);
                                yem_fobusd = yem_fobamout.divide(yem_exchangerate, 10, BigDecimal.ROUND_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
                                cddetailedentry.set("yem_fobamout", yem_fobamout);
                                cddetailedentry.set("yem_fobprice", yem_fobamout.divide(yem_gqty, 10, BigDecimal.ROUND_UP));//FOB单价(RMB)
                                cddetailedentry.set("yem_usdfob", yem_fobusd);
                            }
                            yem_fobtotal = yem_fobtotal.add(yem_fobamout);
                            yem_fobtotalusd = yem_fobtotalusd.add(yem_fobusd);
                        }
                        yem_ca_billlogon.set("yem_fobtotal", yem_fobtotal);
                        yem_ca_billlogon.set("yem_usdfobtotal", yem_fobtotalusd);
                        //调用保存
                        OperationResult Operate = OperationServiceHelper.executeOperate("save",
                                yem_ca_billlogon.getDynamicObjectType().getName(),
                                new DynamicObject[]{yem_ca_billlogon}, OperateOption.create());
                        if(Operate.isSuccess()){
                            jg++;
                        }
                    }
                }
                if (jg > 0) {
                    this.getView().showMessage("更新成功，共更新【" + jg + "】条数据");
                }
            } else {
                this.getView().showMessage("未获取到错误数据，无法修复！");
            }

        }

        if (evt.getItemKey().equals("yem_kpnote")) {
            int jg = 0;
            QFilter qFilter = new QFilter("yem_isdefault", QCP.equals, true);
            DynamicObject[] invoicingremarks = BusinessDataServiceHelper.load("yem_invoicingremarks",
                    "id,yem_ir_entry.yem_display,yem_ir_entry.yem_delimiter,yem_ir_entry.yem_customsfield",
                    new QFilter[]{qFilter}, null);
            if (invoicingremarks.length > 0) {
                String selectProperties = "";
                for (int i = 0; i < invoicingremarks.length; i++) {
                    DynamicObject invoicingre = invoicingremarks[i];
                    DynamicObjectCollection yem_ir_entry = invoicingre.getDynamicObjectCollection("yem_ir_entry");
                    for (int j = 0; j < yem_ir_entry.size(); j++) {
                        DynamicObject entry = yem_ir_entry.get(j);
                        if (entry != null) {
                            String yem_customsfield = entry.getString("yem_customsfield");
                            selectProperties += yem_customsfield + ",";
                        }
                    }
                    //获取单据数据
                    QFilter qFilter2 = new QFilter("yem_cusdecstatusname", QCP.equals, "结关");
                    //    QFilter qFilter2 = new QFilter("yem_entryid", QCP.equals, "020220230000371791");
                    DynamicObject[] cusdec = BusinessDataServiceHelper.load("yem_ca_cusdec",
                            selectProperties.substring(0, selectProperties.length() - 1) + ",yem_billingnote", new QFilter[]{qFilter2}, null);
                    if (invoicingremarks.length > 0) {
                        for (int k = 0; k < cusdec.length; k++) {
                            String yem_billingnote = "";
                            DynamicObject yem_ca_billlogon = cusdec[k];
                            if (yem_ca_billlogon != null) {
                                for (int s = 0; s < yem_ir_entry.size(); s++) {
                                    DynamicObject entrys = yem_ir_entry.get(s);
                                    String value = "";
                                    String yem_display = entrys.getString("yem_display");
                                    String yem_delimiter = entrys.getString("yem_delimiter");
                                    String yem_customsfield = entrys.getString("yem_customsfield");
                                    value = yem_ca_billlogon.getString(yem_customsfield);
                                    yem_billingnote += yem_display + yem_delimiter + value + "\r\n";
                                }
                            }
                            yem_ca_billlogon.set("yem_billingnote", yem_billingnote.trim());
                            //调用保存
                            OperationResult Operate = OperationServiceHelper.executeOperate("save",
                                    yem_ca_billlogon.getDynamicObjectType().getName(),
                                    new DynamicObject[]{yem_ca_billlogon}, OperateOption.create());
                            if (Operate.isSuccess()) {
                                jg++;
                            }
                        }
                        if (jg > 0) {
                            this.getView().showMessage("更新成功，共更新【" + jg + "】条数据");
                        }
                    } else {
                        this.getView().showMessage("未查询到错误数据，禁止修复");
                    }

                }
            }
        }
    }

    /**
     * @param entityName   单据标识
     * @param listColumns  列
     * @param selectedRows 已选行
     * @return
     */
    private DynamicObjectCollection queryData(String entityName, List<IListColumn> listColumns, ListSelectedRowCollection selectedRows) {
        StringBuilder stringBuilder = new StringBuilder();
        // 构造查询字段
        for (int i = 0; i < listColumns.size(); i++) {
            IListColumn listColumn = listColumns.get(i);
            if (!listColumn.getListFieldKey().equals("fseq")) {
                if (i == listColumns.size() - 1) {
                    stringBuilder.append(getFieldKey(entityName, listColumn));
                } else {
                    stringBuilder.append(getFieldKey(entityName, listColumn) + ", ");
                }
            }
        }
        String selectFields = stringBuilder.toString();

        // 构造idList，获取已选行的id，之后作为过滤条件去查询数据
        List<Long> idList = new ArrayList<>();
        for (ListSelectedRow row : selectedRows) {
            idList.add((Long) row.getPrimaryKeyValue());
        }
        // QFilter的过滤条件为：单据id等于idList里面的这些id才符合获取条件，其他的数据不获取
        QFilter qFilter = new QFilter("id", QFilter.in, idList);
        // 查询数据
        DynamicObjectCollection dynamicObjectCollection =
                QueryServiceHelper.query(entityName, selectFields, qFilter.toArray());
        return dynamicObjectCollection;
    }

    private String getFieldKey(String mainEntityName, IListColumn listColumns) {
        if (listColumns.getEntityName().equals(mainEntityName)) {
            return listColumns.getListFieldKey();
        } else {
            return listColumns.getEntityName() + "." + listColumns.getListFieldKey();
        }
    }

    /**
     * excel生成
     *
     * @param excel 数据源，List<List<String>>，外层的list是行，里面的List<String>是列，存储value
     *              excel.size()是行数，excel.get(n).size()是列数
     * @return
     */
    private XSSFWorkbook excel(List<List<Object>> excel) {
        //创建excel工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建工作表sheet
        XSSFSheet sheet = workbook.createSheet("列表数据");
        //设置默认列宽
        sheet.setDefaultColumnWidth(20);

        // 合并第1行的前几列，合并列数 = excel的列数
        CellRangeAddress titleCellAddresses = new CellRangeAddress(0, 0, 0, excel.get(0).size() - 1);
//        sheet.addMergedRegion(titleCellAddresses);

        // 单据列表数据风格样式，设置字体为黑体，字号15
        XSSFCellStyle billStyle = workbook.createCellStyle();
        //设置字体
        XSSFFont billFont = workbook.createFont();
        billFont.setFontName("宋体");
        billFont.setFontHeight(11);
        billStyle.setWrapText(true);
        billStyle.setFont(billFont);

        //设置第一行格式
        Workbook wb = new SXSSFWorkbook();
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        //写入单据列表数据
        for (int i = 0; i < excel.size(); i++) {
            // i+1是因为前面第1行加了一个标题，单据列表数据是从Excel的第2行开始的，所以要+1
            XSSFRow nrow = sheet.createRow(i);
            for (int u = 0; u < excel.get(i).size(); u++) {
                XSSFCell ncell = nrow.createCell(u);
                if (i == 0) {
                    ncell.setCellStyle(cellStyle);
                } else {
                    ncell.setCellStyle(billStyle);
                }
                Object VALUE = excel.get(i).get(u);
                if (VALUE instanceof Double) {
                    ncell.setCellValue((Double) VALUE);
                } else if (VALUE instanceof String) {
                    ncell.setCellValue((String) VALUE);
                } else if (VALUE instanceof Integer) {
                    ncell.setCellValue((Integer) VALUE);
                } else if (VALUE instanceof Date || VALUE instanceof DateTime) {
                    ncell.setCellValue((Date) VALUE);
                } else {
                    ncell.setCellValue((String) VALUE);
                }

            }

        }
        return workbook;
    }

    /**
     * @param entityName
     * @param workbook
     * @return path 路径
     */
    private String upload(String entityName, XSSFWorkbook workbook) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String fileName = entityName + sdf.format(new Date()) + ".xlsx";
        String pathName = "/offices/" + fileName;
        try {
            OutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            InputStream inputStream = parse(outputStream);

            FileService fs = FileServiceFactory.getAttachmentFileService();
            String path = fs.upload(new FileItem(fileName, pathName, inputStream));

            return path;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return "";
    }

    /**
     * outputStream转inputStream
     *
     * @param out outputStream
     * @return inputStream
     * @throws Exception
     */
    public ByteArrayInputStream parse(final OutputStream out) throws Exception {
        ByteArrayOutputStream baos = (ByteArrayOutputStream) out;
        final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
        return swapStream;
    }

    public void Setexchangerate(Date yem_fiedatets, DynamicObject simpleBill, BigDecimal sum) {
        if (simpleBill != null) {
            if(DateUtils.formatDate(DateUtils.getData(yem_fiedatets,"yyyy-MM-dd"), "yyyy-MM-dd")
                    .equals(DateUtils.formatDate("2021-12-31", "yyyy-MM-dd"))){
                yem_fiedatets=DateUtils.formatDate("2022-01-04", "yyyy-MM-dd");
            }
            if(DateUtils.formatDate(DateUtils.getData(yem_fiedatets,"yyyy-MM-dd"), "yyyy-MM-dd")
                    .before(DateUtils.formatDate("2021-12-31 00:00:00", "yyyy-MM-dd HH:mm:ss"))){
                yem_fiedatets=DateUtils.formatDate("2022-01-04", "yyyy-MM-dd");
            }
            Date Min = DateUtils.getMinMonthDate(yem_fiedatets);
            Date max = DateUtils.getMaxMonthDate(yem_fiedatets);
            QFilter filter = new QFilter("yem_date", QCP.large_equals, Min)
                    .and(new QFilter("yem_date", QCP.less_equals, max));
            //查查询字段标
            DynamicObject creatorDObj = simpleBill.getDynamicObject("yem_currencybase");
            String yem_curr = creatorDObj.getString("number");
            String Fileid = "yem_" + yem_curr.toLowerCase();//将字段标识转换为小写
            DynamicObject[] erpcurrency = BusinessDataServiceHelper.load("yem_bd_centralrate",
                    "id,name,number,yem_date," + Fileid + "",
                    new QFilter[]{filter}, "yem_date");
            if (erpcurrency != null && erpcurrency.length > 0) {
                DynamicObject yem_ca_billlogon = erpcurrency[0];
                if (yem_ca_billlogon != null) {
                    BigDecimal exchangerate = BigDecimalUtils.toBigDecimal(yem_ca_billlogon.getString(Fileid)).divide(BigDecimalUtils.one_handred);
                    simpleBill.set("yem_exchangerate", exchangerate);//汇率赋值
                    simpleBill.set("yem_sumlocdecltotal", exchangerate.multiply(sum));//汇率赋值
                }
            }
        }
    }

    public BigDecimal Setexchangerate(Date yem_fiedatets, DynamicObject yem_currencybase) {
        BigDecimal exchangerate = BigDecimal.ZERO;
        if (yem_currencybase != null) {
            Date Min = DateUtils.getMinMonthDate(yem_fiedatets);
            Date max = DateUtils.getMaxMonthDate(yem_fiedatets);
            QFilter filter = new QFilter("yem_date", QCP.large_equals, Min)
                    .and(new QFilter("yem_date", QCP.less_equals, max));
            //查查询字段标
            String yem_curr = yem_currencybase.getString("number");
            String Fileid = "yem_" + yem_curr.toLowerCase();//将字段标识转换为小写
            DynamicObject[] erpcurrency = BusinessDataServiceHelper.load("yem_bd_centralrate",
                    "id,name,number,yem_date," + Fileid + "",
                    new QFilter[]{filter}, "yem_date");
            if (erpcurrency != null && erpcurrency.length > 0) {
                DynamicObject yem_ca_billlogon = erpcurrency[0];
                if (yem_ca_billlogon != null) {
                    exchangerate = BigDecimalUtils.toBigDecimal(yem_ca_billlogon.getString(Fileid)).divide(BigDecimalUtils.one_handred);
                }
            }
        }
        return exchangerate;
    }

    public BigDecimal YBZAmt(String yem_feemarkname, Date yem_fiedatets, BigDecimal yem_feerate, DynamicObject yem_feecurrbase, BigDecimal yem_sumdecltotal,BigDecimal grosswt) {
        BigDecimal amt = BigDecimal.ZERO;
        if (yem_feecurrbase != null) {
            BigDecimal yem_feecurrexchangerate = Setexchangerate(yem_fiedatets, yem_feecurrbase);//运费汇率
            if (yem_feemarkname.equals("单价")) {
                BigDecimal yem_grosswt = grosswt.divide(BigDecimalUtils.one_thousand);//毛重
                amt = yem_grosswt.multiply(yem_feerate).multiply(yem_feecurrexchangerate);
            } else if (yem_feemarkname.equals("率")) {
                BigDecimal feerate = yem_feerate.divide(BigDecimalUtils.one_handred);
                amt = yem_sumdecltotal.multiply(feerate).multiply(yem_feecurrexchangerate);
            } else if (yem_feemarkname.equals("总价")) {
                amt = yem_feerate.multiply(yem_feecurrexchangerate);
            }
        }
        return amt;
    }

}
