package yem.wm.cm.csrm.form;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.form.FormShowParameter;
import kd.bos.form.control.Image;
import kd.bos.form.control.Label;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;
import yem.base.common.utils.YEM;
import yem.wm.cm.csrm.enums.PageIdEnum;

import java.util.Arrays;
import java.util.Comparator;
import java.util.EventObject;

/**
 * 评分金字塔
 *
 * @Author yunshuaiwei
 * @Date 2024/6/3 15:57
 **/
public class ScorePyramidPlugin extends AbstractFormPlugin implements Plugin {

    @Override
    public void afterCreateNewData(EventObject e) {
        // TODO 在此添加业务逻辑
        FormShowParameter formShowParameter = this.getView().getFormShowParameter();
        String searchKey = formShowParameter.getCustomParam("searchKey");
        Long id = formShowParameter.getCustomParam("id");
        DynamicObject scoreMerchant = null;
        if (YEM.isNotEmpty(id)) {
            scoreMerchant = BusinessDataServiceHelper.loadSingle(PageIdEnum.SCORE_MERCHANT.getPageId(), new QFilter[]{new QFilter("id", QCP.equals, id)});
        }
        if (YEM.isNotEmpty(searchKey) && scoreMerchant == null) {
            DynamicObject[] dynamicObjects = BusinessDataServiceHelper.load(PageIdEnum.SCORE_MERCHANT.getPageId(), "id,number,yem_totalscore1,yem_gradingscale,createtime", new QFilter[]{new QFilter("yem_societycreditcode", QCP.equals, searchKey)});
            if (YEM.isNotEmpty(dynamicObjects)) {
                Arrays.sort(dynamicObjects, new Comparator<DynamicObject>() {
                    @Override
                    public int compare(DynamicObject o1, DynamicObject o2) {
                        return o2.getDate("createtime").compareTo(o1.getDate("createtime"));
                    }
                });
                scoreMerchant = dynamicObjects[0];
            }
        }
        if (YEM.isNotEmpty(scoreMerchant)) {
            //评分等级
            DynamicObject yemGradingScale = scoreMerchant.getDynamicObject("yem_gradingscale");
            if (YEM.isNotEmpty(yemGradingScale)) {
                Object score = scoreMerchant.get("yem_totalscore1");
                Image image = this.getControl("yem_imageap");
                image.setUrl(String.format("/isv/yem/globalimgs/images/%s.png", yemGradingScale.getString("number")));
                //得分
                Label scoreLab = this.getView().getControl("yem_labelap4");
                Label levelLab = this.getView().getControl("yem_labelap1");
                scoreLab.setText(String.valueOf(score));
                levelLab.setText(yemGradingScale.getString("name"));
            }
        }
    }
}