package yem.wm.cm.csrm.dynamic;

import kd.bos.algo.DataSet;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.chart.PointLineChart;
import kd.bos.form.control.AbstractGrid;
import kd.bos.form.control.TreeEntryGrid;
import kd.bos.form.control.events.SelectRowsEvent;
import kd.bos.form.control.events.SelectRowsEventListener;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import org.apache.cxf.Bus;
import yem.base.common.utils.PointLineChartHelper;
import yem.base.common.utils.YEM;
import yem.base.common.utils.rptfunction.GroupTopOneFunction;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.oracle.truffle.js.builtins.ArrayPrototypeBuiltins.ArrayPrototype.forEach;
import static kd.bos.kscript.dom.expr.ExprType.Int;

/**
 * 价格管理-首页-价格分析（动态表单插件）
 *  @author lib
 */
public class PriceAnalyzeEdit extends AbstractFormPlugin
{
    private static final String algoKey = PriceAnalyzeEdit.class.getName();

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

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        setPriceInfo();
        setDrawingInfo();
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        ChangeData[] changeSet = e.getChangeSet();
        int rowIndex = changeSet[0].getRowIndex();
        String name = e.getProperty().getName();
        switch(name) {
            case "yem_pricetype" ://价格类型
            case "yem_materiel":// 商品
                setPriceInfo();
                setDrawingInfo();
                break;
            default:
                break;
        }
    }
    // 根据价格详情给刷新折线图
    private void setDrawingInfo(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String yem_pricetype  = (String)this.getView().getModel().getValue("yem_pricetype");// 价格类型
        DynamicObjectCollection yemPriceinfo = this.getView().getModel().getEntryEntity("yem_priceinfo");
        PointLineChart pointLineChart = this.getView().getControl("yem_pointlinechartap");
        pointLineChart.clearData();
        Map<String,Map<String, BigDecimal>> data = new HashMap<>();
        for(DynamicObject info : yemPriceinfo){
            Date yem_bizdate = info.getDate("yem_bizdate");// 价格日期
            DynamicObject yem_pm_area = info.getDynamicObject("yem_pm_area");//区域
            String areaName = yem_pm_area == null? "":yem_pm_area.getString("name");
            DynamicObject yem_pm_market = info.getDynamicObject("yem_pm_market");//市场
            String marketName = yem_pm_market == null? "":yem_pm_market.getString("name");
            DynamicObject yem_pm_productionfirm = info.getDynamicObject("yem_pm_productionfirm");//生产企业
            String firmName = yem_pm_productionfirm == null? "":yem_pm_productionfirm.getString("name");
            DynamicObject yem_pm_exchange = info.getDynamicObject("yem_pm_exchange");//交易所
            String exchangeName = yem_pm_exchange == null? "":yem_pm_exchange.getString("name");
            String yem_contractname = info.getString("yem_contractname");//合约名称
            String yem_materiels = info.getString("yem_materiels");//商品名称
            String yem_specification = info.getString("yem_specification");//规格型号
            DynamicObject yem_unit = info.getDynamicObject("yem_unit");//计量单位
            String unitName = yem_unit == null? "":yem_unit.getString("name");
            DynamicObject yem_currency = info.getDynamicObject("yem_currency");//币别
            String unitNumber = yem_currency == null? "":yem_currency.getString("number");
            BigDecimal yem_openprice = info.getBigDecimal("yem_openprice");//开盘价
            BigDecimal yem_closeprice = info.getBigDecimal("yem_closeprice");//收盘价
            BigDecimal yem_settleprice = info.getBigDecimal("yem_settleprice");//结算价
            BigDecimal yem_price = info.getBigDecimal("yem_price");//价格
            BigDecimal yem_changerangev = info.getBigDecimal("yem_changerangev");//涨跌
            BigDecimal yem_changerange = info.getBigDecimal("yem_changerange");//涨跌%
            String change  = "";
            if (BigDecimal.ZERO.compareTo(yem_changerange) < 0){
                change = "-涨"+yem_changerange+"%";
            } else if (BigDecimal.ZERO.compareTo(yem_changerange) > 0){
                change = "-跌"+yem_changerange+"%";
            }
            Map<String, BigDecimal> map = new HashMap<>();
            String date = format.format(yem_bizdate);
            if (data.containsKey(date)){
                map = data.get(date);
            }
            switch(yem_pricetype){
                case "1": // 市场价格
                    // 区域-市场-规格-涨/跌
                    map.put(areaName+"-"+marketName+"-"+yem_specification,yem_price);
                    break;
                case "2": // 期货价格
                    // 交易所-合约名称-涨/跌
                    map.put(exchangeName+"-"+yem_contractname+yem_specification,yem_settleprice);
                    break;
                case "3": // 企业报价
                    // 生产企业-区域-市场-规格-涨/跌
                    map.put(firmName+"-"+areaName+"-"+marketName+"-"+yem_specification,yem_price);
                    break;
                default:
                    break;
            }
            data.put(date,map);
        }
        PointLineChartHelper.drawChart(pointLineChart,data,"日期","价格");
        pointLineChart.refresh();
    }
    // 根据价格类型给价格详情分录赋值
    private void setPriceInfo(){
        IDataModel model = this.getView().getModel();
        this.getView().getModel().deleteEntryData("yem_priceinfo");
        DynamicObjectCollection priceInfo = queryPriceInfo();
        if (priceInfo != null && !priceInfo.isEmpty()){
            for(DynamicObject info : priceInfo){
                int i = model.createNewEntryRow("yem_priceinfo");
                //区域
                long yemPmArea = info.getLong("yem_pm_area");
                DynamicObject yem_pm_area  = null;
                if (!YEM.isEmpty(yemPmArea)){
                    DynamicObject[] loadArea = BusinessDataServiceHelper.load("yem_pm_area",
                            "id,name",new QFilter[]{new QFilter("id",QCP.equals,yemPmArea)});
                    if (loadArea.length > 0){
                        yem_pm_area = loadArea[0];
                    }
                }
                model.setValue("yem_pm_area",yem_pm_area,i);
                //市场
                long yemPmMarket = info.getLong("yem_pm_market");
                DynamicObject yem_pm_market  = null;
                if (!YEM.isEmpty(yemPmMarket)){
                    DynamicObject[] loadMarket = BusinessDataServiceHelper.load("yem_pm_market",
                            "id,name",new QFilter[]{new QFilter("id",QCP.equals,yemPmMarket)});
                    if (loadMarket.length > 0){
                        yem_pm_market = loadMarket[0];
                    }
                }
                model.setValue("yem_pm_market",yem_pm_market,i);
                //生产企业
                long yemPmFirm = info.getLong("yem_pm_productionfirm");
                DynamicObject yem_pm_productionfirm  = null;
                if (!YEM.isEmpty(yemPmMarket)){
                    DynamicObject[] loadFirm = BusinessDataServiceHelper.load("yem_pm_productionfirm",
                            "id,name",new QFilter[]{new QFilter("id",QCP.equals,yemPmFirm)});
                    if (loadFirm.length > 0){
                        yem_pm_productionfirm = loadFirm[0];
                    }
                }
                model.setValue("yem_pm_productionfirm",yem_pm_productionfirm,i);
                //交易所
                long yemPmExchange = info.getLong("yem_pm_exchange");
                DynamicObject yem_pm_exchange  = null;
                if (!YEM.isEmpty(yemPmExchange)){
                    DynamicObject[] loadExchange = BusinessDataServiceHelper.load("yem_pm_exchange",
                            "id,name",new QFilter[]{new QFilter("id",QCP.equals,yemPmExchange)});
                    if (loadExchange.length > 0){
                        yem_pm_exchange = loadExchange[0];
                    }
                }
                model.setValue("yem_pm_exchange",yem_pm_exchange,i);
                model.setValue("yem_contractname",info.getString("yem_contractname"),i);
                model.setValue("yem_materiels",info.getString("yem_materiels"),i);
                model.setValue("yem_specification",info.getString("yem_specification"),i);
                //计量单位
                long yemUnit = info.getLong("yem_unit");
                DynamicObject yem_unit  = null;
                if (!YEM.isEmpty(yemUnit)){
                    DynamicObject[] loadUnit = BusinessDataServiceHelper.load("bd_measureunits",
                            "id,name",new QFilter[]{new QFilter("id",QCP.equals,yemUnit)});
                    if (loadUnit.length > 0){
                        yem_unit = loadUnit[0];
                    }
                }
                model.setValue("yem_unit",yem_unit,i);
                //币别
                long yemCurrency = info.getLong("yem_currency");
                DynamicObject yem_currency  = null;
                if (!YEM.isEmpty(yemCurrency)){
                    DynamicObject[] loadCurrency = BusinessDataServiceHelper.load("bd_currency",
                            "id,name",new QFilter[]{new QFilter("id",QCP.equals,yemCurrency)});
                    if (loadCurrency.length > 0){
                        yem_currency = loadCurrency[0];
                    }
                }
                model.setValue("yem_currency",yem_currency,i);
                model.setValue("yem_openprice",info.getBigDecimal("yem_openprice"),i);
                model.setValue("yem_closeprice",info.getBigDecimal("yem_closeprice"),i);
                model.setValue("yem_settleprice",info.getBigDecimal("yem_settleprice"),i);
                model.setValue("yem_price",info.getBigDecimal("yem_price"),i);
                model.setValue("yem_changerangev",info.getBigDecimal("yem_changerangev"),i);
                model.setValue("yem_changerange",info.getBigDecimal("yem_changerange"),i);
                model.setValue("yem_bizdate",info.getDate("yem_bizdate"),i);

            }
        }
    }


    // 根据价格类型查询对应价格数据
    private DynamicObjectCollection queryPriceInfo(){
        String yem_pricetype  = (String)this.getView().getModel().getValue("yem_pricetype");
        DataSet result = null;
        switch(yem_pricetype){
            case "1": // 查询市场价格
                result = marketPrice();
                break;
            case "2": // 查询期货价格
                result = futuresPrice();
                break;
            case "3": // 查询企业报价
                result = enterpriseQuote();
                break;
            default:
                break;
        }
        if (result != null){
            return ORM.create().toPlainDynamicObjectCollection(result);
        } else {
            return null;
        }
    }
    // 查询最新市场价格
    private DataSet marketPrice(){
        DynamicObject materiel = (DynamicObject)this.getView().getModel().getValue("yem_materiel");
        Long materielId = materiel == null ? 0L:materiel.getLong("id");
        DataSet result = ORM.create().queryDataSet(algoKey,"yem_pm_marketprice",
                "yem_pm_area,yem_pm_market,yem_materiel.name yem_materiels," +
                        "yem_specification,yem_currency,yem_unit,yem_price,yem_changerangev," +
                        "yem_changerange,yem_bizdate",
                new QFilter[]{new QFilter("billstatus", QCP.equals,"C"),
                        new QFilter("yem_materiel.id", QCP.equals,materielId)},"yem_bizdate");
        result = result.select("yem_pm_area","yem_pm_market","0L yem_pm_productionfirm",
                "0L yem_pm_exchange","'' yem_contractname","yem_materiels","yem_specification"
                ,"yem_unit","yem_currency","0.0 yem_openprice","0.0 yem_closeprice","0.0 yem_settleprice"
                ,"yem_price","yem_changerangev","yem_changerange","yem_bizdate");
        return result;
    }
    // 查询最新期货价格
    private DataSet futuresPrice(){
        DynamicObject materiel = (DynamicObject)this.getView().getModel().getValue("yem_materiel");
        String materielName = materiel == null ? "":materiel.getString("name");
        DataSet result = ORM.create().queryDataSet(algoKey,"yem_fum_futuresprice",
                "yem_contractname,yem_pm_exchange,yem_materiel yem_materiels," +
                        "yem_currency,yem_unit,yem_openprice,yem_closeprice,yem_settleprice,"+
                        "yem_changerangev,yem_bizdate,yem_changerange",
                new QFilter[]{new QFilter("billstatus", QCP.equals,"C"),
                        new QFilter("yem_materiel", QCP.equals,materielName)});
        result = result.select("0L yem_pm_area","0L yem_pm_market","0L yem_pm_productionfirm",
                "yem_pm_exchange","yem_contractname","yem_materiels","'' yem_specification"
                ,"yem_unit","yem_currency","yem_openprice","yem_closeprice","yem_settleprice"
                ,"0.0 yem_price","yem_changerangev","yem_changerange","yem_bizdate");
        return result;
    }
    // 查询最新企业报价
    private DataSet enterpriseQuote(){
        DynamicObject materiel = (DynamicObject)this.getView().getModel().getValue("yem_materiel");
        Long materielId = materiel == null ? 0L:materiel.getLong("id");
        DataSet result = ORM.create().queryDataSet(algoKey,"yem_pm_enterprisequote",
                "yem_pm_area,yem_pm_market,yem_materiel.name yem_materiels," +
                        "yem_specifications yem_specification,yem_currency,yem_unit,yem_price,yem_changerangev," +
                        "yem_changerange,yem_bizdate,yem_pm_productionfirm",
                new QFilter[]{new QFilter("billstatus", QCP.equals,"C"),
                        new QFilter("yem_materiel.id", QCP.equals,materielId)},"yem_bizdate");
        result = result.select("yem_pm_area","yem_pm_market","yem_pm_productionfirm",
                "0L yem_pm_exchange","'' yem_contractname","yem_materiels","yem_specification"
                ,"yem_unit","yem_currency","0.0 yem_openprice","0.0 yem_closeprice","0.0 yem_settleprice"
                ,"yem_price","yem_changerangev","yem_changerange","yem_bizdate");
        return result;
    }



}

