package yem.base.common.module.sso;

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.form.IFormView;
import kd.bos.form.chart.PointLineChart;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import yem.base.common.utils.DateUtil;
import yem.base.common.utils.DynamicObjectUtil;
import yem.base.common.utils.PointLineChartHelper;
import yem.base.common.utils.YEM;

import java.math.BigDecimal;
import java.util.*;

/**
 * 汇率走势--点线图
 *
 * @author zhangh
 */
public class HistoryExchangeRateFormPlugin extends AbstractFormPlugin {

    @Override
    public void afterBindData(EventObject e) {
        long currentOrgId = YEM.getCurrentOrgId();//当前登录组织
        //查询核算组织本位币设置  获取当前组织的本位币
        DynamicObject bd_accountingsys_base = BusinessDataServiceHelper.loadSingle("bd_accountingsys_base", "basecurrrency", new QFilter[]{new QFilter("baseacctorg", QCP.equals, currentOrgId)});
        DynamicObject baseacctorg = null;
        if (bd_accountingsys_base != null) {
            baseacctorg = bd_accountingsys_base.getDynamicObject("basecurrrency");
        } else {//没有设置当前组织的本位币，默认按照人人民币
            baseacctorg = BusinessDataServiceHelper.loadSingle("bd_currency", "id", new QFilter[]{new QFilter("number", QCP.equals, "CNY")});
        }
        this.getModel().setValue("yem_surcurrency", baseacctorg.getLong("id"));
        this.getView().updateView("yem_surcurrency");

        this.getModel().setValue("yem_currencybase", baseacctorg.getLong("id"));
        this.getView().updateView("yem_currencybase");

        Map<String, Map<String, BigDecimal>> data = getData(this.getView(), this.getModel());
        drawChart(data);
    }

    private void drawChart(Map<String, Map<String, BigDecimal>> data) {
        PointLineChart chart = this.getControl("yem_pointlinechartap");
        PointLineChartHelper.drawChart(chart, data, "日期", "汇率");
    }

    public Map<String, Map<String, BigDecimal>> getData(IFormView view, IDataModel model) {
        DynamicObject yem_tagcurrency = (DynamicObject) model.getValue("yem_tagcurrency");
        Long tagcurrency = yem_tagcurrency != null ? yem_tagcurrency.getLong("id") : 0L;
        DynamicObject yem_surcurrency = (DynamicObject) model.getValue("yem_surcurrency");
        Long surcurrency = yem_surcurrency != null ? yem_surcurrency.getLong("id") : 0L;
        Date yem_datebegin = (Date) model.getValue("yem_datebegin");
        Date yem_dateend = (Date) model.getValue("yem_dateend");
        List<QFilter> qFilters = new ArrayList<>();
        qFilters.add(new QFilter("status", QCP.equals, "C"));
        qFilters.add(new QFilter("enable", QCP.equals, "1"));
        qFilters.add(new QFilter("orgcur", QCP.equals, tagcurrency));
        qFilters.add(new QFilter("cur", QCP.equals, surcurrency));
        if (YEM.isNotEmpty(yem_datebegin) && YEM.isNotEmpty(yem_dateend)) {
            qFilters.add(new QFilter("effectdate", ">", yem_datebegin));
            qFilters.add(new QFilter("effectdate", "<", yem_dateend));
        } else {
            qFilters.add(new QFilter("effectdate", ">", DateUtil.getMonthFirstDay(new Date())));
            qFilters.add(new QFilter("effectdate", "<", new Date()));
        }
        String selectFields = DynamicObjectUtil.getSelectfields("bd_exrate_tree", false);
        DynamicObject[] bd_exrate_tree = BusinessDataServiceHelper.load("bd_exrate_tree", selectFields,
                qFilters.toArray(new QFilter[0]), "effectdate");
        Map<String, Map<String, BigDecimal>> datas = new HashMap<>();
        List<String> dateList = new ArrayList<>();

        for (DynamicObject exrate : bd_exrate_tree) {
            String effectdate = DateUtil.formatDate(exrate.getDate("effectdate"));
            String curName = exrate.getLocaleString("orgcur.name").getLocaleValue();
            BigDecimal excval = exrate.getBigDecimal("excval");
            if (datas.containsKey(effectdate)) {//生效日期
                datas.get(effectdate).put(curName, excval);
            } else {
                Map<String, BigDecimal> map = new HashMap<>();
                map.put(curName, excval);
                datas.put(effectdate, map);
            }
            if (!dateList.contains(effectdate)) {
                dateList.add(effectdate);
            }
        }

        return datas;
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String name = e.getProperty().getName();
        ChangeData[] changeSet = e.getChangeSet();
        int rowIndex = changeSet[0].getRowIndex();

        switch (name) {
            case "yem_tagcurrency":
            case "yem_surcurrency":
            case "yem_datebegin":
            case "yem_dateend":
                Map<String, Map<String, BigDecimal>> data = getData(this.getView(), this.getModel());
                drawChart(data);
                break;

            case "yem_currency":
            case "yem_datecurrency":
                setEntryInfor(rowIndex, this.getModel());
                break;

            default:
                break;
        }
    }

    public void setEntryInfor(int rowIndex, IDataModel model) {
        DynamicObject yem_currency = (DynamicObject) this.getModel().getValue("yem_currency", rowIndex);
        DynamicObject yem_currencybase = (DynamicObject) this.getModel().getValue("yem_currencybase");
        DynamicObject yem_exchangetable = (DynamicObject) this.getModel().getValue("yem_exchangetable");
        Date yem_datecurrency = (Date) this.getModel().getValue("yem_datecurrency", rowIndex);
        BigDecimal rate = YEM.getExchangeRate(yem_exchangetable, yem_currency, yem_currencybase, yem_datecurrency);
        BigDecimal yesterdayRate = YEM.getExchangeRate(yem_exchangetable, yem_currency, yem_currencybase, DateUtil.addDays(yem_datecurrency, -1));
        BigDecimal range = rate.subtract(yesterdayRate);

        this.getModel().setValue("yem_rate", rate, rowIndex);

        String yem_range = "";
        if (range.compareTo(BigDecimal.ZERO) > 0) {
            yem_range = "涨⬆ " + range;
            YEM.changeRowColor(this.getView(), "yem_entryentity", rowIndex, "red", "");
        } else if (range.compareTo(BigDecimal.ZERO) < 0) {
            yem_range = "跌⬇ " + range.abs();
            YEM.changeRowColor(this.getView(), "yem_entryentity", rowIndex, "green", "");
        }

        this.getModel().setValue("yem_range", yem_range, rowIndex);
    }
}
