package com.yem.rf.salescommission;

import com.yem.wm.utils.RptUtil;
import com.yem.wm.utils.YEM;
import kd.bos.algo.DataSet;
import kd.bos.dataentity.entity.DynamicObject;
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.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import org.apache.commons.compress.utils.Lists;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.yem.rf.salescommission.CompleteShipDetailReportPlugin.queryGathering_ClaimDate;
import static com.yem.rf.salescommission.CompleteShipDetailReportPlugin.querySalesOrder_PayRate;
import static com.yem.rf.utils.RFUtils.formatDate;
import static com.yem.rf.utils.RFUtils.getBaseQFilter;

/**
 * @Description: TODO
 * @Date: 2024/7/8 10:24
 * @Created: by ZZSLL
 */

public class SalesCommissionReportPlugin extends AbstractReportListDataPlugin {

    private static final String algoKey = SalesCommissionReportPlugin.class.getName();

    @Override
    public DataSet query(ReportQueryParam param, Object o) throws Throwable {
        DataSet resDataSet;
        DataSet delivernotice = queryDeliverNotice(param);
        DataSet storagetrans = queryStorageTrans(param);
        DataSet salesorder = querySalesOrder(param);
        DataSet claimedAmt = queryGathering_ClaimedAmt_Total();
        ArrayList<Long> ids = querySalesOrderIds();
        DataSet payRate = querySalesOrder_PayRate(ids);
        DataSet claimDate = queryGathering_ClaimDate(ids, payRate);
        resDataSet = delivernotice.leftJoin(storagetrans)
                .on("delivernoticeid", "storagetransid")
                .select(RptUtil.getDataSetFiledAlias(delivernotice), RptUtil.getDataSetFiledAlias(storagetrans))
                .finish();
        resDataSet = resDataSet.leftJoin(salesorder)
                .on("coreentryid", "salesorderenid")
                .select(RptUtil.getDataSetFiledAlias(resDataSet), RptUtil.getDataSetFiledAlias(salesorder))
                .finish();
        resDataSet = resDataSet.leftJoin(claimedAmt)
                .on("salesorderid", "main_id_g_claimed_amt_fk")
                .select(RptUtil.getDataSetFiledAlias(resDataSet), RptUtil.getDataSetFiledAlias(claimedAmt))
                .finish();
        claimDate = claimDate.select("main_id_gathering_fk, yem_prodpaydate yem_firstpaydate, yem_endpaydate yem_lastpaydate");
        resDataSet = resDataSet.leftJoin(claimDate)
                .on("salesorderid", "main_id_gathering_fk")
                .select(RptUtil.getDataSetFiledAlias(resDataSet), RptUtil.getDataSetFiledAlias(claimDate))
                .finish();

        resDataSet = resDataSet.select(String.join(",", RptUtil.getDataSetFiledAlias(resDataSet)) +
                ", yem_safobamount - yem_singlepartgiftmat yem_actualsalesamt, " +//实际销售金额
                "(yem_safobamount - yem_singlepartgiftmat) * yem_exrate yem_actualsalesamtba, " +//实际销售金额（人民币)
                "(yem_safobamount - yem_singlepartgiftmat) * yem_exrate - yem_companystandamt yem_assstand, " +//考核标准
                "CASE WHEN yem_salcontractclaamt >= yem_offeramount THEN 'A' ELSE 'B' END yem_amtcomplete");//是否全款
        StringBuilder where = new StringBuilder();

        FilterInfo filter = param.getFilter();
        String salesorderno = filter.getString("yem_salesorderno");//合同号
        long producttype = filter.getLong("yem_bd_producttype.id");//产品分类
        long customer = filter.getLong("yem_bd_customer");//客户
        long products = filter.getLong("yem_bd_products");//机型
        long resourceno = filter.getLong("yem_resourceno");//资源号
        Date start = filter.getDate("yem_ladingdate_start");//提单日期-开始
        Date end = filter.getDate("yem_ladingdate_end");//提单日期-结束
        where.append("salesorder_billtype IN ('yem_es_salesorder_nmzj', 'yem_es_salesorder_ZJ') AND salesorder_commissiontype IN ('Z', 'ZP')");
        if (YEM.isNotEmpty(salesorderno)) {
            where.append(" AND yem_contractno LIKE '%").append(salesorderno).append("%'");
        }
        if (producttype > 0) {
            where.append(" AND yem_products = ").append(producttype);
        }
        if (customer > 0) {
            where.append(" AND yem_customer = ").append(customer);
        }
        if (products > 0) {
            where.append(" AND yem_productmodel = ").append(products);
        }
        if (resourceno > 0) {
            where.append(" AND yem_resourcescode = ").append(resourceno);
        }
            if (YEM.isNotEmpty(start)) {
            where.append(" AND TO_DATE(yem_ladingdatetext,'yyyy-MM-dd') >= ").append(String.format("TO_DATE('%s','yyyy-MM-dd')", formatDate(start)));
        }
        if (YEM.isNotEmpty(end)) {
            where.append(" AND TO_DATE(yem_ladingdatetext,'yyyy-MM-dd') <= ").append(String.format("TO_DATE('%s','yyyy-MM-dd')", formatDate(end)));
        }
        resDataSet = resDataSet.where(where.toString());

        return resDataSet;
    }

