public without sharing class InventoryHeaderHandler extends Oly_TriggerHandler {
    private Map<Id, Inventory_Header__c> newMap;
    private Map<Id, Inventory_Header__c> oldMap;
    private List<Inventory_Header__c> newList;
    private List<Inventory_Header__c> oldList;

    private Set<Id> checkedApprovalIHIdSet = new Set<Id>();

    // 需要追加共享的共享Object
    private static List<SObject> shareList = new List<SObject>();
    // 已经放在追加共享List的Key
    private static Set<String> shareSet = new Set<String>();

    private static List<Inventory_Detail__c> idList = new List<Inventory_Detail__c>();
    private static List<Consum_Inventory_Detail__c> cidList = new List<Consum_Inventory_Detail__c>();

    private static Set<Id> updateAssetIdSet = new Set<Id>();
    private static Map<Id, Asset> updateAssetMap = new Map<Id, Asset>();
    // 20210427 you start
    public static Integer FIELDMAX = 35;
    // 20210427 you end
    public InventoryHeaderHandler() {
        this.newMap = (Map<Id, Inventory_Header__c>) Trigger.newMap;
        this.oldMap = (Map<Id, Inventory_Header__c>) Trigger.oldMap;
        this.newList = (List<Inventory_Header__c>) Trigger.new;
        this.oldList = (List<Inventory_Header__c>) Trigger.old;
    }

    protected override void beforeInsert() {
        genInventoryReportNo(); // 盘点报告书编号生成
        assignApprovalUsers(); // 分配审批用户 -- 经理(备品) & 部长(备品) & 总监(备品)
    }

    protected override void beforeUpdate() {
        idList = new List<Inventory_Detail__c>();
        updateAssetMap = new Map<Id, Asset>();
        assignApprovalUsers();  // 分配审批用户 -- 经理(备品) & 部长(备品) & 总监(备品)
    }

    protected override void afterUpdate() {
        // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc Start
        closeTask();
        // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc End
        approvalIHD();
        setShare();
        if (shareList.size() > 0) {
            insert shareList;
        }
        System.debug(updateAssetMap);
        if (updateAssetMap.isEmpty() == false) {
            update updateAssetMap.values();
        }


        if (idList.size() > 0) {
            //update by rentx 2021-05-13 start 1625
            // LostReportHandler.Loaner_AutoGiveup(null, null, idList);
            LostReportHandler.Loaner_AutoGiveup(null, null, idList, null);
            //update by rentx 2021-05-13 end 1635
        }
        if(cidList.size()>0){
            for (Consum_Inventory_Detail__c id1 : cidList) {
                id1.Auto_Lost_item_giveup__c = true;
            }
            update cidList;
        }
    }

    private void setShare() {
        for (Inventory_Header__c nObj: newList) {
            Inventory_Header__c oObj = oldMap.get(nObj.Id);
            if (nObj.Inventory_Status__c != nObj.Inventory_Status__c
                    && nObj.Inventory_Status__c == '填写完毕') {
                List<String> userList = new List<String>();
                userList.add(nObj.Jingli_Equipment_Id__c + '_Read');
                userList.add(nObj.Buzhang_Equipment_Id__c + '_Read');
                userList.add(nObj.Zongjian_Equipment_Id__c + '_Read');
                // userList.add(nObj.RA_TongkuoZongjian_F__c + '_Read');
                LostReportHandler.setSObjectShare('Inventory_Header__Share', 'Manual', nObj.Id, userList, nObj.OwnerId, shareSet, shareList);
            }
        }
    }

    /**
     * 盘点报告书编号生成规则
     * [OCMA-自动生成年度-自动生成BJ-01(开始盘点日期对应的月份)]
     * 年度 可参考申请No的生成方式
     * BJ 根据备品存放地来生成 (北京 备品中心:BJ  上海 备品中心:SH  广州 备品中心:GZ)
     */
    private void genInventoryReportNo() {
        //20210427 you 1650 start
        SS_Batch_Column_Mapping__c mpdMapping = SS_Batch_Column_Mapping__c.getValues('Inventory_Header_Name');//盘点编码              
        Map<String,String> HeaderMap = new Map<String,String>();
        for (Integer i = 1; i <= FIELDMAX; i++) {
            String lpadI = ('00' + i).right(3);
            String fromColumn = 'From_Column_' + lpadI + '__c';
            String apiStr = String.valueOf(mpdMapping.get(fromColumn));
            if (String.isBlank(apiStr) == false) {
                String ssColumn = 'SS_Column_' + lpadI + '__c';
                String ssApiStr = String.valueOf(mpdMapping.get(ssColumn));
                HeaderMap.put(apiStr,ssApiStr);  
            }

        }
        //20210427 you 1650 end
        String reportNo = '', location = '', month = '';
        for (Inventory_Header__c nObj : this.newList) {
            // 20210223 you WLIG-BV8CHF start
            // reportNo = 'OCMA-' + nObj.Report_No_Year__c + '-';
            reportNo = 'OCMA-' + nObj.Report_No_Year_New__c + '-';
            // 20210223 you WLIG-BV8CHF end
            //20210427 you 1650 start
            if(HeaderMap.containsKey(nObj.Internal_asset_location__c)){
                
                if (nObj.Internal_asset_location__c == '北京 备品中心') {
                    reportNo += 'BJ-';
                } else if (nObj.Internal_asset_location__c == '上海 备品中心') {
                    if(String.isBlank(nObj.Fixture_Header__c)){
                        reportNo += 'SH-';
                    }
                    // Fixture_Header__c有值的是耗材的盘点表头
                    else{
                        reportNo += 'ET/DISP-';
                    }

                } else if (nObj.Internal_asset_location__c == '广州 备品中心') {
                    reportNo += 'GZ-';
                }else{
                    reportNo += 'BSC-'+HeaderMap.get(nObj.Internal_asset_location__c)+'-';
                }
            }    
            /**
            if (nObj.Internal_asset_location__c == '北京 备品中心') {
                reportNo += 'BJ-';
            } else if (nObj.Internal_asset_location__c == '上海 备品中心') {
                if(String.isBlank(nObj.Fixture_Header__c)){
                    reportNo += 'SH-';
                }
                // Fixture_Header__c有值的是耗材的盘点表头
                else{
                    reportNo += 'ET/DISP-';
                }

            } else if (nObj.Internal_asset_location__c == '广州 备品中心') {
                reportNo += 'GZ-';
            } else if (nObj.Internal_asset_location__c == '青岛') {//20210423 you 1650
                reportNo += 'QD-';
            }
            **/
            //20210427 you 1650 end
            month  = String.valueOf(nObj.Inventory_Start_Date__c.month());
            if(String.isNotBlank(month) && month.length() == 1){
                month = '0' + month;
            }
            reportNo += month;
            nObj.Name = reportNo;
        }
    }

    /**
     * 分配审批用户 -- 经理(备品) & 部长(备品) & 总监(备品)
     */
    private void assignApprovalUsers() {
        for (Inventory_Header__c nObj : this.newList) {
            Inventory_Header__c oObj;
            if (Trigger.isUpdate) {
                oObj = this.oldMap.get(nObj.Id);
            }
            if (Trigger.isInsert || nObj.InventorySubmit_PIC__c != oObj.InventorySubmit_PIC__c
                || (oObj.Inventory_Status__c != '填写完毕' && nObj.Inventory_Status__c == '填写完毕')) {
                bp3_Setting__c conf = bp3_Setting__c.getOrgDefaults();
                if (String.isNotBlank(nObj.Jingli_Equipment_Id__c)) {
                    nObj.Jingli_Equipment__c = nObj.Jingli_Equipment_Id__c;
                }
                if (String.isNotBlank(nObj.Buzhang_Equipment_Id__c)) {
                    nObj.Buzhang_Equipment__c = nObj.Buzhang_Equipment_Id__c;
                }
                /**
                20210701 1650 you 华东得办事处是副总监
                if (String.isNotBlank(nObj.Zongjian_Equipment_Id__c)) {
                    nObj.Zongjian_Equipment__c = nObj.Zongjian_Equipment_Id__c;
                }**/
                if(nObj.InventoryBenbu__c  == '医疗华东营业本部' &&nObj.Internal_asset_location__c!= '广州 备品中心' && nObj.Internal_asset_location__c!= '北京 备品中心' && nObj.Internal_asset_location__c!= '上海 备品中心') {
                    nObj.Zongjian_Equipment__c = conf.FuZongJian__c;
                }
                else {
                    if (String.isNotBlank(nObj.Zongjian_Equipment_Id__c)) {
                       nObj.Zongjian_Equipment__c = nObj.Zongjian_Equipment_Id__c;
                     }
                } 
            }
        }
    }

    private void approvalIHD() {
        Set<Id> checkedApprovalIDSet = new Set<Id>();
        for (Inventory_Header__c nObj : newList) {
            Inventory_Header__c oObj = oldMap.get(nObj.Id);
            System.debug(oObj.Inventory_Status__c);
            System.debug(nObj.Inventory_Status__c);
            if (oObj.Inventory_Status__c != '已批准'
                    && nObj.Inventory_Status__c == '已批准'
                    && !checkedApprovalIHIdSet.contains(nObj.Id)) {
                checkedApprovalIDSet.add(nObj.Id);
                checkedApprovalIHIdSet.add(nObj.Id);
                // TODO Header 1件ずつ呼び出すしかないですか？
                if(String.isBlank(nObj.Fixture_Header__c)){                    
                    InventoryReportDetailArchiveBatch mBatch = new InventoryReportDetailArchiveBatch(nObj);
                    Database.executeBatch(mBatch);
                    // 借出明细
                    Integer fileNo = 0;
                    Integer totalCount = 0;
                    Integer totalCountDone = 0;
                    InventoryReportDtlArcRaesdBatch raesdBatch = new InventoryReportDtlArcRaesdBatch(nObj, fileNo, totalCount, totalCountDone);
                    Database.executeBatch(raesdBatch);
                }
                // 耗材盘点表头
                else {
                    ConsumInventoryReportDetailArchiveBatch mBatch = new ConsumInventoryReportDetailArchiveBatch(nObj);
                    Database.executeBatch(mBatch);
                    // 借出明细
                    Integer fileNo = 0;
                    Integer totalCount = 0;
                    Integer totalCountDone = 0;
                    ConsumInventoryReportDtlArcRaesdBatch raesdBatch = new ConsumInventoryReportDtlArcRaesdBatch(nObj, fileNo, totalCount, totalCountDone);
                    Database.executeBatch(raesdBatch);
                }
            }
        }
        List<Inventory_Detail__c> idList1 = [SELECT Id,
                                                    Appended_Inventory_Frozen_Quantity_F__c,
                                                    Inventory_Deviation__c,
                                                    Asset__c,
                                                    Internal_Asset_Flg__c,
                                                    Asset__r.Inventory_Frozen_Quantity__c,
                                                    Asset__r.Inventory_Profit_Quantity__c
                                               FROM Inventory_Detail__c
                                              WHERE Inventory_Header__c = :checkedApprovalIDSet
                                                AND Auto_Lost_item_giveup__c = false
                                                AND Inventory_Deviation__c != 0
                                                AND Inventory_Time__c != null];
        List<Consum_Inventory_Detail__c> idList2 = [SELECT Id,
                                                    Appended_Inventory_Frozen_Quantity_F__c,
                                                    Inventory_Deviation__c,
                                                    Asset__c,
                                                    Internal_Asset_Flg__c,
                                                    Asset__r.Inventory_Frozen_Quantity__c,
                                                    Asset__r.Inventory_Profit_Quantity__c
                                               FROM Consum_Inventory_Detail__c
                                              WHERE Inventory_Header__c = :checkedApprovalIDSet
                                                AND Inventory_Deviation__c != 0
                                                AND Inventory_Time__c != null];
        for (Inventory_Detail__c id1 : idList1) {
            if (!updateAssetIdSet.contains(id1.Asset__c)) {
                updateAssetIdSet.add(id1.Asset__c);
                updateAssetMap.put(id1.Asset__c, new Asset(Id = id1.Asset__c,
                                                            Appended_Inventory_Frozen_Quantity__c = id1.Asset__r.Inventory_Frozen_Quantity__c,
                                                            Inventory_Frozen_Quantity__c = 0,
                                                            Appended_Inventory_Profit_Quantity__c = id1.Asset__r.Inventory_Profit_Quantity__c,
                                                            Inventory_Profit_Quantity__c = 0
                                                            ));
            }
            if (id1.Internal_Asset_Flg__c == false && id1.Inventory_Deviation__c < 0) {
                idList.add(id1);
            }
        }
        for (Consum_Inventory_Detail__c id1 : idList2) {
            if (!updateAssetIdSet.contains(id1.Asset__c)) {
                updateAssetIdSet.add(id1.Asset__c);
                updateAssetMap.put(id1.Asset__c, new Asset(Id = id1.Asset__c,
                                                            Appended_Inventory_Frozen_Quantity__c = id1.Asset__r.Inventory_Frozen_Quantity__c,
                                                            Inventory_Frozen_Quantity__c = 0,
                                                            Appended_Inventory_Profit_Quantity__c = id1.Asset__r.Inventory_Profit_Quantity__c,
                                                            Inventory_Profit_Quantity__c = 0
                                                            ));
            }
            if (id1.Internal_Asset_Flg__c == false && id1.Inventory_Deviation__c < 0) {
                cidList.add(id1);
            }
        }
    }

    // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc Start
    private void closeTask() {
        List<task__c> updTaskList = new List<task__c>();
        Date today = Date.today();
        for (Inventory_Header__c nObj : newList) {
            Inventory_Header__c oObj = this.oldMap.get(nObj.Id);

            if (oObj.Inventory_Status__c != '填写完毕' && nObj.Inventory_Status__c == '填写完毕') {
                if (nObj.Internal_asset_location__c.contains('备品中心')) {
                    String roleName = null;
                    if (nObj.Internal_asset_location__c == '北京 备品中心') {
                        roleName = '备品中心北方管理成员';
                    } else if (nObj.Internal_asset_location__c == '上海 备品中心') {
                        roleName = '备品中心华东管理成员';
                    } else if (nObj.Internal_asset_location__c == '广州 备品中心') {
                        roleName = '备品中心南方管理成员';
                    }

                    List<task__c> taskList = [SELECT Id, taskStatus__c FROM task__c WHERE (taskStatus__c = '01 分配' OR taskStatus__c = '02 接受' OR taskStatus__c = '05 延期') AND RecordType.Name = '盘点检查计划' AND assignee__r.Profile.Name = '2B2_备品中心检测&仓库管理(照片)' AND assignee__r.RoleName_wave__c =: roleName];
                    for (task__c t : taskList) {
                        t.taskStatus__c = '03 完成';
                        t.Finished_Date__c = today;
                        updTaskList.add(t);
                    }
                } else {
                    List<task__c> taskList = [SELECT Id, taskStatus__c FROM task__c WHERE (taskStatus__c = '01 分配' OR taskStatus__c = '02 接受' OR taskStatus__c = '05 延期') AND RecordType.Name = '盘点检查计划' AND assignee__r.Work_Location__c =: nObj.Internal_asset_location__c];
                    for (task__c t : taskList) {
                        t.taskStatus__c = '03 完成';
                        t.Finished_Date__c = today;
                        updTaskList.add(t);
                    }
                }
            }
        }

        if (!updTaskList.isEmpty()) {
            FixtureUtil.withoutUpdate(updTaskList);
        }
    }
    // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc End
}