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

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.entity.OrmLocaleValue;
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;

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

/**
 * @author 夜子
 * {@code @ClassName} PartsImportOp
 * {@code @description:} 部件导入操作
 * {@code @date} 2023年07月12日
 * {@code @version:} 1.0
 */
public class PartsImportOp 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 bill : bills) {
            bill = BusinessDataServiceHelper.loadSingle(bill.getPkValue(), bill.getDynamicObjectType().getName());
            OrmLocaleValue strname = (OrmLocaleValue) bill.getLocaleString("name");
            CreateEquipmentlist( bill.getString("number"), strname.getLocaleValue_zh_CN(),
                    strname.getLocaleValue_en(), bill);
        }

    }

    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,yem_etcnumber", new QFilter[] { qFilter});
        if (etcmanualObj != null) {
            etcmanualId = Long.parseLong(etcmanualObj.getPkValue().toString());
        }
        return etcmanualId;
    }

    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;
    }

    /**
     * @MethodName 创建电子目录明细（车型）
     * @Author  SC
     * @Description
     * @Date 17:38 2023/8/28
     * @Param [number, name, enname, bill] [车型编号, 英文名称, 中文吗名称, 导入表单实体]
     **/

    private void CreateEquipmentlist(String number, String name, String enname,
                                 DynamicObject bill) {
        long etcmanualId = GetEquipmentlistPkValue(number);
        DynamicObject etcmanual = BusinessDataServiceHelper.newDynamicObject("yem_em_equipmentlist");
        if (EmptyUtils.isNotEmpty(etcmanualId)) {
            etcmanual = BusinessDataServiceHelper.loadSingle(etcmanualId, "yem_em_equipmentlist");
        }

//            DynamicObject orgObj =  BusinessDataServiceHelper.loadSingle("100000", "bos_adminorg");
        DynamicObject adminorg = bill.getDynamicObject("createorg");
        DynamicObject userObj = BusinessDataServiceHelper.loadSingle(RequestContext.get().getCurrUserId(), "bos_user");

        etcmanual.set("createorg", adminorg);
        etcmanual.set("useorg", adminorg);
        etcmanual.set("org", adminorg);
        etcmanual.set("number", number);
        LocaleString str = new LocaleString();
        str.setLocaleValue_zh_CN(name);
        if (EmptyUtils.isNotEmpty(enname)) {
            str.setLocaleValue_en(enname);
        }
        etcmanual.set("name", str);
        etcmanual.set("creator", userObj);
        etcmanual.set("createtime", new Date());
        etcmanual.set("status", "C");
        etcmanual.set("enable", "1");
        etcmanual.set("ctrlstrategy", "5");
        DynamicObject yem_basemodelib = bill.getDynamicObject("yem_basemodelib");
        if (yem_basemodelib != null) {
            etcmanual.set("yem_basemodelib", yem_basemodelib);
        }
        DynamicObject equtype = bill.getDynamicObject("yem_equtype");
        if (equtype != null) {
            etcmanual.set("yem_eqctype", equtype);
        }
        DynamicObject yem_brand = bill.getDynamicObject("yem_brand");
        if (yem_brand != null) {
            etcmanual.set("yem_brand", yem_brand);
        }
        DynamicObject yem_group = bill.getDynamicObject("yem_group");
        if (yem_group != null) {
            yem_group = BusinessDataServiceHelper.loadSingle(yem_group.getPkValue(), "yem_em_comlefttree");
            etcmanual.set("yem_brandmodel", yem_group);
        }

        //图片
        List<String> pathlist =  GetAttachmentPath(number);
        if(pathlist.size()>0){
            etcmanual.set("yem_picture", pathlist.get(0));
        }


        OperationResult etcmanual_save = OperationServiceHelper.executeOperate("save", "yem_em_equipmentlist",
                new DynamicObject[] { etcmanual }, null);
        if (etcmanual_save.isSuccess()) {
            long new_etcmanualId = Long.parseLong(etcmanual_save.getSuccessPkIds().get(0).toString());
            CreateComponentALL( new_etcmanualId, number, name, enname, bill);
        } else {
            StringBuilder detailMessage = new StringBuilder(etcmanual_save.getMessage());
            for (IOperateInfo errInfo1 : etcmanual_save.getAllErrorOrValidateInfo()) {
                detailMessage.append(errInfo1.getMessage());
            }
            throw new KDBizException(ResManager.loadKDString("生成设备电子目录失败：", "PartsImportOp_8", "ensign_equipment")
                    + detailMessage);
        }

    }

    /**
     * @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 ecatalogGroupObj = BusinessDataServiceHelper.loadSingle("yem_em_component",
                "id,number,name,createorg.id,yem_cnumber,yem_equipmentlistid", new QFilter[] { qFilter, qFilter1, qFilter2 });
        if (ecatalogGroupObj != null) {
            ComponentId = Long.parseLong(ecatalogGroupObj.getPkValue().toString());
        }
        return ComponentId;
    }

    /**
     * @MethodName 生成所有的部件
     * @Author  SC
     * @Description
     * @Date 14:58 2023/8/29
     * @Param [etcmanualId, number, name, enname, bill] [电子目录ID, 编码, 名称, 英文名称, 导入单实体]
     **/
    private void CreateComponentALL( long etcmanualId, String number, String name, String enname,
                                          DynamicObject bill) {
//        DynamicObject adminorg = BusinessDataServiceHelper.loadSingle("100000", "bos_adminorg");
        DynamicObject adminorg = bill.getDynamicObject("createorg");
        //生成电子目录部件
        long rootGroupId =  CreateComponent(0L,adminorg,etcmanualId,number,name,enname,0);
        if(rootGroupId>0L){
            DynamicObjectCollection entryentityList = bill.getDynamicObjectCollection("yem_componentsentity");
            int index = 1;
            for (DynamicObject dy : entryentityList) {
                String syncstatus = dy.getString("yem_syncstatus");
                if ("S".equals(syncstatus)) { //已同步
                    continue;
                }
                String partsno = dy.getString("yem_partsno");
                String partsname = dy.getString("yem_partsname");
                String partsenname = dy.getString("yem_partsenname");
                if (EmptyUtils.isEmpty(partsno)) {
                    continue;
                }
                String parentpartsno = dy.getString("yem_parentno");
                String parentpartsname = dy.getString("yem_parentname");
                String parentpartsename = dy.getString("yem_parentename");
                if (EmptyUtils.isNotEmpty(partsno) && EmptyUtils.isEmpty(parentpartsno)) {
//                  long new_ecatalogGroupId = GetComponentPkValue(partsno, etcmanualId ,adminorg);、
                    CreateComponent(rootGroupId,adminorg,etcmanualId,partsno,partsname,partsenname,index);
                    index++;
                } else if (EmptyUtils.isNotEmpty(partsno) && EmptyUtils.isNotEmpty(parentpartsno)) {
                    long parent_ecatalogGroupId = GetComponentPkValue(parentpartsno, etcmanualId ,adminorg);
                    if (EmptyUtils.isEmpty(parent_ecatalogGroupId)) {
                        parent_ecatalogGroupId = CreateComponent(rootGroupId,adminorg,etcmanualId,parentpartsno,parentpartsname,parentpartsename,index);
                        if (parent_ecatalogGroupId > 0L) {
//                            long new_ecatalogGroupId = GetComponentPkValue(partsno, etcmanualId ,adminorg);
                            CreateComponent(parent_ecatalogGroupId,adminorg,etcmanualId,partsno,partsname,partsenname,index);
                        }
                    } else {
//                        long new_ecatalogGroupId = GetComponentPkValue(partsno, etcmanualId ,adminorg);
                        CreateComponent(parent_ecatalogGroupId,adminorg,etcmanualId,partsno,partsname,partsenname,index);
                    }
                    index++;
                }
                dy.set("yem_syncstatus", "S");
            }
        }
        bill.set("yem_importstatus", "F");
        SaveServiceHelper.save(new DynamicObject[] { bill });
    }

    private long CreateComponent(long rootGroupId,DynamicObject adminorg, long etcmanualId, String number, String name,
                                         String enname, int index) {
        DynamicObject equipmentlist = BusinessDataServiceHelper.loadSingle(etcmanualId, "yem_em_equipmentlist");
        DynamicObject userObj = BusinessDataServiceHelper.loadSingle(RequestContext.get().getCurrUserId(), "bos_user");
        DynamicObject component = BusinessDataServiceHelper.newDynamicObject("yem_em_component");
        long ecatalogGroupId = GetComponentPkValue(number, etcmanualId ,adminorg);
        if (EmptyUtils.isNotEmpty(ecatalogGroupId)) {
            component = BusinessDataServiceHelper.loadSingle(ecatalogGroupId, "yem_em_component");

        }else{
            component.set("ctrlstrategy", "5");
            component.set("isleaf", "1");
        }

        component.set("createorg", adminorg);
        component.set("org", adminorg);
        component.set("useorg", adminorg);
        component.set("creator", userObj);
        component.set("createtime", new Date());
        component.set("modifier", userObj);
        component.set("modifytime", new Date());
        component.set("status", "C");
        component.set("enable", "1");
        component.set("yem_isimport", true);
        component.set("yem_equipmentlistid", etcmanualId);
        DynamicObject yem_basemodelib = equipmentlist.getDynamicObject("yem_basemodelib");
        if (yem_basemodelib != null) {
            component.set("yem_basemodelib", yem_basemodelib);
        }

        component.set("yem_cnumber", number);
        LocaleString str = new LocaleString();
        str.setLocaleValue_zh_CN(name);
        if (EmptyUtils.isNotEmpty(enname)) {
            str.setLocaleValue_en(enname);
        }
        component.set("name", str);
        component.set("yem_enname", enname);

        //是否电子目录
        if(equipmentlist.getString("number").equals(number)){
            component.set("yem_isepc", true);
        }else{
            component.set("yem_isepc", false);
        }

        //上级及层级处理
        component.set("parent", null);
        component.set("level", 1);
        DynamicObject parent_component = null;
        if (rootGroupId !=0L) {
            QFilter qFilter3 = new QFilter("id", QCP.equals, rootGroupId);
            parent_component = BusinessDataServiceHelper.loadSingle("yem_em_component",
                    "id,number,name", new QFilter[] { qFilter3 });
            if(parent_component!=null){
                parent_component =  BusinessDataServiceHelper.loadSingle(parent_component.getPkValue(), "yem_em_component");
                component.set("parent", parent_component);
                int level = parent_component.getInt("level");
                component.set("level", level + 1);
            }
        }

        //系统编码
        String newNumber = CodeRuleServiceHelper.getNumber("yem_em_component", component,
                adminorg.getPkValue().toString());
        component.set("number", newNumber);

        //图片处理
        List<String> pathlist =  GetAttachmentPath(number);
        if(pathlist.size()>0){
            component.set("yem_picture", pathlist.get(0));
            StringBuilder urls = new StringBuilder();
            for(String path :pathlist){
                String url = path + ";";
                urls.append(url);
            }
            component.set("yem_imageurl", urls.toString());
        }

        OperationResult ecataloggroup_save = OperationServiceHelper.executeOperate("save", "yem_em_component",
                new DynamicObject[] { component }, null);
        if (ecataloggroup_save.isSuccess()) {

            if(parent_component!=null){
                parent_component =  BusinessDataServiceHelper.loadSingle(parent_component.getPkValue(), "yem_em_component");
                parent_component.set("isleaf", false);
                SaveServiceHelper.save(new DynamicObject[] { parent_component });
            }

            return Long.parseLong(ecataloggroup_save.getSuccessPkIds().get(0).toString());
        } else {
            StringBuilder detailMessage = new StringBuilder(ecataloggroup_save.getMessage());
            for (IOperateInfo errInfo : ecataloggroup_save.getAllErrorOrValidateInfo()) {
                detailMessage.append(errInfo.getMessage());
            }
            if(index==0){
                throw new KDBizException(ResManager.loadKDString("生成设备电子目录类别(车型部件)时保存失败：", "PartsImportOp_10", "yem_equipment")
                        + detailMessage);
            }else{
                throw new KDBizException(ResManager.loadKDString(
                        ResManager.loadKDString("生成第【", "PartsImportOp_6", "yem_equipment_equipment"),
                        "CompanyImportOp_1", "yem_equipment_equipment") + index
                        + ResManager.loadKDString("]行的设备电子目录类别(部件)时保存失败：", "PartsImportOp_11", "yem_equipment")
                        + detailMessage);
            }
        }
    }

}