    private ArrayList<Long> querySalesOrderIds() {
        QFilter qFilter = getBaseQFilter();
        qFilter.and("yem_billtype.number", "in", new String[]{"yem_es_salesorder_nmzj", "yem_es_salesorder_ZJ"});
        DynamicObject[] load = BusinessDataServiceHelper.load("yem_es_salesorder", "id", qFilter.toArray());
        ArrayList<Long> list = Lists.newArrayList();
        for (DynamicObject dynamicObject : load) {
            list.add(dynamicObject.getLong("id"));
        }
        return list;
    }

    /**
     * 销售出库
     * @param param 产品分类、客户、合同号、机型、资源号
     * @return
     */
    private DataSet queryDeliverNotice(ReportQueryParam param) {
        QFilter qFilter = getBaseQFilter();
        List<String> selectfields = new ArrayList<>();
        selectfields.add("yem_es_materialinfo.yem_sourceentryid delivernoticeid");
        selectfields.add("yem_es_materialinfo.yem_coreentryid coreentryid");
        selectfields.add("yem_corebillid corebillid");
        selectfields.add("yem_contractnum yem_contractno");//合同号
        selectfields.add("yem_bd_products yem_products");
        selectfields.add("yem_customer");//客户
        selectfields.add("yem_es_materialinfo.id detailid");
        selectfields.add("yem_es_materialinfo.yem_es_salesorder_z.yem_vehicleno yem_vehicleno");//整机编号
        selectfields.add("yem_es_materialinfo.yem_es_salesorder_z.yem_resourcescode yem_resourcescode");//资源号
        selectfields.add("yem_es_materialinfo.yem_es_salesorder_z.yem_milltype yem_productmodel");//资源号
        selectfields.add("yem_es_materialinfo.yem_qty yem_qty");//数量
        selectfields.add("yem_currency yem_currency");//结算币别
        selectfields.add("yem_exrate yem_exrate");//汇率
        selectfields.add("createtime");

        return ORM.create().queryDataSet(algoKey, "yem_es_delivernotice", String.join(",", selectfields), qFilter.toArray())
                .orderBy(new String[]{"createtime DESC"});
    }

    /**
     * 订舱通知单
     * @param param 提单日期
     * @return
     */
    private DataSet queryStorageTrans(ReportQueryParam param) {
        QFilter qFilter = getBaseQFilter();

        List<String> selectfields = new ArrayList<>();
        selectfields.add("yem_es_materialinfo.yem_sourceentryid storagetransid");
        selectfields.add("yem_clientcountry yem_clientcountry");//贸易国别
        selectfields.add("TO_CHAR(yem_tddate, 'yyyy-MM-dd') yem_ladingdatetext");//提单日期
        return ORM.create().queryDataSet(algoKey, "yem_es_storagetrans", String.join(",", selectfields), qFilter.toArray());
    }

    /**
     * 外销合同
     * @param param
     * @return
     */
    private DataSet querySalesOrder(ReportQueryParam param) {
        QFilter qFilter = getBaseQFilter();
        qFilter.and("yem_billtype.number", "in", new String[]{"yem_es_salesorder_nmzj", "yem_es_salesorder_ZJ"});

        List<String> selectfields = new ArrayList<>();
        selectfields.add("id salesorderid");
        selectfields.add("yem_es_materialinfo.id salesorderenid");
        selectfields.add("yem_reccondition yem_reccondition");//收款条件
        selectfields.add("yem_es_materialinfo.yem_saamtpriceclause yem_safobamount");//销售金额（价格条款）  整机合计价格
        selectfields.add("yem_es_materialinfo.yem_singlepartgiftmat yem_singlepartgiftmat");//单台配件赠送金额 赠送配件金额
        selectfields.add("yem_es_materialinfo.yem_fobamount yem_companystandamt");//公司标准价
        selectfields.add("CASE WHEN yem_issinosurecon = '1' THEN 'A' ELSE 'B' END yem_iscredit");//是否信保合同
        selectfields.add("yem_billtype.number salesorder_billtype");//单据类型
        selectfields.add("yem_es_materialinfo.yem_commissiontype salesorder_commissiontype");//业务分类
        selectfields.add("yem_offeramount");

        return ORM.create().queryDataSet(algoKey, "yem_es_salesorder", String.join(",", selectfields), qFilter.toArray());
    }

    /**
     * 查询合同各个款项性质的已认领金额合计
     *
     * @return
     */
    public static DataSet queryGathering_ClaimedAmt_Total() {
        QFilter qFilter = getBaseQFilter(new String[]{"B", "C"});
        List<String> selectfields = new ArrayList<>();

        selectfields.add("yem_receiptdetail.yem_claimdetail.yem_salcontractno.id main_id_g_claimed_amt_fk");
        selectfields.add("yem_receiptdetail.yem_claimdetail.yem_claimamt yem_salcontractclaamt");//收款认领金额

        DataSet dataSet = ORM.create().queryDataSet(algoKey, "yem_gathering", String.join(",", selectfields), qFilter.toArray());
        dataSet = dataSet
                .groupBy(new String[]{"main_id_g_claimed_amt_fk"})
                .sum("yem_salcontractclaamt")
                .finish();

        return dataSet;
    }
}
