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.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.List;
import java.util.Map;

/**
 * @author zhouc
 * @date 2024/4/18 10:41
 * @className ServiceRepairTask
 * @description 服务维修单定时更新整机档案服务维修分录
 */
public class ServiceRepairTask 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_ismachine", QCP.equals, false));
        DynamicObjectCollection servicerepair = QueryServiceHelper.query("yem_servicerepair", "id,billno,yem_factoryno", new QFilter[]{qFilter}, null);
        if (servicerepair.size() > 0) {
            for (int i = 0; i < servicerepair.size(); i++) {
                DynamicObject object = servicerepair.get(i);
                String yem_factoryno = object.getString("yem_factoryno");
                if (yem_factoryno.length() > 0) {
                    //整机档案
                    DynamicObject getdevicefiles = getdevicefiles(yem_factoryno);
                    //服务维修单
                    DynamicObject yem_servicerepair = BusinessDataServiceHelper.loadSingle(object.getString("id"), "yem_servicerepair");
                    if (yem_servicerepair != null && getdevicefiles != null) {
                        //整机档案维修记录
                        DynamicObjectCollection yem_maintenancerecords = getdevicefiles.getDynamicObjectCollection("yem_maintenancerecords");
                        //服务维修
                        DynamicObjectCollection yem_faultypartsreco = yem_servicerepair.getDynamicObjectCollection("yem_faultypartsreco");
                        for (int j = 0; j < yem_faultypartsreco.size(); j++) {
                            DynamicObject dynamicObject = yem_faultypartsreco.get(j);
                            long id = dynamicObject.getLong("id");
                            if (isExistence(yem_maintenancerecords, id)) {
                                DynamicObject maintenancerecords = yem_maintenancerecords.addNew();
                                maintenancerecords.set("yem_maintenancetime", yem_servicerepair.getDate("yem_bizdate"));//维修时间
                                maintenancerecords.set("yem_maintenancepre", yem_servicerepair.getString("yem_operator.number"));//维修人
                                maintenancerecords.set("yem_warrantytype", dynamicObject.getString("yem_warrantytype"));//质保件类型
                                maintenancerecords.set("yem_warrantyname", dynamicObject.getString("yem_warrantyname"));//质保件名称
                                maintenancerecords.set("yem_material", dynamicObject.getDynamicObject("yem_material"));//物料编码
                                maintenancerecords.set("yem_materialname", dynamicObject.getString("yem_materialname"));//物料名称
                                maintenancerecords.set("yem_unit", dynamicObject.getDynamicObject("yem_unit"));//物料名称
                                maintenancerecords.set("yem_qtywx", dynamicObject.getBigDecimal("yem_qty"));//数量
                                maintenancerecords.set("yem_price", dynamicObject.getBigDecimal("yem_price"));//单价（人民币）
                                maintenancerecords.set("yem_amt", dynamicObject.getBigDecimal("yem_amt"));//金额（人民币）
                                maintenancerecords.set("yem_mark", yem_servicerepair.getString("yem_remark"));//备注
                                maintenancerecords.set("yem_servicerepairid", yem_servicerepair.getString("id"));//服务维修单id
                                maintenancerecords.set("yem_servicerepairenryid", dynamicObject.getString("id"));//服务维修单分录id
                                maintenancerecords.set("yem_servicerepairno", yem_servicerepair.getString("billno"));//服务维修单单号
                            }
                        }
                        //保存整机档案
                        OperationResult Operate = OperationServiceHelper.executeOperate("save",
                                getdevicefiles.getDynamicObjectType().getName(), new DynamicObject[]{getdevicefiles}, OperateOption.create());
                        if (Operate.isSuccess()) {
                            yem_servicerepair.set("yem_ismachine", true);
                            yem_servicerepair.set("yem_synzjda", "同步成功");
                            yem_servicerepair.set("yem_synzjda_tag", null);
                            SaveServiceHelper.update(yem_servicerepair);
                        } else {
                            List<IOperateInfo> allErrorOrValidateInfo = Operate.getAllErrorOrValidateInfo();
                            String message = Operate.getMessage();
                            yem_servicerepair.set("yem_synzjda", "同步整机档案失败：" + message + "请点击查看详情！");
                            yem_servicerepair.set("yem_synzjda_tag", allErrorOrValidateInfo);
                            SaveServiceHelper.update(yem_servicerepair);
                        }

                    }
                }
            }
        }

        updateVoidStatus();
    }


    /**
     * 更新作废状态
     */
    private void updateVoidStatus() {
        QFilter qFilter = new QFilter("billstatus", QCP.equals, "C");
        qFilter.and(new QFilter("yem_ismachine", QCP.equals, true));
        DynamicObjectCollection servicerepair_pl = QueryServiceHelper.query("yem_servicerepair", "id,billno,yem_factoryno", new QFilter[]{qFilter}, null);

        for (DynamicObject object : servicerepair_pl) {
            String factoryno = object.getString("yem_factoryno");
            if (YEM.isEmpty(factoryno)) {
                continue;
            }

            //整机档案
            DynamicObject getdevicefiles = getdevicefiles(factoryno);
            //服务维修单
            DynamicObject servicerepair = BusinessDataServiceHelper.loadSingle(object.getString("id"), "yem_servicerepair");

            if (YEM.isNotEmpty(servicerepair) && YEM.isNotEmpty(getdevicefiles)) {
                //整机档案维修记录
                DynamicObjectCollection maintenancerecords = getdevicefiles.getDynamicObjectCollection("yem_maintenancerecords");
                //服务维修
                DynamicObjectCollection faultypartsreco = servicerepair.getDynamicObjectCollection("yem_faultypartsreco");

                for (DynamicObject dynamicObject : faultypartsreco) {
                    long id = dynamicObject.getLong("id");
                    String voidstatus = servicerepair.getString("yem_voidstatus");//作废状态
                    for (DynamicObject maintenancerecord : maintenancerecords) {
                        long yem_servicerepairenryid = maintenancerecord.getLong("yem_servicerepairenryid");
                        if (yem_servicerepairenryid == id) {
                            maintenancerecord.set("yem_voidstatus", voidstatus);
                        }
                    }
                }
            }

            OperationServiceHelper.executeOperate("save",
                    getdevicefiles.getDynamicObjectType().getName(), new DynamicObject[]{getdevicefiles}, OperateOption.create());
        }
    }

    /**
     * 获取整机档案单据对象
     *
     * @param yem_framenumber 整机编码
     * @return
     */
    public DynamicObject getdevicefiles(String yem_framenumber) {
        DynamicObject DynamicObject = null;
        QFilter qFilter = new QFilter("yem_framenumber", QCP.equals, yem_framenumber);
        DynamicObject Object = BusinessDataServiceHelper.loadSingle("yem_em_devicefiles", "id,number", qFilter.toArray());
        if (Object != null) {
            DynamicObject = BusinessDataServiceHelper.loadSingle(Object.getString("id"), "yem_em_devicefiles");
        }
        return DynamicObject;
    }

    public Boolean isExistence(DynamicObjectCollection yem_maintenancerecords, Long fentryid) {
        Boolean flg = true;
        if (yem_maintenancerecords.size() > 0) {
            for (int i = 0; i < yem_maintenancerecords.size(); i++) {
                DynamicObject dynamicObject = yem_maintenancerecords.get(i);
                long yem_servicerepairenryid = dynamicObject.getLong("yem_servicerepairenryid");
                if (yem_servicerepairenryid == fentryid) {
                    return false;
                }
            }
        }
        return flg;
    }
}
