package com.yem.wm.task;

import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.YEM;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.exception.KDException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.api.MessageHandler;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.workflow.engine.msg.info.MessageInfo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhouc
 * @date 2024-04-13
 * @className TrackconsoleSendMessageTask
 * @description 定时发送消息
 */
public class TrackconsoleSendMessageTask extends AbstractTask {
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        QFilter qFilter = new QFilter("billstatus", QCP.equals, "C");//
        qFilter.and(new QFilter("yem_issendmessage", QCP.equals, false));
        qFilter.and(new QFilter("yem_billtype.number", QCP.equals, "yem_tracktaskconsole_zj"));
        String selectfield = DynamicObjectUtil.getSelectfields("yem_tracktaskconsole", false);
//        String selectfields = DynamicObjectUtil.getEntrySelectfields(selectfield, "yem_tracktaskconsole", "yem_es_materialinfo", false);
        String selectfields = DynamicObjectUtil.getEntrySelectfields(selectfield, "yem_tracktaskconsole", "yem_es_salesorder_r", false);
        String selectfieldss = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_tracktaskconsole", "yem_es_salesorder_r", "yem_es_salesorder_z", false);
        DynamicObject[] tracktaskconsole = BusinessDataServiceHelper.load("yem_tracktaskconsole", selectfieldss, new QFilter[]{qFilter}, null);
        for (int i = 0; i < tracktaskconsole.length; i++) {
            DynamicObject dynamicObject = tracktaskconsole[i];
            Boolean satisfy = isSatisfy(dynamicObject);
            //满足条件发送消息
            if (satisfy) {
                QFilter qFilter1 = new QFilter("phone", QCP.equals, "18765333065");
                DynamicObject user = BusinessDataServiceHelper.loadSingle("bos_user", "id", qFilter1.toArray());
                long yem_operator = dynamicObject.getLong("yem_operator.id");
                List<Long> list = new ArrayList<>();
                list.add(yem_operator);
                if (user != null) {
                    list.add(user.getLong("id"));
                }
                //客户
                String yem_customer = dynamicObject.getString("yem_customer.name");
                //贸易国别
                String yem_clientcountry = dynamicObject.getString("yem_clientcountry.name");
                //合同号
                String yem_contractnumber = dynamicObject.getString("yem_contractnumber");
                //下单审批的单据编号
                String yem_lotno = dynamicObject.getString("yem_lotno");
                String xdfbillno = yem_contractnumber + "_" + yem_lotno;
                String title = "贸易国别:【" + yem_clientcountry + "】;客户:【" + yem_customer + "】的合同号【" + yem_contractnumber + "】,对应的订单整机生产信息已经到达精试状态，请及时进行后续操作！";
                String msg = "贸易国别为【" + yem_clientcountry + "】的客户【" + yem_customer + "】的合同号【" + yem_contractnumber + " 】," +
                        "其下单审批单号【" + xdfbillno + "】对应的订单整机生产信息已经到达精试状态，详细数据：\n" + Concatenated(dynamicObject);
                long result = YEM.sendMessage(list, "系统发送", MessageInfo.TYPE_MESSAGE, title, msg, "业务消息");
                if (result > 0) {
                    dynamicObject.set("yem_issendmessage", true);
                    SaveServiceHelper.update(new DynamicObject[]{dynamicObject});
                }
            }
        }
    }

    /**
     * 是否满足条件
     *
     * @param dynamicObject 跟单任务控制台对象
     */
    public Boolean isSatisfy(DynamicObject dynamicObject) {
        //备料（生产、采购）信息
        DynamicObjectCollection yemEsSalesorderR = dynamicObject.getDynamicObjectCollection("yem_es_salesorder_r");
        for (int i = 0; i < yemEsSalesorderR.size(); i++) {
            DynamicObject EsSalesorderR = yemEsSalesorderR.get(i);
            BigDecimal yemStockqty = EsSalesorderR.getBigDecimal("yem_stockqty");
            //整机生产信息
            DynamicObjectCollection yemEsSalesorderZ = EsSalesorderR.getDynamicObjectCollection("yem_es_salesorder_z");
            if (yemStockqty.compareTo(BigDecimal.valueOf(yemEsSalesorderZ.size())) == 0) {
                for (int j = 0; j < yemEsSalesorderZ.size(); j++) {
                    DynamicObject EsSalesorderZ = yemEsSalesorderZ.get(j);
                    String yemAccuracytest = EsSalesorderZ.getString("yem_accuracytest");
                    if (yemAccuracytest.equals("B")) {
                        return false;
                    }
                }
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 拼接主要信息
     * 样例为 机型【机型】资源号【资源号】 对应 序号、整机编号（按资源号展示）
     *
     * @return
     */
    public String Concatenated(DynamicObject dynamicObject) {
        StringBuilder stringBuilder = new StringBuilder();
        Map<String, List> map = new HashMap<>();
        //备料（生产、采购）信息
        DynamicObjectCollection yemEsSalesorderR = dynamicObject.getDynamicObjectCollection("yem_es_salesorder_r");
        for (int i = 0; i < yemEsSalesorderR.size(); i++) {
            String row = String.valueOf(i + 1);
            DynamicObject EsSalesorderR = yemEsSalesorderR.get(i);
            //整机生产信息
            DynamicObjectCollection yemEsSalesorderZ = EsSalesorderR.getDynamicObjectCollection("yem_es_salesorder_z");
            for (int j = 0; j < yemEsSalesorderZ.size(); j++) {
                String rows = String.valueOf(j + 1);
                DynamicObject EsSalesorderZ = yemEsSalesorderZ.get(j);
                String yem_milltype = EsSalesorderZ.getString("yem_milltype.number");//机型
                String yem_resourcescode = EsSalesorderZ.getString("yem_resourcescode.number");//资源号
                String yem_vehicleno = EsSalesorderZ.getString("yem_vehicleno");
                String Key = yem_milltype + "_" + yem_resourcescode;
                if (map.containsKey(Key)) {
                    List list = map.get(Key);
                    list.add("生产、采购第【" + row + "】行,整机生产信息第【" + rows + "】行,对应整机编码:【" + yem_vehicleno+"】");//整机编码
                    map.put(Key, list);
                } else {
                    List list = new ArrayList<>();
                    list.add("生产、采购第【" + row + "】行,整机生产信息第【" + rows + "】行,对应整机编码:【" + yem_vehicleno+"】");//整机编码
                    map.put(Key, list);
                }
            }
        }
        //拼接map
        for (String key : map.keySet()) {
            String[] s = key.split("_");
            List list = map.get(key);
            stringBuilder.append("机型【" + s[0] + "】,资源号【" + s[1] + "】,对应\n " + String.join("\n ", list) + "\n");
        }
        return stringBuilder.toString();
    }

    @Override
    public MessageHandler getMessageHandle() {
        return super.getMessageHandle();
    }

}
