package com.yem.em.bd.etcmanualim.op;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.yem.em.utils.EmptyUtils;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.url.UrlService;

/**
 * @author 夜子
 * @ClassName DetailImportOp
 * @description: 零件导入操作
 * @date 2023年07月12日
 * @version: 1.0
 */
public class DetailImportOp  extends AbstractOperationServicePlugIn {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
//        List<String> keys = e.getFieldKeys();
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        super.beginOperationTransaction(e);
        DynamicObject[] bills = e.getDataEntities();
        for (DynamicObject dynamicObject : bills) {
            DynamicObject bill = dynamicObject;
            bill = BusinessDataServiceHelper.loadSingle(bill.getPkValue(), bill.getDynamicObjectType().getName());
            String number  = bill.getString("number");
            long etcmanualId = GetEquipmentlistPkValue(number);
            if (etcmanualId !=0L) {
                CreatePart(etcmanualId, bill);
            } else {
                throw new KDBizException(
                        ResManager.loadKDString("导入异常,上级资源目录不存在！", "DetailImportOp_0", "yem_equipment"));
            }
        }
    }


    private long GetMaterial(String number) {
        long materialId = 0;
        DynamicObject orgObj = BusinessDataServiceHelper.loadSingle("100000", "bos_adminorg");
        QFilter qFilter = new QFilter("number", QCP.equals, number);
        QFilter qFilter1 = new QFilter("createorg", QCP.equals, orgObj.getPkValue());
        DynamicObject materialObj = BusinessDataServiceHelper.loadSingle("bd_material", "id,number,name",
                new QFilter[] { qFilter, qFilter1 });
        if (materialObj != null) {
            materialId = Long.parseLong(materialObj.getPkValue().toString());
        }
        return materialId;
    }

    /**
     * @MethodName 获取电子目录明细ID
     * @Author  SC
     * @Description
     * @Date 17:36 2023/8/28
     * @Param 编码
     * @return long
     **/
    private long GetEquipmentlistPkValue(String number) {
        long etcmanualId = 0;
        QFilter qFilter = new QFilter("number", QCP.equals, number);
        DynamicObject etcmanualObj = BusinessDataServiceHelper.loadSingle("yem_em_equipmentlist", "id,number,name",
                new QFilter[] { qFilter });
        if (etcmanualObj != null) {
            etcmanualId = Long.parseLong(etcmanualObj.getPkValue().toString());
        }
        return etcmanualId;
    }

    /**
     * @MethodName 获取设备部件ID
     * @Author  SC
     * @Description
     * @Date 18:18 2023/8/28
     * @Param [number, etcmanualId] [编码，电子目录ID,组织]
     * @return long
     **/
    private long GetComponentPkValue(String number, Long etcmanualId,DynamicObject adminorg) {
        long ComponentId = 0;
        QFilter qFilter = new QFilter("yem_cnumber", QCP.equals, number);
        QFilter qFilter1 = new QFilter("yem_equipmentlistid", QCP.equals, etcmanualId);
        QFilter qFilter2 = new QFilter("createorg.id", QCP.equals, adminorg.getPkValue());
        DynamicObject partGroupObj = BusinessDataServiceHelper.loadSingle("yem_em_component",
                "id,number,name,createorg.id,yem_cnumber,yem_equipmentlistid", new QFilter[] { qFilter, qFilter1, qFilter2 });
        if (partGroupObj != null) {
            ComponentId = Long.parseLong(partGroupObj.getPkValue().toString());
        }
        return ComponentId;
    }

    /**
     * @MethodName 获取设备零件ID
     * @Author  SC
     * @Description
     * @Date 18:18 2023/8/28
     * @Param [number, etcmanualId] [编码，电子目录ID,部件,组织]
     * @return long
     **/
    private long GetPartPkValue(String number, Long etcmanualId, DynamicObject Component,DynamicObject adminorg) {
        long partId = 0;
        QFilter qFilter = new QFilter("yem_pnumber", QCP.equals, number);
        QFilter qFilter1 = new QFilter("yem_equipmentlistid", QCP.equals, etcmanualId);
        QFilter qFilter2 = new QFilter("group.id", QCP.equals, Component.getPkValue());
        QFilter qFilter3 = new QFilter("createorg.id", QCP.equals, adminorg.getPkValue());
        DynamicObject partObj = BusinessDataServiceHelper.loadSingle("yem_em_part",
                "id,number,name,yem_equipmentlistid,yem_pnumber", new QFilter[] { qFilter, qFilter1, qFilter2, qFilter3 });
        if (partObj != null) {
            partId = Long.parseLong(partObj.getPkValue().toString());
        }
        return partId;
    }

    private void CreatePart(long etcmanualId, DynamicObject bill) {
        DynamicObject equipmentlist = BusinessDataServiceHelper.loadSingle(etcmanualId, "yem_em_equipmentlist");
        //            DynamicObject orgObj =  BusinessDataServiceHelper.loadSingle("100000", "bos_adminorg");
        DynamicObject adminorg = bill.getDynamicObject("createorg");
        DynamicObjectCollection entryentityList = bill.getDynamicObjectCollection("yem_partentity");
        int index = 1;
        for (DynamicObject dy : entryentityList) {
            String yncstatusd = dy.getString("yem_syncstatusd");
            if ("S".equals(yncstatusd)) { //已同步
                continue;
            }
            String detailno = dy.getString("yem_detailno");
            if (EmptyUtils.isEmpty(detailno)) {
                continue;
            }
            String detailname = dy.getString("yem_detailname");
            String detailenname = dy.getString("yem_detailenname");
            String partsno = dy.getString("yem_partsno_p");

            long ComponentId = GetComponentPkValue(partsno, etcmanualId,adminorg );
            if (ComponentId == 0) {
                throw new KDBizException(ResManager.loadKDString("未找到第[", "DetailImportOp_4", "bfcl_equipment") + index
                        + ResManager.loadKDString("]行的部件【", "DetailImportOp_5", "bfcl_equipment") + partsno
                        + ResManager.loadKDString("】，请先尝试同步部件后再重试！", "DetailImportOp_6", "bfcl_equipment"));
            }
            DynamicObject component = BusinessDataServiceHelper.loadSingle(ComponentId, "yem_em_component");
            long PartId = GetPartPkValue(detailno, etcmanualId , component,adminorg);
            DynamicObject part = BusinessDataServiceHelper.newDynamicObject("yem_em_part");
            DynamicObject userObj = BusinessDataServiceHelper.loadSingle(RequestContext.get().getCurrUserId(), "bos_user");
            if (EmptyUtils.isNotEmpty(PartId)) {
                part = BusinessDataServiceHelper.loadSingle(PartId, "yem_em_part");
            }

            part.set("createorg", adminorg);
            part.set("org", adminorg);
            part.set("useorg", adminorg);
            part.set("creator", userObj);
            part.set("createtime", new Date());
            part.set("modifier", userObj);
            part.set("modifytime", new Date());
            part.set("status", "C");
            part.set("enable", "1");
            part.set("yem_isimport", true);
            part.set("ctrlstrategy", "5");
            part.set("yem_equipmentlistid", etcmanualId);
            DynamicObject yem_basemodelib = equipmentlist.getDynamicObject("yem_basemodelib");
            if (yem_basemodelib != null) {
                component.set("yem_basemodelib", yem_basemodelib);
            }
            part.set("yem_enname", detailenname);
            part.set("yem_pnumber", detailno);
            LocaleString str = new LocaleString();
            str.setLocaleValue_zh_CN(detailname);
            if (EmptyUtils.isNotEmpty(detailenname)) {
                str.setLocaleValue_en(detailenname);
            }
            part.set("name", str);
            part.set("yem_materielmodel", dy.getString("yem_detailmodel"));
            DynamicObject unitsub = dy.getDynamicObject("yem_detailunit");
            if (unitsub != null) {
                part.set("yem_unit", unitsub);
            }
            BigDecimal qtysub = dy.getBigDecimal("yem_detailqty");
            part.set("yem_qty", qtysub);
            part.set("yem_atlasno", dy.getString("yem_detailseq"));
            part.set("yem_remark", dy.getString("yem_remarksd"));
            part.set("group", component);

            //系统编码处理
            String newNumber = CodeRuleServiceHelper.getNumber("yem_em_part", part,
                    adminorg.getPkValue().toString());
            part.set("number", newNumber);

            //图片处理 待处理
            List<String> pathlist =  GetAttachmentPath(detailno);
            if(pathlist.size()>0){
                part.set("yem_picture", pathlist.get(0));
            }

            OperationResult part_save = OperationServiceHelper.executeOperate("save", "yem_em_part",
                    new DynamicObject[] { part }, null);
            if (!part_save.isSuccess()) {
                for (IOperateInfo errInfo1 : part_save.getAllErrorOrValidateInfo()) {
                    String detailMessage1 = errInfo1.getMessage();
                    throw new KDBizException(ResManager.loadKDString("生成第[", "DetailImportOp_2", "yem_equipment")
                            + index
                            + ResManager.loadKDString("]行的设备电子目录明细(零件)时保存失败：", "DetailImportOp_8", "yem_equipment")
                            + detailMessage1);
                }
            }
            index++;
            dy.set("yem_syncstatusd", "S");
        }
        bill.set("yem_importstatus", "S");
        SaveServiceHelper.save(new DynamicObject[] { bill });
    }

    private List<String> GetAttachmentPath(String number) {
        List<String> pathlist = new ArrayList<>();
        List<String> fname = new ArrayList<>();
        fname.add(number+".jpg");
        fname.add(number+".gif");
        fname.add(number+".png");
        DynamicObject[] atts = BusinessDataServiceHelper.load("bos_attachment", "id,ffileid,fattachmentname",
                new QFilter[] { new QFilter("fbilltype", QCP.equals, "yem_em_materialpicupload"),
                        new QFilter("fattachmentname", QCP.in, fname) });
        for (DynamicObject att : atts) {
            String  path = UrlService.getAttachmentFullUrl(att.getString("ffileid"));
            pathlist.add(path);
        }

        return pathlist;
    }

}
