package com.yem.wm.im.intauditbusa.form;

import com.yem.ensign.common.BigDecimalUtils;
import com.yem.ensign.common.CommonUtils;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.property.AmountProp;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.IFormView;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.field.AmountEdit;
import kd.bos.form.field.FieldEdit;
import kd.bos.form.field.TextEdit;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.print.api.PrintTask;
import kd.bos.print.api.PrintWork;
import kd.bos.print.core.service.PrtAttach;
import kd.bos.print.service.BosPrintServiceHelper;
import kd.bos.servicehelper.AttDto;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.PrintServiceHelper;

import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author xwudd
 * @date 17:19
 * @Description
 **/
public class IntAuditBuSaEdit extends AbstractBillPlugIn {


    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        switch(operateKey){
            case "viewparentbill" :
                viewParentBill();
                break;
        }
    }

    public void viewParentBill(){
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        Long needBillIntAuditId = (Long)model.getValue("yem_sourceentryid");
        FunctionalCommon.viewBill(view,model.getDataEntity().getDynamicObjectType().getName(),needBillIntAuditId);
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();
        IDataModel model = this.getModel();
        switch (name){
            //计算佣金汇率
            case "yem_cncurrency":
            case "yem_currencybase":
            case "org":
            case "yem_exratedate":
            case "yem_exratetable":
                DynamicObject org = (DynamicObject) model.getValue("org");
                DynamicObject cncurrency = (DynamicObject) model.getValue("yem_cncurrency");
                DynamicObject currencybase = (DynamicObject) model.getValue("yem_currencybase");
                DynamicObject exratetable = (DynamicObject) model.getValue("yem_exratetable");
                Date exratedate = (Date) model.getValue("yem_exratedate");
                if(org != null && cncurrency != null && currencybase != null && exratetable !=null){
                    BigDecimal exchangeRate = CommonUtils.getExchangeRate(exratetable.getLong("id"), cncurrency.getLong("id"), currencybase.getLong("id"),
                            org.getLong("id"), exratedate);
                    model.setValue("yem_cnexrate",exchangeRate);

                }
                break;
//            case "yem_priceitem":
//                setFieldMustInput();
//                break;
            case "yem_genusprice"://单价
                calculateGenusPremium(rowIndex, model);
                calculateGenusInterestAmt(rowIndex, model);
                calculateGenusCreditAmt(rowIndex, model);
                break;
            case "yem_insuranceaddrate":////保险加成率
                calculateGenusPremium(-1, model);
                break;
            case "yem_rapratesum"://合同是否信保为是的收汇百分比合计
                calculateGenusInterestAmt(-1, model);
                calculateGenusCreditAmt(-1, model);
                break;
            case "yem_insurancefeerate"://保险费率%
                calculateGenusPremium(-1, model);
                break;
            case "yem_interestrate"://利息率%
                calculateGenusInterestAmt(-1, model);
                break;
            case "yem_creditratetext":
                calculateGenusCreditAmt(-1, model);
                break;
        }
    }

    /**
     * 1、保险费：单价**保险加成率*保险费率/100;
     * @param rowIndex
     * @param model
     */
    private void calculateGenusPremium(int rowIndex, IDataModel model) {

        BigDecimal insuranceaddrate = (BigDecimal) model.getValue("yem_insuranceaddrate");//保险加成率
        BigDecimal insurancefeerate = (BigDecimal) model.getValue("yem_insurancefeerate");//保险费率%

        if (rowIndex == -1) {
            int rowCount = model.getEntryRowCount("yem_genusinfo");
            for (int i = 0; i < rowCount; i++) {
                BigDecimal genusprice = (BigDecimal) model.getValue("yem_genusprice", i);//单价

                BigDecimal genuspremium = BigDecimalUtils.div(genusprice.multiply(insuranceaddrate).multiply(insurancefeerate), new BigDecimal("100"), 2);////保险费
                //1、保险费：单价**保险加成率*保险费率/100;
                model.setValue("yem_genuspremium", genuspremium, i);//保险费
            }
        } else {
            BigDecimal genusprice = (BigDecimal) model.getValue("yem_genusprice", rowIndex);//单价

            BigDecimal genuspremium = BigDecimalUtils.div(genusprice.multiply(insuranceaddrate).multiply(insurancefeerate), new BigDecimal("100"), 2);////保险费
            //1、保险费：单价**保险加成率*保险费率/100;
            model.setValue("yem_genuspremium", genuspremium, rowIndex);//保险费
        }
    }

    /**
     * 2、银行利息费=单价*收款计划中的是否信保为是的收汇百分比%*利息率/100，利息率手填
     * @param rowIndex
     * @param model
     */
    private void calculateGenusInterestAmt(int rowIndex, IDataModel model) {
        BigDecimal rapratesum = (BigDecimal) model.getValue("yem_rapratesum");//合同是否信保为是的收汇百分比合计
        BigDecimal interestrate = (BigDecimal) model.getValue("yem_interestrate");//利息率%
        if (rowIndex == -1) {
            int rowCount = model.getEntryRowCount("yem_genusinfo");
            for (int i = 0; i < rowCount; i++) {
                BigDecimal genusprice = (BigDecimal) model.getValue("yem_genusprice", i);//单价


                BigDecimal genusinterestamt = BigDecimalUtils.div(genusprice.multiply(rapratesum).multiply(interestrate), new BigDecimal("100"), 2);//银行利息费
                //2、银行利息费=单价*收款计划中的是否信保为是的收汇百分比%*利息率/100，利息率手填
                model.setValue("yem_genusinterestamt", genusinterestamt, i);//银行利息费
            }
        } else {
            BigDecimal genusprice = (BigDecimal) model.getValue("yem_genusprice", rowIndex);//单价

            BigDecimal genusinterestamt = BigDecimalUtils.div(genusprice.multiply(rapratesum).multiply(interestrate), new BigDecimal("100"), 2);//银行利息费
            //2、银行利息费=单价*收款计划中的是否信保为是的收汇百分比%*利息率/100，利息率手填
            model.setValue("yem_genusinterestamt", genusinterestamt, rowIndex);//银行利息费
        }
    }

    /**
     * 3、信保费=单价*收款计划中的是否信保为是的收汇百分比%*信保费率/100
     * @param rowIndex
     * @param model
     */
    private void calculateGenusCreditAmt(int rowIndex, IDataModel model) {

        BigDecimal rapratesum = (BigDecimal) model.getValue("yem_rapratesum");//合同是否信保为是的收汇百分比合计
        String creditratetext = (String) model.getValue("yem_creditratetext");
        BigDecimal creditrate = BigDecimal.ZERO;//信保费率

        if (YEM.isNotEmpty(creditratetext) && !creditratetext.contains("；")) {
            creditrate = new BigDecimal(creditratetext);
        }

        if (rowIndex == -1) {
            int rowCount = model.getEntryRowCount("yem_genusinfo");
            for (int i = 0; i < rowCount; i++) {
                BigDecimal genusprice = (BigDecimal) model.getValue("yem_genusprice", i);//单价

                BigDecimal genuscreditamt = BigDecimalUtils.div(genusprice.multiply(rapratesum).multiply(creditrate), new BigDecimal("100"), 2);
                //3、信保费=单价*收款计划中的是否信保为是的收汇百分比%*信保费率/100
                model.setValue("yem_genuscreditamt", genuscreditamt, i);//信保费
            }
        } else {
            BigDecimal genusprice = (BigDecimal) model.getValue("yem_genusprice", rowIndex);//单价

            BigDecimal genuscreditamt = BigDecimalUtils.div(genusprice.multiply(rapratesum).multiply(creditrate), new BigDecimal("100"), 2);
            //3、信保费=单价*收款计划中的是否信保为是的收汇百分比%*信保费率/100
            model.setValue("yem_genuscreditamt", genuscreditamt, rowIndex);//信保费
        }
    }

    @Override
    public void afterBindData(EventObject e)
    {
        super.afterBindData(e);
//        setFieldMustInput();
    }

    /**
     * 1、内审预算单的价格条款等于CIF、CFR时，海运费必填，CIF时保费必填，其他价格条款不控制，见截图1；
     */
//    private void setFieldMustInput()
//    {
//        IDataModel model = this.getModel();
//        DynamicObject dataEntity = model.getDataEntity(true);
//        // 价格条款
//        DynamicObject priceitem = dataEntity.getDynamicObject("yem_priceitem");
//        if (priceitem == null) {
//            return;
//        }
//        String name = priceitem.getString("name");
//
//        AmountEdit marinsupreamt = this.getControl("yem_marinsupreamt");
//        AmountEdit seafreight = this.getControl("yem_seafreight");
//
//        if (marinsupreamt == null || seafreight == null) {
//            return;
//        }
//
//        AmountProp marinsupreamtProperty = (AmountProp) marinsupreamt.getProperty();
//
//        AmountProp seafreightProperty = (AmountProp) seafreight.getProperty();
//
//        marinsupreamtProperty.setMustInput(false);
//        seafreightProperty.setMustInput(false);
//
//        if ("CIF".equals(name)) {
//            marinsupreamtProperty.setMustInput(true);
//        }
//
//        if ("CIF".equals(name) || "CFR".equals(name)) {
//            seafreightProperty.setMustInput(true);
//        }
//    }
}
