package com.yem.rf.salescommission;

import com.yem.wm.utils.RptUtil;
import com.yem.wm.utils.YEM;
import com.yem.wm.utils.groupfunc.GroupConcatFunctionByComma;
import kd.bos.algo.DataSet;
import kd.bos.algo.GroupbyDataSet;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.report.AbstractReportListDataPlugin;
import kd.bos.entity.report.FilterInfo;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;

import java.util.*;

import static com.yem.rf.utils.RFUtils.getBaseQFilter;
import static kd.fi.er.report.query.TripOrderRpt.algoKey;

/**
 * @author ljw
 * @date 2024/9/5 16:06
 * @description SparepartsNotShippedPlugin
 */
public class SparepartsNotShippedPlugin extends AbstractReportListDataPlugin {
    @Override
    public DataSet query(ReportQueryParam reportQueryParam, Object o) throws Throwable {
        DataSet resDataSet;
        DataSet yemEsSalesorder = yemEsSalesorder();
        DataSet yemEsStoragetrans = yemEsStoragetrans();
        DataSet yemImEncasement = yemImEncasement();
        DataSet yemGathering = yemGathering();
        DataSet yemShippingdetails = yemShippingdetails();
        resDataSet = yemEsSalesorder.leftJoin(yemEsStoragetrans).on("queryDeliverNoticeid", "yem_corebillid")
                .select(RptUtil.getDataSetFiledAlias(yemEsSalesorder), RptUtil.getDataSetFiledAlias(yemEsStoragetrans)).finish();
        resDataSet = resDataSet.leftJoin(yemImEncasement).on("queryDeliverNoticeid", "encasementcorebillid")
                .select(RptUtil.getDataSetFiledAlias(resDataSet), RptUtil.getDataSetFiledAlias(yemImEncasement)).finish();
        resDataSet = resDataSet.leftJoin(yemGathering).on("queryDeliverNoticeid", "yem_titleid")
                .select(RptUtil.getDataSetFiledAlias(resDataSet), RptUtil.getDataSetFiledAlias(yemGathering)).finish();
        resDataSet = resDataSet.leftJoin(yemShippingdetails).on("queryDeliverNoticeid", "yemShippingdetailsyem_sourcebillid")
                .select(RptUtil.getDataSetFiledAlias(resDataSet), RptUtil.getDataSetFiledAlias(yemShippingdetails)).finish();
        resDataSet = resDataSet.distinct();
        resDataSet = RptUtil.zeroNullNums(resDataSet);
        DataSet selected = resDataSet.select(String.join(",", RptUtil.getDataSetFiledAlias(resDataSet)) +
                ",(yem_offeramount-yem_theamountpaid) yem_theamountowed" +
                ",placeexamineqty-delivernoticeqty yem_offerqty"+
                ",placeexamineamt-yem_totalallamount yem_offeramounts"+
                ",CASE WHEN  (yem_contractamount = yem_salcontractclaamt)  THEN  paymenttime ELSE null END yem_bizdate");
        selected =  selected.removeFields("paymenttime");
        FilterInfo filter = reportQueryParam.getFilter();
        String yemContract = filter.getString("yem_billnos");
        DynamicObject yemClient = filter.getDynamicObject("yem_clientname");
        DynamicObjectCollection yem_bd_producttype = filter.getDynamicObjectCollection("yem_bd_producttype");
        StringBuilder sb = new StringBuilder();
        DataSet result = selected.where("yem_billno != ''");
        sb.append("yem_billno != ''");
//        sb.append("delivernoticebillstatus != null'");
        if (YEM.isNotEmpty(yemContract)) {
            sb.append("  AND  yem_billno   like '").append("%").append(yemContract).append("%").append("'");
        }
        if (YEM.isNotEmpty(yemClient)) {
            sb.append("  AND  yem_client  = ").append("'" + yemClient.getString("name") + "'");
        }
        if (YEM.isNotEmpty(yem_bd_producttype)){
            List<String> names = new ArrayList<>();
            for (DynamicObject dynamicObject : yem_bd_producttype) {
                String name = dynamicObject.getString("name");
                names.add(name);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("var",names);
            result = result.filter("yem_bd_products in var",map);

        }
        DataSet where = result.where(sb.toString());
        return where.distinct();
    }

    /**
     * 发运明细单
     *
     * @return
     */
    private DataSet yemShippingdetails() {

        QFilter qFilter = getBaseQFilter();
        List<String> selectfields = new ArrayList<>();
        selectfields.add("yem_iswithaccessories yem_boardaccessor");
        selectfields.add("yem_transportstyle.name yem_shippingmethod");
        selectfields.add("yem_sourcebillid yemShippingdetailsyem_sourcebillid");
        DataSet yemShippingdetails = ORM.create().queryDataSet(algoKey, "yem_shippingdetails", String.join(",", selectfields), qFilter.toArray());
        yemShippingdetails = yemShippingdetails.select(String.join(",", RptUtil.getDataSetFiledAlias(yemShippingdetails)) +
                ",CASE WHEN yem_boardaccessor = 'A' THEN '是' ELSE '否' END yem_boardaccessory");
        yemShippingdetails = yemShippingdetails
                .groupBy(new String[]{"yemShippingdetailsyem_sourcebillid"})
                .groupConcat("yem_boardaccessory", "yem_boardaccessory", "；")
                .groupConcat("yem_shippingmethod", "yem_shippingmethod", "；")
                .finish();
        return yemShippingdetails;
    }

    /**
     * 收款单金额对比
     *
     * @return
     */
    private DataSet yemGathering() {
        QFilter qFilter = getBaseQFilter(new String[]{"B", "C"});
        List<String> selectfields = new ArrayList<>();
        selectfields.add("yem_receiptdetail.yem_claimdetail.yem_salcontractno.id yem_titleid");//收款单的合同号id
        selectfields.add("yem_receiptdetail.yem_claimdetail.yem_salcontractclaamt yem_salcontractclaamt");//收款单的合同金额
        DataSet yemShippingdetails = ORM.create().queryDataSet(algoKey, "yem_gathering", String.join(",", selectfields), qFilter.toArray());
        yemShippingdetails = yemShippingdetails.groupBy(new String[]{"yem_titleid"})
                .sum("yem_salcontractclaamt")
                .finish();
        yemShippingdetails = getYemShippingdetails(qFilter, yemShippingdetails);
        return yemShippingdetails;
    }

    /**
     * 收款单认领时间
     *
     * @param qFilter
     * @param yemShippingdetails
     * @return
     */
    private static DataSet getYemShippingdetails(QFilter qFilter, DataSet yemShippingdetails) {
        List<String> selectfield = new ArrayList<>();
        selectfield.add("yem_receiptdetail.yem_claimdetail.yem_salcontractno.id yem_salcontractnoid");//收款单的合同号id
        selectfield.add("yem_bizdate paymenttimes");//
        DataSet yemShippingdetail = ORM.create().queryDataSet(algoKey, "yem_gathering", String.join(",", selectfield), qFilter.toArray());
        yemShippingdetail = yemShippingdetail.groupBy(new String[]{"yem_salcontractnoid"}).max("paymenttimes").finish();
        yemShippingdetail = yemShippingdetail.addField("TO_CHAR(paymenttimes, 'yyyy-MM-dd') paymenttime","paymenttime");
        yemShippingdetails = yemShippingdetail.leftJoin(yemShippingdetails)
                .on("yem_salcontractnoid", "yem_titleid")
                .select(RptUtil.getDataSetFiledAlias(yemShippingdetail), RptUtil.getDataSetFiledAlias(yemShippingdetails))
                .finish();
        DataSet claimedAmt = queryGathering_ClaimedAmt();
        yemShippingdetails = yemShippingdetails.leftJoin(claimedAmt).on("yem_salcontractnoid","salesorderid")
                .select(RptUtil.getDataSetFiledAlias(yemShippingdetails), RptUtil.getDataSetFiledAlias(claimedAmt)).finish();
        return yemShippingdetails;
    }

    /**
     * 查询合同各个款项性质的已认领金额合计
     *
     * @return
     */
    private static DataSet queryGathering_ClaimedAmt() {
        QFilter qFilter = getBaseQFilter(new String[]{"B", "C"});
        List<String> selectfields = new ArrayList<>();
        selectfields.add("yem_receiptdetail.yem_claimdetail.yem_salcontractno.id salesorderid");
        selectfields.add("yem_receiptdetail.yem_claimdetail.yem_claimamt yem_theamountpaid");//收款认领金额
        DataSet dataSet = ORM.create().queryDataSet(algoKey, "yem_gathering", String.join(",", selectfields), qFilter.toArray());
        dataSet = dataSet
                .groupBy(new String[]{"salesorderid"})
                .sum("yem_theamountpaid")
                .finish();
        return dataSet;
    }

    /**
     * 装箱单
     *
     * @return
     */
    private DataSet yemImEncasement() {
        QFilter qFilter = getBaseQFilter();
        List<String> selectfields = new ArrayList<>();
        selectfields.add("yem_corebillid encasementcorebillid");
        selectfields.add("yem_completionstatuspj yem_completionstatuspj");
        DataSet yemEsSalesorder = ORM.create().queryDataSet(algoKey, "yem_im_encasement", String.join(",", selectfields), qFilter.toArray());
        return yemEsSalesorder;
    }

    /**
     * 订舱通知单
     *
     * @return
     */
    private DataSet yemEsStoragetrans() {
        QFilter qFilter = getBaseQFilter();
        List<String> selectfields = new ArrayList<>();
        selectfields.add("yem_corebillid yem_corebillid");
        selectfields.add("yem_origcurrepremium yem_origcurrepremium");
        DataSet yemEsSalesorder = ORM.create().queryDataSet(algoKey, "yem_es_storagetrans", String.join(",", selectfields), qFilter.toArray());
        yemEsSalesorder = yemEsSalesorder.groupBy(new String[]{"yem_corebillid"}).sum("yem_origcurrepremium").finish();
        return yemEsSalesorder;
    }

    /**
     * 外销合同
     *
     * @return
     */
    private DataSet yemEsSalesorder() {
        QFilter qFilter = getBaseQFilter();
        qFilter.and("yem_es_materialinfo.yem_businesssort", QCP.equals, "P");
        qFilter.and("yem_signconfirmstatus",QCP.equals,"A");
        qFilter.and("yem_cancelstatus",QCP.equals,"A");
        List<String> selectfields = new ArrayList<>();
        selectfields.add("id queryDeliverNoticeid");
        selectfields.add("yem_operator yem_salesman");
        selectfields.add("yem_billtype.name yem_billtype");
        selectfields.add("billno yem_billno");
        selectfields.add("yem_customer yem_customer");
        selectfields.add("yem_priceitem yem_priceitem");
        selectfields.add("yem_offeramount yem_offeramount");
//        selectfields.add("yem_offeramount yem_offeramounts");
        selectfields.add("yem_interestamt yem_interestamt");
        selectfields.add("yem_creditamt yem_creditamt");
        selectfields.add("yem_fundpoolamt yem_fundpoolamt");
        selectfields.add("yem_premiumamt yem_premiumamt");
        selectfields.add("yem_customer.name yem_client");
        selectfields.add("yem_seafreight yem_seafreight");
        selectfields.add("yem_landcarrycost yem_landcarrycost");
        selectfields.add("yem_airliftcost yem_airliftcost");
        selectfields.add("yem_expresscost yem_expresscost");
        selectfields.add("yem_offeramount yem_contractamount");
        selectfields.add("yem_clientcountry yem_clientcountry");
        selectfields.add("TO_CHAR(yem_acshipdate, 'yyyy-MM-dd') yem_acshipdate");
        selectfields.add("yem_reccondition yem_reccondition");
        selectfields.add("yem_currency.name yem_currency");
        selectfields.add("yem_companyname yem_companyname");
        selectfields.add("yem_bd_products.name yem_bd_products");
        DataSet yemEsSalesorder = ORM.create().queryDataSet(algoKey, "yem_es_salesorder", String.join(",", selectfields), qFilter.toArray());
        yemEsSalesorder = yemEsSalesorder.distinct();
        yemEsSalesorder = yemEsSalesorder.select(String.join(",", RptUtil.getDataSetFiledAlias(yemEsSalesorder)) +
                ",yem_seafreight+yem_landcarrycost+yem_airliftcost+yem_expresscost yem_freight");
        DataSet rightDataSet = yemEsSalesorders();
        yemEsSalesorder = yemEsSalesorder.leftJoin(rightDataSet).on("queryDeliverNoticeid", "Noticeid")
                .select(RptUtil.getDataSetFiledAlias(yemEsSalesorder), RptUtil.getDataSetFiledAlias(rightDataSet)).finish();
       DataSet yemPlaceexamine  = yemPlaceexamine();
       yemEsSalesorder = yemEsSalesorder.leftJoin(yemPlaceexamine).on("queryDeliverNoticeid","yem_sourcebillid")
               .select(RptUtil.getDataSetFiledAlias(yemEsSalesorder), RptUtil.getDataSetFiledAlias(yemPlaceexamine)).finish();
        DataSet yemEsDelivernotice = yemEsDelivernotice();
        yemEsSalesorder = yemEsSalesorder.leftJoin(yemEsDelivernotice).on("queryDeliverNoticeid","delivernoticecorebillid")
                .select(RptUtil.getDataSetFiledAlias(yemEsSalesorder), RptUtil.getDataSetFiledAlias(yemEsDelivernotice)).finish();
        DataSet esSalesorder = EsSalesorder();
        yemEsSalesorder = yemEsSalesorder.leftJoin(esSalesorder).on("queryDeliverNoticeid","newsalesorderid")
                .select(RptUtil.getDataSetFiledAlias(yemEsSalesorder),RptUtil.getDataSetFiledAlias(esSalesorder)).finish();
        yemEsSalesorder = yemEsSalesorder.where("billstatus = 'B' OR billstatus = 'C'");
        yemEsSalesorder = yemEsSalesorder.where("delivernoticebillstatus  != 'C'");
        yemEsSalesorder = yemEsSalesorder.distinct();
        return yemEsSalesorder;
    }/**
     * 外销合同多选基础资料
     *
     * @return
     */
    private DataSet EsSalesorder() {
        QFilter qFilter = getBaseQFilter();
        qFilter.and("yem_es_materialinfo.yem_businesssort", QCP.equals, "P");
        qFilter.and("yem_signconfirmstatus",QCP.equals,"A");
        qFilter.and("yem_cancelstatus",QCP.equals,"A");
        List<String> selectfields = new ArrayList<>();
        selectfields.add("id newsalesorderid");
        selectfields.add("yem_shipports.fbasedataid.name yem_shipports");//起运港
        selectfields.add("yem_destports.fbasedataid.name yem_destports");//目的港
        DataSet yemEsSalesorder = ORM.create().queryDataSet(algoKey, "yem_es_salesorder", String.join(",", selectfields), qFilter.toArray());
        yemEsSalesorder = yemEsSalesorder.groupBy(new String[]{"newsalesorderid"})
                .agg(new GroupConcatFunctionByComma(), "yem_shipports", "yem_shipports")
                .agg(new GroupConcatFunctionByComma(), "yem_destports", "yem_destports")
                .finish();
        return yemEsSalesorder;
    }



    /**
     * 销售出库
     * @return
     */
    private DataSet yemEsDelivernotice() {
        QFilter qFilter = getBaseQFilter(new String[]{"A","B","C"});
        List<String> selectfields = new ArrayList<>();
        selectfields.add("yem_corebillid delivernoticecorebillid");
        selectfields.add("billstatus delivernoticebillstatus");
        selectfields.add("billno delivernoticebillno");
        selectfields.add("TO_CHAR(auditdate, 'yyyy-MM-dd') yem_shipdate");
        DataSet yemEsSalesorder = ORM.create().queryDataSet(algoKey, "yem_es_delivernotice", String.join(",", selectfields), qFilter.toArray());
        DataSet yemEsDelivernotice = yem_esDelivernotice();
        yemEsSalesorder = yemEsSalesorder.leftJoin(yemEsDelivernotice).on("delivernoticecorebillid","esdelivernoticecorebillid")
                .select(RptUtil.getDataSetFiledAlias(yemEsSalesorder), RptUtil.getDataSetFiledAlias(yemEsDelivernotice)).finish();
        return yemEsSalesorder;
    }
    /**
     * 销售出库
     * @return
     */
    private DataSet yem_esDelivernotice() {
        QFilter qFilter = getBaseQFilter(new String[]{"A","B","C"});
        List<String> selectfields = new ArrayList<>();
        selectfields.add("yem_corebillid esdelivernoticecorebillid");
        selectfields.add("yem_es_materialinfo.yem_qty delivernoticeqty");
        selectfields.add("yem_totalallamount yem_totalallamount");
        DataSet yemEsSalesorder = ORM.create().queryDataSet(algoKey, "yem_es_delivernotice", String.join(",", selectfields), qFilter.toArray());
        yemEsSalesorder.groupBy(new String[]{"esdelivernoticecorebillid"}).sum("delivernoticeqty").sum("yem_totalallamount").finish();
        return yemEsSalesorder;
    }
    private DataSet yemPlaceexamine() {
        QFilter qFilter = getBaseQFilter(new String[]{"B","C"});
        List<String> selectfields = new ArrayList<>();
        selectfields.add("yem_sourcebillid yem_sourcebillid");
        selectfields.add("billstatus billstatus");
        DataSet yemEsSalesorder = ORM.create().queryDataSet(algoKey, "yem_placeexamine", String.join(",", selectfields), qFilter.toArray());
        DataSet yemPlaceexamine = yem_placeexamine();
        yemEsSalesorder = yemEsSalesorder.leftJoin(yemPlaceexamine).on("yem_sourcebillid","yemsourcebillid")
                .select(RptUtil.getDataSetFiledAlias(yemEsSalesorder), RptUtil.getDataSetFiledAlias(yemPlaceexamine)).finish();
        return yemEsSalesorder;
    }
  private DataSet yem_placeexamine() {
        QFilter qFilter = getBaseQFilter(new String[]{"B","C"});
        List<String> selectfields = new ArrayList<>();
        selectfields.add("yem_sourcebillid yemsourcebillid");
        selectfields.add("yem_es_materialinfo.yem_qty placeexamineqty");
        selectfields.add("yem_es_materialinfo.yem_amt placeexamineamt");
        DataSet yemEsSalesorder = ORM.create().queryDataSet(algoKey, "yem_placeexamine", String.join(",", selectfields), qFilter.toArray());
      yemEsSalesorder = yemEsSalesorder.groupBy(new String[]{"yemsourcebillid"}).sum("placeexamineqty").sum("placeexamineamt").finish();
        return yemEsSalesorder;
    }

    /**
     * 外销合同
     *
     * @return
     */
    private DataSet yemEsSalesorders() {
        QFilter qFilter = getBaseQFilter();
        qFilter.and("yem_signconfirmstatus",QCP.equals,"A");
        qFilter.and("yem_cancelstatus",QCP.equals,"A");
        qFilter.and("yem_es_materialinfo.yem_businesssort", QCP.equals, "P");
        List<String> selectfields = new ArrayList<>();
        selectfields.add("id Noticeid");
        selectfields.add("yem_es_materialinfo.yem_qty yem_qty");
        DataSet yemEsSalesorder = ORM.create().queryDataSet(algoKey, "yem_es_salesorder", String.join(",", selectfields), qFilter.toArray());
        yemEsSalesorder = yemEsSalesorder.groupBy(new String[]{"Noticeid"}).sum("yem_qty").finish();
        return yemEsSalesorder;
    }

}
