public with sharing class LexOverdueStockController {
    /*****************検索用******************/
    public static String barcode { get; set; }

    // 过期和销存,画面显示用
    public static List<orderBean> codPageRecords { get; set; }

    // 过期和销存,画面显示用
    public static List<orderBean> overduePageRecords { get; set; }

    // 登录者工作地
    private static String userWorkLocation;
    //经销商用户产品分类（ET、ENG）
    private static String agencyProType;
    private static String sqlagencyProType;
    // 经销商信息
    private static Account accountInfo;

    //判断操作人员是否销存
    public static Boolean iSinventory = false;

    public static List<Consumable_order_details2__c> overdueList = new List<Consumable_order_details2__c>();

    public static Integer pageRecordsSize {
        get {
            return codPageRecords == null ? 0 : codPageRecords.size();
        }
    }

    public LexOverdueStockController() {
    }

    // 画面初始化
    @AuraEnabled
    public static ResponseBodyLWC init() {
        ResponseBodyLWC res = new ResponseBodyLWC();
        Map<String, object> data = new Map<String, object>();
        res.entity = data;

        codPageRecords = new List<orderBean>();
        overduePageRecords = new List<orderBean>();
        // 获取用户和经销商信息
        user Useracc = [SELECT Accountid, Work_Location__c, UserPro_Type__c FROM user WHERE id = :UserInfo.getUserId()];
        userWorkLocation = Useracc.Work_Location__c;
        agencyProType = Useracc.UserPro_Type__c;
        if (String.isBlank(Useracc.UserPro_Type__c)) {
            agencyProType = 'ET';
        }
        sqlagencyProType = '%' + agencyProType + '%';
        accountInfo = [SELECT id, Name, Dealer_discount__c FROM account WHERE id = :Useracc.accountid];
        // 过期库存汇总信息
        List<AggregateResult> orderDetZaiku = [
            SELECT count(Id) countsum, Consumable_Product__c prodid, Consumable_Product__r.Name_Text__c prodname, Box_Piece__c boxPiece
            FROM Consumable_order_details2__c
            WHERE
                Dealer_Arrive__c = TRUE
                AND Dealer_Shipment__c = FALSE
                AND Dealer_Saled__c = FALSE
                AND Lose_Flag__c = FALSE
                AND Isoverdue__c = 0
                AND Dealer_Returned__c = FALSE
                AND Cancellation_Flag__c = FALSE
                AND Bar_Code__c != NULL
                AND Product_Type__c LIKE :sqlagencyProType
                AND Dealer_Info_text__c = :accountInfo.Name
                AND Arrive_Owner_Work_Location__c = :userWorkLocation
            GROUP BY Consumable_Product__c, Box_Piece__c, Consumable_Product__r.Name_Text__c
        ];

        for (AggregateResult overdue : orderDetZaiku) {
            codPageRecords.add(new orderBean(overdue));
        }

        system.debug('codPageRecords====>' + codPageRecords);
        data.put('codPageRecords', JSON.serialize(codPageRecords));
        data.put('userWorkLocation', userWorkLocation);
        data.put('accountName', accountInfo.Name);
        data.put('agencyProType', agencyProType);
        data.put('orderDetZaiku', JSON.serialize(orderDetZaiku));
        res.status = 'Success';
        res.code = 200;
        System.debug('res = ' + res);
        return res;
    }

    // BarCode录入
    @AuraEnabled
    public static ResponseBodyLWC searchorderBean(
        String agencyProTypeLWC,
        String userWorkLocationLWC,
        String accountNameLWC,
        String barcodeLWC,
        String codPageRecordsLWC
    ) {
        ResponseBodyLWC res = new ResponseBodyLWC();
        Map<String, object> data = new Map<String, object>();
        res.entity = data;
        List<orderBean> codPageRecords = (List<orderBean>) JSON.deserialize(codPageRecordsLWC, List<orderBean>.class);
        sqlagencyProType = '%' + agencyProTypeLWC + '%';
        system.debug('sqlagencyProType==>' + sqlagencyProType);
        barcode = barcodeLWC;
        system.debug('barcode==>' + barcode);
        userWorkLocation = userWorkLocationLWC;
        // add by Wang Xueqin 2023/04/12
        // 获取用户和经销商信息
        user Useracc = [SELECT Accountid, Work_Location__c, UserPro_Type__c FROM user WHERE id = :UserInfo.getUserId()];
        accountInfo = [SELECT id, Name, Dealer_discount__c FROM account WHERE id = :Useracc.accountid];

        iSinventory = true;
        Set<String> barCodeoverdue = new Set<String>();
        overduePageRecords = new List<orderBean>();
        List<String> barCodeListP = ParseBarCode(barcode);
        // 页面显示数据初始化
        for (orderBean codPage : codPageRecords) {
            codPage.pandian = 0;
        }
        // 查询所有过期库存
        List<Consumable_order_details2__c> orderDetZaiku = [
            SELECT
                Id,
                Name,
                Consumable_Product__c,
                Bar_Code__c,
                Consumable_Product__r.Name__c,
                Dealer_Info_text__c,
                Asset_Model_No__c,
                Isoverdue__c,
                Box_Piece__c,
                Sterilization_limit__c,
                Bar_Code_search__c
            FROM Consumable_order_details2__c
            WHERE
                Dealer_Arrive__c = TRUE
                AND Dealer_Shipment__c = FALSE
                AND Dealer_Saled__c = FALSE
                AND Lose_Flag__c = FALSE
                AND Isoverdue__c = 0
                AND Dealer_Returned__c = FALSE
                AND Cancellation_Flag__c = FALSE
                AND Bar_Code__c != NULL
                AND Product_Type__c LIKE :sqlagencyProType
                AND Dealer_Info_text__c = :accountInfo.Name
                AND Arrive_Owner_Work_Location__c = :userWorkLocation
        ];
        // 没有输入条码时，循环页面，所有打钩产品全部销存
        // 取得所有
        overdueList = new List<Consumable_order_details2__c>();
        if (String.isBlank(barcode)) {
            System.debug('barcode空');
            for (orderBean codPage : codPageRecords) {
                if (codPage.check) {
                    for (Consumable_order_details2__c cod2 : orderDetZaiku) {
                        if (cod2.Consumable_Product__c == codPage.prodid && codPage.boxPiece == cod2.Box_Piece__c) {
                            overduePageRecords.add(new orderBean(cod2, '过期库存销存'));
                            overdueList.add(cod2);
                        }
                    }
                    codPage.pandian = codPage.overlimitCount;
                }
            }
            // return;
            System.debug('overduePageRecords = ' + overduePageRecords);
            System.debug('overdueList = ' + overdueList);
            data.put('overduePageRecords', JSON.serialize(overduePageRecords));
            data.put('codPageRecords', JSON.serialize(codPageRecords));
            data.put('iSinventory', iSinventory);
            data.put('overdueList', overdueList);
            res.status = 'Success1';
            res.code = 200;
            // res.msg = '请输入BarCode号';
            System.debug('res = ' + res);
            return res;
        }

        // 输入barcode时

        // BarCode的检索  所有在库
        List<Consumable_order_details2__c> reSet = [
            SELECT
                Id,
                Consumable_Product__c,
                Consumable_Product__r.Name__c,
                Box_Piece__c,
                Bar_Code_search__c,
                Dealer_Shipment__c,
                Dealer_Saled__c,
                Lose_Flag__c,
                Bar_Code__c,
                Cancellation_Flag__c,
                Isoverdue__c,
                Sterilization_limit__c
            FROM Consumable_order_details2__c
            WHERE
                Bar_Code_search__c IN :BarCodeListP
                AND Dealer_Arrive__c = TRUE
                AND Cancellation_Flag__c = FALSE
                AND Dealer_Returned__c = FALSE
                AND Bar_Code__c != NULL
                AND Product_Type__c LIKE :sqlagencyProType
                AND Arrive_Owner_Work_Location__c = :userWorkLocation
                AND Dealer_Info_text__c = :accountInfo.Name
            ORDER BY Name
        ];

        System.debug('reSet===>' + reSet);

        for (Consumable_order_details2__c cod2 : reSet) {
            if (
                (cod2.Dealer_Shipment__c == false &&
                cod2.Dealer_Saled__c == false &&
                cod2.Lose_Flag__c == false &&
                cod2.Cancellation_Flag__c == false) && cod2.Isoverdue__c == 0
            ) {
                for (orderBean codPage : codPageRecords) {
                    if (cod2.Consumable_Product__c == codPage.prodid && cod2.Box_Piece__c == codPage.boxPiece) {
                        overduePageRecords.add(new orderBean(cod2, '过期库存销存'));
                        overdueList.add(cod2);
                        codPage.pandian++;
                        codPage.check = true;
                    }
                }
            } else if (cod2.Dealer_Shipment__c || cod2.Dealer_Saled__c) {
                overduePageRecords.add(new orderBean(cod2, '产品已经出库'));
            } else {
                overduePageRecords.add(new orderBean(cod2, '不是过期库存'));
            }
        }
        System.debug('overduePageRecords = ' + overduePageRecords);
        data.put('overduePageRecords', JSON.serialize(overduePageRecords));
        data.put('codPageRecords', JSON.serialize(codPageRecords));
        data.put('iSinventory', iSinventory);
        data.put('overdueList', overdueList);
        res.status = 'Success';
        res.code = 200;
        System.debug('res = ' + res);
        return res;
    }

    // 保存按钮
    @AuraEnabled
    public static ResponseBodyLWC save(Boolean iSinventory, string saveCodPageRecords, List<Consumable_order_details2__c> saveoverdueList) {
        ResponseBodyLWC res = new ResponseBodyLWC();
        Map<String, object> data = new Map<String, object>();
        res.entity = data;
        system.debug('saveCodPageRecords=============>' + saveCodPageRecords);
        system.debug('saveoverdueList' + saveoverdueList);
        overdueList = saveoverdueList;
        // if(saveoverdueList==null){
        //     return new ResponseBodyLWC('Error',500, '请选择要销存的明细', '');

        // }

        List<orderBean> codPageRecords = (List<orderBean>) JSON.deserialize(saveCodPageRecords, List<orderBean>.class);
        // List<Consumable_order_details2__c> overdueList = (List<Consumable_order_details2__c>)JSON.deserialize(saveoverdueList,List<Consumable_order_details2__c>.class);
        // add by Wang Xueqin 2023/04/12
        // 获取用户和经销商信息
        user Useracc = [SELECT Accountid, Work_Location__c, UserPro_Type__c FROM user WHERE id = :UserInfo.getUserId()];
        accountInfo = [SELECT id, Name, Dealer_discount__c FROM account WHERE id = :Useracc.accountid];

        // 跳过明细2不必要更新
        StaticParameter.EscapeConsumableOrderDetail2Trigger = true;
        if (!iSinventory) {
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'请先点【BarCode录入】'));
            return new ResponseBodyLWC('Error', 500, '请先录入BarCode', '');
            // return null;
        }
        integer Lo = 0;
        for (orderBean header : codPageRecords) {
            if (header.check == true) {
                Lo++;
            }
        }
        if (Lo == 0) {
            iSinventory = false;
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'请选择要销存的明细。'));
            return new ResponseBodyLWC('Error', 500, '请选择要销存的明细', '');
            // return null;
        }
        Integer orderDetNo = 1;
        Savepoint sp = Database.setSavepoint();
        Consumable_order__c po = new Consumable_order__c();
        po.Name = '*';
        po.Order_status__c = '批准';
        po.Inventory_date__c = Date.today();
        po.Order_type__c = '销存';
        po.Dealer_Info__c = accountInfo.Id;
        po.Order_ProType__c = agencyProType;
        po.RecordTypeid = System.Label.RT_ConOrder_Overdue;
        try {
            insert po;
            Consumable_order__c order = [SELECT Name FROM Consumable_order__c WHERE id = :po.id];
            List<Consumable_orderdetails__c> InsList = new List<Consumable_orderdetails__c>();
            for (orderBean header : codPageRecords) {
                if (header.check == true) {
                    Consumable_orderdetails__c insPan = new Consumable_orderdetails__c();
                    String str = string.valueOf(orderDetNo);
                    if (str.length() == 1) {
                        str = '0' + str;
                    }
                    insPan.Name = order.Name + '-' + str;
                    insPan.Consumable_Product__c = header.prodId;
                    insPan.Consumable_order__c = po.Id;
                    insPan.Lose_reason__c = '过期库存销存';
                    insPan.Overdue_count__c = header.pandian;
                    insPan.Overdue_SUM__c = header.overlimitCount;
                    insPan.RecordTypeId = System.Label.RT_ConOrderDetail1_Inventory;
                    orderDetNo++;
                    InsList.add(insPan);
                }
            }
            // 生成明细1
            if (InsList.size() > 0) {
                insert InsList;
            }

            for (Consumable_order_details2__c cod : overdueList) {
                cod.Consumable_Inventory_order__c = po.Id;
                cod.Inventory_date__c = Date.today();
                cod.Lose_reason__c = '过期库存销存';
                cod.Lose_Flag__c = true;
            }
            if (overdueList.size() > 0) {
                ControllerUtil.updateOrderDetailsSatus(overdueList);
            }
        } catch (Exception ex) {
            Database.rollback(sp);
            ApexPages.addMessages(ex);
            return null;
        }
        // return new Pagereference('/' + po.Id);
        data.put('Id', po.Id);
        res.status = 'Success';
        res.code = 200;
        System.debug('res = ' + res);
        return res;
    }

    // 将页面或取得BarCode去掉重复的，转换成List
    public static List<String> ParseBarCode(String Code) {
        Map<String, Integer> barcodeCountMap = new Map<String, Integer>();
        String[] Cache = new List<String>{};
        Cache = Code.split('\n');
        List<String> Buff = new List<String>();
        for (String A : Cache) {
            A = A.trim().toUpperCase();
            if (barcodeCountMap.containsKey(A)) {
                barcodeCountMap.put(A, barcodeCountMap.get(A) + 1);
            } else {
                barcodeCountMap.put(A, 1);
            }
            Buff.add(A + barcodeCountMap.get(A));
        }
        return Buff;
    }

    // Data Bean
    @TestVisible
    class orderBean implements Comparable {
        @AuraEnabled
        public Consumable_order_details2__c orderdetails2 { get; set; }
        @AuraEnabled
        public Product2__c Prod { get; set; }
        @AuraEnabled
        public Boolean check { get; set; }

        // 过期库存
        @AuraEnabled
        public Integer overlimitCount { get; set; }
        // 销存数量
        @AuraEnabled
        public Integer pandian { get; set; }
        // 销存原因
        @AuraEnabled
        public String diffReason { get; set; }
        // 单位
        @AuraEnabled
        public String boxPiece { get; set; }
        @AuraEnabled
        public String prodname { get; set; }
        @AuraEnabled
        public String prodid { get; set; }
        orderBean(Consumable_order_details2__c e, string str) {
            orderdetails2 = e;
            Prod = e.Consumable_Product__r;
            DiffReason = str;
        }
        public orderBean(AggregateResult e) {
            check = false;
            overlimitCount = Integer.valueOf(e.get('countsum'));
            prodname = String.valueOf(e.get('prodname'));
            prodid = String.valueOf(e.get('prodid'));
            boxPiece = String.valueOf(e.get('BoxPiece'));
            pandian = 0;
        }
        // 排序
        public Integer compareTo(Object compareTo) {
            orderBean compareToesd = (orderBean) compareTo;
            Integer returnValue = 0;
            if (overlimitCount > compareToesd.overlimitCount) {
                returnValue = -1;
            } else if (overlimitCount < compareToesd.overlimitCount) {
                returnValue = 1;
            }
            return returnValue;
        }
    }
}