public with sharing class InventoryResultRecordController {
    // 检索区域
    public String fixtureModelNo {get; set;}  // 备品配套明细型号 Fixture_Model_No__c
    public String assetStatus {get; set;}  // 备品状态 Asset_Status__c
    public String assetCategory {get; set;}  // 备品类别 耗材/备品
    public String salesdepartment {get; set;}  // 所在地区本部 Salesdepartment__c
    public String salesProvince {get; set;}  // 所在地区省 SalesProvince__c
    public String whLocation {get; set;}  // 货架号 WH_location__c
    public String internal_Asset_Flg {get; set;}  // 固定资产 Internal_Asset_Flg__c
    public String inventory_Deviation {get; set;}  // 盘点误差 Inventory_Deviation__c
    public Date consumable_Guaranteen_end {get; set;} // 消耗品有效期至
    public String bpPankuiYing { get; set; }      // 盘亏/盘盈
    public String ifInternalAsset { get; set; }   // 是否固定资产
    public String keyword { get; set; }
    public Boolean hasConsumAsset {get;set;}
    //add by rentx 20210901 start 
    public List<String> allHCCodelist {get;set;}
    //add by rentx 20210901 end
    public String consumable_Guaranteen_endStr {
        get;
        set{
            consumable_Guaranteen_endStr = value;
            if (String.isNotBlank(consumable_Guaranteen_endStr)) {
                consumable_Guaranteen_end = Date.valueOf(consumable_Guaranteen_endStr.replace('/', '-'));
            }
            else {
                consumable_Guaranteen_end = null;
            }
        }
    } // 消耗品有效期至
    public static final String NONE = system.label.StartTrading_None;  // 「なし」ラベル [Chinese:--无--]
    public static bp3_Setting__c conf = bp3_Setting__c.getOrgDefaults();
    private String mainAstQR = '';
    public boolean doneFlg {get; set;}
    public boolean canDoFlg {get; set;}

    public List<SelectOption> assetStatusOptionList {
        get {
            // FIXME StartTrading_None を使う、--なし-- はNGでしょう
            List<SelectOption> selectOptions = new List<SelectOption> { new SelectOption(NONE, NONE) };
            selectOptions.add(new SelectOption('未盘点', '未盘点'));
            selectOptions.add(new SelectOption('已盘点', '已盘点'));
            return selectOptions;
        }
    }
    public List<SelectOption> assetCategoryOptionList {
        get {
            //默认不展示 --无-- updatebyrentx 20210824
            List<SelectOption> selectOptions = new List<SelectOption> { /*new SelectOption(NONE, NONE)*/ };
            selectOptions.add(new SelectOption('备品', '备品'));
            selectOptions.add(new SelectOption('耗材', '耗材'));
            return selectOptions;
        }
    }

    // 所在地区(本部)PlickList
    public List<SelectOption> salesdepartmentOpts {
        get {
            if (salesdepartmentOpts == null) {
                salesdepartmentOpts = getPlickList('Asset', 'Salesdepartment__c');
            }
            return salesdepartmentOpts;
        }
        set;
    }

    // 所在地区(省)PlickList
    public List<SelectOption> salesProvinceOpts {
        get {
            if (salesProvinceOpts == null) {
                salesProvinceOpts = getPlickList('Asset', 'SalesProvince__c');
            }
            return salesProvinceOpts;
        }
        set;
    }

    //public Asset assetQuery {get; set;}  // 查询用

    public List<Inventory_Detail__c> inventoryDetailList {get; set;}  // 查看全部保有设备结果
    public List<Consum_Inventory_Detail__c> consumInventoryDetailList {get; set;}  // 查看全部保有设备结果

    public String bieCunFangDi { get; set; }     //别存放地, 肯定有值 不为null
    public String deptCheck_PIC { get; set; }  //办事处的确认人 20210618 1650 you
    public String qrType {get; set;}
    public String qrError {get; set;}
    public String qrId {get; set;}
    public List<String> accsessaryNameList {get; set;}
    public boolean canStartFlg {get; set;}
    private Map<String, List<String>> statusMap {get; set;}
    //private Set<String> inventoryModelNo {get; set;}  // 查看全部保有设备结果
    public Inventory_Detail__c id_dummy {get; set;}  // 查看全部保有设备结果
    public String inventoryUser1 {get; set;}  // 查看全部保有设备结果
    public String inventoryUser2 {get; set;}  // 查看全部保有设备结果
    public String inventoryUser3 {get; set;}  // 查看全部保有设备结果
    public Inventory_Header__c inventoryHeader {get; set;}  // 查看全部保有设备结果
    public Inventory_Header__c consumInventoryHeader {get; set;}  // 查看全部保有设备结果
    public Map<String, Integer> unfixAssetMap {get; set;}
    public Map<String, Integer> fixAssetMap {get; set;}
    public Map<String, Integer> consumAssetMap {get; set;}
    public Map<String, Integer> sumRateMap {get; set;}      // 合计进展率&合计实盘率Map
    private Map<String, Decimal> oldCountMap {get; set;}
    private List<User> inventoryUserList {get; set;}
    public String descStr {get; set;}
    public String descSHStr {get; set;}
    public String descNotSHStr {get; set;}
    public Boolean angecylookrole {get; set;}  // 只读权限 1650 20210628


    public InventoryResultRecordController() {

    }

    public InventoryResultRecordController(ApexPages.StandardController controller) {

    }

    //别存放地 SelectOption
    public List<SelectOption> getbieCunFangDiOps() {
        if (UserInfo.getProfileId() == System.Label.ProfileId_SystemAdmin || System.Label.ProfileId_EquCenAdmin.contains(UserInfo.getProfileId())) {
            List<SelectOption> sl;
            //简档 2B3_备品中心管理者(照片) 在开始盘点的时候能看到所有的办事处信息
            if(UserInfo.getProfileId() == System.Label.ProfileId_EquCenAdminPic){//20211217 you 课题C9Q9JQ
                sl =  getPlickList('Asset', 'Internal_asset_location__c');
            }else{
                sl = FixtureUtil.bieCunFangDiOpsMap.get('备品管理中心');
                if (sl[0].getValue() == 'All') sl.remove(0);
            }
            
            return sl;
        } else {
            return new List<SelectOption>{
                new SelectOption(bieCunFangDi, bieCunFangDi)
            };
        }
    }
    //盘点人 SelectOption
    public List<SelectOption> getInventoryUserOps() {
        if (inventoryUserList.size() > 0) {
            List<SelectOption> selectOptions = new List<SelectOption>{ new SelectOption(NONE, NONE) };
            for (User iuser : inventoryUserList) {
                selectOptions.add(new SelectOption(iuser.Id, iuser.Name));
            }
            return selectOptions;
        } else {
            return new List<SelectOption> { new SelectOption(NONE, NONE) };
        }
    }

    // 画面初始化
    public void init() {
        angecylookrole = false;
        bpPankuiYing = NONE;
        ifInternalAsset = NONE;
        assetStatus = NONE;
        assetCategory = NONE;
        salesdepartment = NONE;
        salesProvince = NONE;
        whLocation = null;
        keyword = null;
        consumable_Guaranteen_endStr = null;
        sumRateMap = getRateMap(0, 0, 0);
        User currUser = [
                Select Id, Name,Dept__c, Default_Referable_Apply_Equipment_Center__c, JingliEquipmentId__c
                From User
                Where Id = :UserInfo.getUserId()];
        if (String.isBlank(currUser.Default_Referable_Apply_Equipment_Center__c)) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '当前用户所在地不能为空'));
            return;
        }
        

        bieCunFangDi = currUser.Default_Referable_Apply_Equipment_Center__c;
        deptCheck_PIC = currUser.Dept__c; //20210618 1650 you
        String cunFangDi = ApexPages.currentPage().getParameters().get('cunFangDi');
        hasConsumAsset = false;
        system.debug(cunFangDi+'==177='+bieCunFangDi);
        if (cunFangDi != null) bieCunFangDi = cunFangDi;
        //20210628 you 1650 办事处看不到 货架号
        if (bieCunFangDi=='广州 备品中心' || bieCunFangDi=='北京 备品中心' || bieCunFangDi=='上海 备品中心') {
            angecylookrole =true;
        }
        //inventoryModelNo = new Set<String>();
        accsessaryNameList = new List<String>();
        id_dummy = new Inventory_Detail__c();
        //Asset ast = [select Id from Asset limit 1];
        //assetQuery = new Asset(Id=ast.Id);
        inventoryDetailList = new List<Inventory_Detail__c>();
        consumInventoryDetailList = new List<Consum_Inventory_Detail__c>();
        //add by rentx 20210901 start
        allHCCodelist = new List<String>();
        //add by rentx 20210901 end
        descStr = conf.BeiPin_Desc__c;
        descSHStr = conf.SH_BeiPin_Desc__c;
        descNotSHStr = conf.Not_SH_BeiPin_Desc__c;

        List<Inventory_User_Permission__mdt> usrList = [select InventoryUser__c from Inventory_User_Permission__mdt where Label = :bieCunFangDi];
        if(null!=usrList && usrList.size()>0){//20211217 you 课题C9Q9JQ
          Id[] usrArray = usrList[0].InventoryUser__c.split(',');
          inventoryUserList = [select id, name from user where id in :usrArray];
          inventoryUser1 = usrList[0].InventoryUser__c.contains(UserInfo.getUserId()) ? UserInfo.getUserId() : NONE;

        }
        
        statusMap = new Map<String, List<String>>();
        //备品搬家 20210706  SFDC-C5CC5S 暂停
        List<Inventory_Header__c> ihList = [
            select Id, Inventory_Status__c, Name, Internal_asset_location__c, Inventory_Start_Date__c, Fixture_Header__c
              from Inventory_Header__c
             where Inventory_Status__c <> '已批准' and Internal_asset_location__c =:bieCunFangDi
                and Inventory_Start_Date__c = LAST_N_DAYS:30
                ORDER BY Fixture_Header__c NULLS FIRST];
        // List<Inventory_Header__c> ihList = [
        //     select Id, Inventory_Status__c, Name, Internal_asset_location__c, Inventory_Start_Date__c, Fixture_Header__c
        //       from Inventory_Header__c
        //      where Inventory_Status__c <> '已批准' and Internal_asset_location__c =:bieCunFangDi
        //         and Inventory_Start_Date__c = LAST_N_DAYS:1
        //         ORDER BY Fixture_Header__c NULLS FIRST];        
        inventoryHeader = null;
        consumInventoryHeader = null;
        canDoFlg = false;
        unfixAssetMap = getInitData(new List<AggregateResult>(), 'unfix');
        fixAssetMap = getInitData(new List<AggregateResult>(), 'fix');
        consumAssetMap = getInitData(new List<AggregateResult>(), 'consum');
        if (ihList.size() == 0){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '没有开始中的盘点，请点击开始盘点'));
        }
        for(Inventory_Header__c ih:ihList){
            if(String.isBlank(ih.Fixture_Header__c)) {
                if( String.isNotBlank(ih.Inventory_Status__c)){
                    if (ih.Inventory_Status__c == '处理中') {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '盘点处理中，请等待Batch处理完毕。Batch处理完毕后会发送处理结果邮件。'));
                    }
                    else{
                        inventoryHeader = ih;
                        canDoFlg = canDoFlg || !System.Approval.isLocked(inventoryHeader.Id);

                        List<AggregateResult> fixAssetList = [
                                Select Internal_Asset_Flg__c fix, Asset_Status__c status, sum(toAbandon_amount__c) abAmount, sum(Amount__c) amount, sum(Inventory_Count__c) acAmount
                                From Inventory_Detail__c//20210525 you 1650
                                Where Inventory_Header__c = :inventoryHeader.Id AND Asset_Status__c <> '丢失借出明细' AND Asset_Status__c <> '丢失调拨明细'
                                group by Internal_Asset_Flg__c, Asset_Status__c];
                        unfixAssetMap = getInitData(fixAssetList, 'unfix');
                        fixAssetMap = getInitData(fixAssetList, 'fix');
                    }
                }
                else{
                    unfixAssetMap = getInitData(new List<AggregateResult>(), 'unfix');
                    fixAssetMap = getInitData(new List<AggregateResult>(), 'fix');
                }
            }
            else {
                hasConsumAsset = true;
                if (String.isNotBlank(ih.Inventory_Status__c)) {
                    if (ih.Inventory_Status__c == '处理中') {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '耗材盘点处理中，请等待Batch处理完毕。Batch处理完毕后会发送处理结果邮件。'));
                    }
                    else{
                        consumInventoryHeader = ih;
                        canDoFlg = canDoFlg || !System.Approval.isLocked(consumInventoryHeader.Id);
                        List<AggregateResult> consumAssetList = [
                                Select Internal_Asset_Flg__c fix, Asset_Status__c status, sum(toAbandon_amount__c) abAmount, sum(Amount__c) amount, sum(Inventory_Count__c) acAmount
                                From Consum_Inventory_Detail__c
                                Where Inventory_Header__c = :consumInventoryHeader.Id
                                AND Asset_Status__c != '已消耗明细'
                                group by Internal_Asset_Flg__c, Asset_Status__c];
                        consumAssetMap = getInitData(consumAssetList, 'consum');
                    }
                }
                else{
                    consumAssetMap = getInitData(new List<AggregateResult>(), 'consum');
                }
            }
        }
        //System.assertEquals('qyj','unfixAssetMap'+unfixAssetMap);
        //System.assertEquals('qyj','fixAssetMap'+fixAssetMap);
        //System.assertEquals('qyj','consumAssetMap'+consumAssetMap);
        sumRateMap = getRateMap(unfixAssetMap.get('allsum')+fixAssetMap.get('allsum')+consumAssetMap.get('allsum')
                                , unfixAssetMap.get('dsum')+fixAssetMap.get('dsum')+consumAssetMap.get('dsum')
                                , unfixAssetMap.get('acsum')+fixAssetMap.get('acsum')+consumAssetMap.get('acsum'));
    }

    //public void checkQRCode() {
    //    String soqlWhere = '';
    //    if (!String.isBlank(assetQuery.WH_Location__c)) {
    //        soqlWhere += ' AND WH_Location__c = \'' + assetQuery.WH_Location__c + '\' ';
    //    }  // 货架号
    //    if (!String.isBlank(id_dummy.VWH_Location__c)) {
    //        if (id_dummy.VWH_Location__c == '待报废') {
    //            soqlWhere += 'AND toAbandon_amount__c > 0 ';
    //        } else {
    //            soqlWhere += 'AND VWH_Location__c = \'' + id_dummy.VWH_Location__c + '\' ';
    //        }

    //    }  // 虚拟货架号
    //    if (assetStatus != NONE) {
    //        if (assetStatus == '未盘点') soqlWhere += 'AND Inventory_Time__c = null ';
    //        if (assetStatus == '已盘点') soqlWhere += 'AND Inventory_Time__c <> null ';
    //    }  // 备品状态
    //    if (!String.isBlank(assetQuery.Salesdepartment__c)) {
    //        soqlWhere += 'AND Asset__r.Salesdepartment__c = \'' + assetQuery.Salesdepartment__c + '\' ';
    //    }  // 所在地区 本部 Saless_Department__c
    //    if (!String.isBlank(assetQuery.SalesProvince__c)) {
    //        soqlWhere += 'AND Asset__r.SalesProvince__c = \'' + assetQuery.SalesProvince__c + '\' ';
    //    }  // 所在地区 省 Sales_Province__c
    //    if (assetQuery.Consumable_Guaranteen_end__c != NULL) {
    //        Date tempDate = assetQuery.Consumable_Guaranteen_end__c;
    //        //System.debug('====:tempDate' + tempDate);
    //        soqlWhere += 'AND Asset__r.Consumable_Guaranteen_end__c = :tempDate ';
    //    }

    //    //附属品扫描状态
    //    String scanType = ApexPages.currentPage().getParameters().get('scanType');
    //    String qrcode = ApexPages.currentPage().getParameters().get('qrcode');
    //    String headId = inventoryHeader.Id;
    //    String searchSql = '';
    //    if (scanType == '2') {
    //        searchSql = 'select id, Asset__c, Main_Asset__c, Asset__r.Manage_type__c ' +
    //                        'from Inventory_Detail__c '+
    //                        'where Asset__r.Fixture_QRCode__c = :qrcode and OneToOne_Accsessary__c = true and Main_Asset__c = :mainAstQR ' +
    //                              'and Inventory_Header__c = :headId and Asset_Status__c = \'在库\' and Amount__c > 0' +
    //                        soqlWhere;
    //        List<Inventory_Detail__c> accList = Database.query(searchSql);
    //        if (accList.size() > 0) {
    //            qrError = '';
    //            qrId = accList[0].Main_Asset__c + ':' + accList[0].Asset__c;
    //            qrType = accList[0].Asset__r.Manage_type__c != '数量管理' ? '4' : '5';
    //        } else {
    //            qrError = '不存在此附属品';
    //        }
    //        return;
    //    }
    //    mainAstQR = '';
    //    //是否一对一主体
    //    searchSql = 'select id, Main_Asset__c ' +
    //                    'from Inventory_Detail__c '+
    //                    'where Main_Asset__r.Fixture_QRCode__c = :qrcode and OneToOne_Body__c = true ' +
    //                          'and Inventory_Header__c = :headId and Asset_Status__c = \'在库\' and Amount__c > 0' +
    //                    soqlWhere;
    //    List<Inventory_Detail__c> idList = Database.query(searchSql);
    //    if (idList.size() > 0) {
    //        qrError = '';
    //        qrType = '2';
    //        qrId = idList[0].Main_Asset__c;
    //        mainAstQR = idList[0].Main_Asset__c;
    //        //searchSql = 'select id, Main_Asset__c, Fixture_Model_No__c, Amount__c ' +
    //        //                'from Inventory_Detail__c '+
    //        //                'where Main_Asset__c = :qrId and OneToOne_Accsessary__c = true ' +
    //        //                      'and Inventory_Header__c = :headId and Asset_Status__c = \'在库\' and Amount__c > 0' +
    //        //                soqlWhere;
    //        //List<Inventory_Detail__c> accsessaryList = Database.query(searchSql);
    //        //accsessaryNameList = new List<String>();
    //        //for (Inventory_Detail__c accsessary : accsessaryList) {
    //        //    accsessaryNameList.add(accsessary.Fixture_Model_No__c);
    //        //}

    //        return;
    //    }

    //    //查找当前画面中非一对一附属品
    //    searchSql = 'select id, Fixture_Model_No__c, Asset__r.Manage_type__c, Asset__c ' +
    //                    'from Inventory_Detail__c '+
    //                    'where Asset__r.Fixture_QRCode__c = :qrcode and Inventory_Header__c = :headId ' +
    //                          'and OneToOne_Accsessary__c = false and Asset_Status__c = \'在库\' and Amount__c > 0' +
    //                    soqlWhere;
    //    List<Inventory_Detail__c> ast = Database.query(searchSql);
    //    System.debug(ast);
    //    if (ast.size() > 0) {
    //        qrError = '';
    //        if (ast[0].Asset__r.Manage_type__c == '数量管理') {
    //            qrType = '1';
    //        } else {
    //            qrType = '3';
    //        }
    //        qrId = ast[0].Asset__c;
    //    } else {
    //        searchSql = 'select id, Fixture_Model_No__c, Asset__r.Manage_type__c, Asset__c ' +
    //                    'from Inventory_Detail__c '+
    //                    'where Asset__r.Fixture_QRCode__c = :qrcode and Inventory_Header__c = :headId ' +
    //                          'and OneToOne_Accsessary__c = true and Asset_Status__c = \'在库\' and Amount__c > 0' +
    //                    soqlWhere;
    //        ast = Database.query(searchSql);
    //        if (ast.size() > 0) {
    //            qrError = '一对一附属品请先扫描主体';
    //        } else {
    //            qrError = '不存在此备品';
    //        }
    //    }
    //}

    public void startInventory() {
        String userStr = '';
        String submitPIC = '';
        String checkPIC = '';
        if (bieCunFangDi == '北京 备品中心') {
            userStr = conf.BJ_Start_Inventory_User__c;
            submitPIC = conf.BJ_InventorySubmit_PIC__c;
            checkPIC = conf.BJ_InventoryCheck_PIC__c;
        } else if (bieCunFangDi == '上海 备品中心') {
            userStr = conf.SH_Start_Inventory_User__c;
            submitPIC = conf.SH_InventorySubmit_PIC__c;
            checkPIC = conf.SH_InventoryCheck_PIC__c;
        } else if (bieCunFangDi == '广州 备品中心') {
            userStr = conf.GZ_Start_Inventory_User__c;
            submitPIC = conf.GZ_InventorySubmit_PIC__c;
            checkPIC = conf.GZ_InventoryCheck_PIC__c;
        } else{

            if (bieCunFangDi == '青岛') {//20210423 you 1650
                userStr = conf.QD_Start_Inventory_User__c;
                submitPIC = conf.QD_InventorySubmit_PIC__c;
                //checkPIC = conf.QD_InventoryCheck_PIC__c;
            } else if (bieCunFangDi == '沈阳') {//20210604 you 1650
                userStr = conf.SY_Start_Inventory_User__c;
                submitPIC = conf.SY_InventorySubmit_PIC__c;
                //checkPIC = conf.SY_InventoryCheck_PIC__c;
            } else if (bieCunFangDi == '呼和浩特') {//20210604 you 1650
                userStr = conf.HHHT_Start_Inventory_User__c;
                submitPIC = conf.HHHT_InventorySubmit_PIC__c;
                //checkPIC = conf.SY_InventoryCheck_PIC__c;
            } else if (bieCunFangDi == '济南') {
                userStr = conf.JN_Start_Inventory_User__c;
                submitPIC = conf.JN_InventorySubmit_PIC__c;
                //checkPIC = conf.SY_InventoryCheck_PIC__c;
            } else if (bieCunFangDi == '郑州') {
                userStr = conf.ZZ_Start_Inventory_User__c;
                submitPIC = conf.ZZ_InventorySubmit_PIC__c;
                //checkPIC = conf.SY_InventoryCheck_PIC__c;
            } else if (bieCunFangDi == '太原') {
                userStr = conf.TY_Start_Inventory_User__c;
                submitPIC = conf.TY_InventorySubmit_PIC__c;
                //checkPIC = conf.SY_InventoryCheck_PIC__c;
            } else if (bieCunFangDi == '西安') {
                userStr = conf.XA_Start_Inventory_User__c;
                submitPIC = conf.XA_InventorySubmit_PIC__c;
                //checkPIC = conf.SY_InventoryCheck_PIC__c;
            } else if (bieCunFangDi == '兰州') {
                userStr = conf.LZ_Start_Inventory_User__c;
                submitPIC = conf.LZ_InventorySubmit_PIC__c;
                //checkPIC = conf.SY_InventoryCheck_PIC__c;
            } else if (bieCunFangDi == '乌鲁木齐') {
                userStr = conf.WLMQ_Start_Inventory_User__c;
                submitPIC = conf.WLMQ_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '大连') {
                userStr = conf.DL_Start_Inventory_User__c;
                submitPIC = conf.DL_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '哈尔滨') {
                userStr = conf.HEB_Start_Inventory_User__c;
                submitPIC = conf.HEB_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '长春') {
                userStr = conf.CC_Start_Inventory_User__c;
                submitPIC = conf.CC_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '银川') {
                userStr = conf.YC_Start_Inventory_User__c;
                submitPIC = conf.YC_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '西宁') {
                userStr = conf.XN_Start_Inventory_User__c;
                submitPIC = conf.XN_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '天津') {
                userStr = conf.TJ_Start_Inventory_User__c;
                submitPIC = conf.TJ_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '上海') {
                userStr = conf.SH_Start_Inventory_User_Agency__c;
                submitPIC = conf.SH_InventorySubmit_PIC_Agency__c;
            } else if (bieCunFangDi == '福州') {
                userStr = conf.FZ_Start_Inventory_User__c;
                submitPIC = conf.FZ_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '杭州') {
                userStr = conf.HZ_Start_Inventory_User__c;
                submitPIC = conf.HZ_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '南京') {
                userStr = conf.NJ_Start_Inventory_User__c;
                submitPIC = conf.NJ_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '南昌') {
                userStr = conf.NC_Start_Inventory_User__c;
                submitPIC = conf.NC_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '合肥') {
                userStr = conf.HF_Start_Inventory_User__c;
                submitPIC = conf.HF_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '长沙') {
                userStr = conf.CS_Start_Inventory_User__c;
                submitPIC = conf.CS_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '贵阳') {
                userStr = conf.GY_Start_Inventory_User__c;
                submitPIC = conf.GY_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '武汉') {
                userStr = conf.WH_Start_Inventory_User__c;
                submitPIC = conf.WH_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '昆明') {
                userStr = conf.KM_Start_Inventory_User__c;
                submitPIC = conf.KM_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '南宁') {
                userStr = conf.NN_Start_Inventory_User__c;
                submitPIC = conf.NN_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '重庆') {
                userStr = conf.CQ_Start_Inventory_User__c;
                submitPIC = conf.CQ_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '成都') {
                userStr = conf.CD_Start_Inventory_User__c;
                submitPIC = conf.CD_InventorySubmit_PIC__c;
            } else if (bieCunFangDi == '广州') {
                userStr = conf.GZ_Start_Inventory_User_Agency__c;
                submitPIC = conf.GZ_InventorySubmit_PIC_Agency__c;
            } else if (bieCunFangDi == '石家庄') {
                userStr = conf.SJZ_Start_Inventory_User__c;
                submitPIC = conf.SJZ_InventorySubmit_PIC__c;
            }

            //20210618 1650 you 办事处的确认人为这几个
            if(deptCheck_PIC=='医疗东北营业本部'){
                checkPIC = '00510000001O6HoAAK';
            }else if(deptCheck_PIC=='医疗华北营业本部'){
                checkPIC = '00510000001O6I2AAK';
            }else if(deptCheck_PIC=='医疗西北营业本部'){
                checkPIC = '00510000000gW9pAAE';
            }else if(deptCheck_PIC=='医疗华东营业本部'){
                checkPIC = '00510000000gW9BAAU';
            }else if(deptCheck_PIC=='医疗西南营业本部'){
                checkPIC = '00510000008pVbWAAU';
            }else if(deptCheck_PIC=='医疗华南营业本部'){
                checkPIC = '00510000001OOMjAAO';
            }

        }
        if (!userStr.contains(UserInfo.getUserId().left(15))) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '没有开始盘点的权限'));
            return;
        }
        User currUser1 = [
                Select Id, JingliEquipmentId__c
                From User
                Where Id = :UserInfo.getUserId()];
        if (null==currUser1.JingliEquipmentId__c) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '备品审批流为空，无法开始盘点，请维护。'));  
            return;
        }
        // 备品搬家 SFDC-C5CC5S 暂停
        List<Inventory_Header__c> ihList = [select Id, Inventory_Status__c, Name, Internal_asset_location__c, Inventory_Start_Date__c from Inventory_Header__c where Internal_asset_location__c =:bieCunFangDi and Inventory_Start_Date__c = LAST_N_DAYS:30];
        // List<Inventory_Header__c> ihList = [select Id, Inventory_Status__c, Name, Internal_asset_location__c, Inventory_Start_Date__c from Inventory_Header__c where Internal_asset_location__c =:bieCunFangDi and Inventory_Start_Date__c = LAST_N_DAYS:1];
        if (ihList.size() > 0) {
            if (ihList[0].Inventory_Status__c == null) {
                //do nothing
                InventoryStartAssetSnapshotBatch istarter = new InventoryStartAssetSnapshotBatch(bieCunFangDi, ihList[0]);
                Database.executeBatch(istarter, 50);

                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '开始盘点处理，请等待Batch处理结束'));
                return;
            } else {
                if (ihList[0].Inventory_Status__c <> '已批准') {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '有未结束的盘点'));
                } else {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '本仓库本月已进行过盘点'));
                }
                return;
            }
        }
       
        Inventory_Header__c ih_new = new Inventory_Header__c();
        ih_new.Internal_asset_location__c = bieCunFangDi;
        ih_new.Inventory_Status__c = '处理中';
        ih_new.InventoryPIC__c = UserInfo.getUserId();
        ih_new.Inventory_Start_Date__c = Date.today();
        ih_new.InventorySubmit_PIC__c = String.isBlank(submitPIC) ? null : submitPIC;
        ih_new.InventoryCheck_PIC__c = String.isBlank(checkPIC) ? null : checkPIC;
        ih_new.UniqueKey__c = bieCunFangDi+':'+Date.today().toStartOfMonth();
        //.toStartOfMonth(); 备品搬家  uniqueKey保证唯一  SFDC-C5CC5S
        
        FixtureUtil.withoutUpsertIh(new List<Inventory_Header__c> {ih_new});

        InventoryStartAssetSnapshotBatch istarter = new InventoryStartAssetSnapshotBatch(bieCunFangDi, ih_new);
        Database.executeBatch(istarter, 50);

        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '开始盘点处理，请等待Batch处理结束'));
    }

    public void save() {
        doneFlg = false;
        // 类别为备品或为空 <=> 类别!=耗材
        if (assetCategory != '耗材' && inventoryHeader!=null && String.isNotBlank(inventoryHeader.Id) && System.Approval.isLocked(inventoryHeader.Id)) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '此盘点已锁定，不能修改盘点数据'));
            return ;
        }
        // 类别为耗材或为空 <=> 类别!=备品
        if (assetCategory != '备品'  && consumInventoryHeader!=null && String.isNotBlank(consumInventoryHeader.Id) && System.Approval.isLocked(consumInventoryHeader.Id)) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '此耗材盘点已锁定，不能修改盘点数据'));
            return ;
        }
        try {
            List<sObject> upsertList = new List<sObject>();
            Set<Id> cleanInventoryTimeSet = new Set<Id>();
            for(Inventory_Detail__c idc : inventoryDetailList) {
                //只保存有变化的盘点数量
                if (!oldCountMap.containsKey(idc.Id)) continue;
                Decimal oldCount = oldCountMap.get(idc.Id);
                Decimal oldCount_int = oldCount == null ? 0 : oldCount;
                Decimal newCount = idc.Inventory_Count__c;
                Decimal newCount_int = newCount == null ? 0 : newCount;
                if (oldCount_int == newCount_int && !((oldCount == null && newCount == 0) || (oldCount == 0 && newCount == null))) continue;

                if (idc.Inventory_Count__c != null) {
                    idc.InventoryPerson1__c = inventoryUser1 == NONE ? null : inventoryUser1;
                    idc.InventoryPerson2__c = inventoryUser2 == NONE ? null : inventoryUser2;
                    idc.InventoryPerson3__c = inventoryUser3 == NONE ? null : inventoryUser3;
                    idc.Inventory_Time__c = System.now();
                } else {
                    idc.InventoryPerson1__c = null;
                    idc.InventoryPerson2__c = null;
                    idc.InventoryPerson3__c = null;
                    idc.Inventory_Time__c = null;
                    cleanInventoryTimeSet.add(idc.Asset__c);
                }
                upsertList.add(idc);
            }
            for(Consum_Inventory_Detail__c idc : consumInventoryDetailList) {
                //只保存有变化的盘点数量
                if (!oldCountMap.containsKey(idc.Id)) continue;
                Decimal oldCount = oldCountMap.get(idc.Id);
                Decimal oldCount_int = oldCount == null ? 0 : oldCount;
                Decimal newCount = idc.Inventory_Count__c;
                Decimal newCount_int = newCount == null ? 0 : newCount;
                if (oldCount_int == newCount_int && !((oldCount == null && newCount == 0) || (oldCount == 0 && newCount == null))) continue;

                if (idc.Inventory_Count__c != null) {
                    idc.InventoryPerson1__c = inventoryUser1 == NONE ? null : inventoryUser1;
                    idc.InventoryPerson2__c = inventoryUser2 == NONE ? null : inventoryUser2;
                    idc.InventoryPerson3__c = inventoryUser3 == NONE ? null : inventoryUser3;
                    idc.Inventory_Time__c = System.now();
                } else {
                    idc.InventoryPerson1__c = null;
                    idc.InventoryPerson2__c = null;
                    idc.InventoryPerson3__c = null;
                    idc.Inventory_Time__c = null;
                    cleanInventoryTimeSet.add(idc.Asset__c);
                }
                upsertList.add(idc);
            }
            if (upsertList.size() > 0) {
                FixtureUtil.withoutUpdate(upsertList);
                //清空的情况，也要清空asset单位的盘点状态
                if (cleanInventoryTimeSet.size() > 0) {
                    List<Inventory_Detail__c> cleanInventoryTimeList = [select Id, Asset_Inventory_Flg__c from Inventory_Detail__c where Asset__c in :cleanInventoryTimeSet and Sync_Asset_Record_Flag__c = true];
                    List<Consum_Inventory_Detail__c> cleanConsumInventoryTimeList = [select Id, Asset_Inventory_Flg__c from Consum_Inventory_Detail__c where Asset__c in :cleanInventoryTimeSet and Sync_Asset_Record_Flag__c = true];
                    upsertList = new List<sObject>();
                    for (Inventory_Detail__c cit : cleanInventoryTimeList) {
                        cit.Asset_Inventory_Flg__c = false;
                        upsertList.add(cit);
                    }
                    for (Consum_Inventory_Detail__c cit : cleanConsumInventoryTimeList) {
                        cit.Asset_Inventory_Flg__c = false;
                        upsertList.add(cit);
                    }
                    FixtureUtil.withoutUpdate(upsertList);
                }
                searchBtn();
            }
            doneFlg = true;
        } catch (exception e) {
            doneFlg = false;
            System.debug(e.getStackTraceString());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,e.getMessage()));
        }

    }

    public void searchBtn() {
        // 类别为备品或为空 <=> 类别!=耗材
        if (assetCategory != '耗材' && inventoryHeader!=null && String.isNotBlank(inventoryHeader.Id) && System.Approval.isLocked(inventoryHeader.Id)) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '此盘点已锁定，不能修改盘点数据'));
            return ;
        }
        // 类别为耗材或为空 <=> 类别!=备品
        if (assetCategory != '备品'  && consumInventoryHeader!=null && String.isNotBlank(consumInventoryHeader.Id) && System.Approval.isLocked(consumInventoryHeader.Id)) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '此耗材盘点已锁定，不能修改盘点数据'));
            return ;
        }
        //add by rentx 20210901 start
        allHCCodelist = new List<String>();
        //add by rentx 20210901 end
        List<Inventory_Header__c> ihList = new List<Inventory_Header__c>();
        //备品搬家 SFDC-C5CC5S
        ihList = [select Id,Inventory_Status__c, Name, Internal_asset_location__c, Inventory_Start_Date__c
                        , Fixture_Header__c
                        from Inventory_Header__c
                        where Inventory_Status__c <> null and Inventory_Status__c <> '已批准' and Internal_asset_location__c =:bieCunFangDi
                          and Inventory_Start_Date__c = LAST_N_DAYS:30
                          ORDER BY Fixture_Header__c nulls first
                        ];
        // ihList = [select Id,Inventory_Status__c, Name, Internal_asset_location__c, Inventory_Start_Date__c
        //                 , Fixture_Header__c
        //                 from Inventory_Header__c
        //                 where Inventory_Status__c <> null and Inventory_Status__c <> '已批准' and Internal_asset_location__c =:bieCunFangDi
        //                   and Inventory_Start_Date__c = LAST_N_DAYS:1
        //                   ORDER BY Fixture_Header__c nulls first
        //                 ];
        oldCountMap = new Map<String, Decimal>();

        if(ihList.isEmpty()) {
            inventoryDetailList = new List<Inventory_Detail__c>();
            consumInventoryDetailList = new List<Consum_Inventory_Detail__c>();
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '没有开始中的盘点，请点击开始盘点'));
            unfixAssetMap = getInitData(new List<AggregateResult>(), 'unfix');
            fixAssetMap = getInitData(new List<AggregateResult>(), 'fix');
            consumAssetMap = getInitData(new List<AggregateResult>(), 'consum');
        }
        system.debug('==='+ihList.size());
        for(Inventory_Header__c ih:ihList){
            Boolean isConsum = String.isNotBlank(ih.Fixture_Header__c);
            String ihId = ih.Id;
            if(assetCategory == '耗材' && !isConsum) continue; //选耗材时，忽略备品的表头
            if(assetCategory == '备品' && isConsum) continue; // 选备品时，忽略耗材的表头
            if (ih.Inventory_Status__c == '处理中') {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '盘点处理中，请等待Batch处理完毕。Batch处理完毕后会发送处理结果邮件。'));
                return;
            }
            String soqlAsset = 'select '
                                + 'Id, Asset__r.SerialNumber, Inventory_Count__c, Asset__c, Asset__r.Manage_type__c, '
                                + ' Fixture_Model_No__c, Fixture_QRCode__c, Asset_Status__c, WH_location__c, Amount__c, Salesdepartment__c,Asset__r.Product2.Packing_list_Fixture_F__c';
            if(isConsum){
                soqlAsset += ', Barcode__c, Asset__r.Product_Serial_No__c ';
                //add by rentx 20210823 start 耗材盘点时记录code ---- 
                soqlAsset += ', HCCodes__c ';
                //add by rentx 20210823 end 耗材盘点时记录code 
                soqlAsset += 'from Consum_Inventory_Detail__c ';
            }
            else{
                soqlAsset += ', OneToOne_Accsessary__c, OneToOne_Body__c, Main_Asset__c, VWH_Location__c ';
                soqlAsset += 'from Inventory_Detail__c ';
            }
            soqlAsset += 'where Inventory_Header__c = :ihId and Asset_Status__c in (\'在库\',\'冻结\') and Amount__c > 0 ';
            if (!String.isBlank(fixtureModelNo)) {
                String[] vals = fixtureModelNo.split(' ');
                system.debug(vals);
                soqlAsset += 'AND (';
                String fmodelno = '';
                for (String v : vals) {
                    // 关键字 -- 备品配套明细型号
                    fmodelno += ' Fixture_Model_No__c LIKE \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\'';
                    fmodelno += 'OR';
                }
                fmodelno = fmodelno.removeEnd('OR');
                soqlAsset += fmodelno + ' )';
            }  // 备品配套明细型号
            if (!String.isBlank(whLocation)) {
                soqlAsset += 'AND WH_Location__c = \'' + String.escapeSingleQuotes(whLocation) + '\' ';
            }  // 货架号
            if (!String.isBlank(id_dummy.VWH_Location__c)) {
                if (id_dummy.VWH_Location__c == '待报废') {
                    soqlAsset += 'AND toAbandon_amount__c > 0 ';
                } else {
                    soqlAsset += 'AND VWH_Location__c = \'' + String.escapeSingleQuotes(id_dummy.VWH_Location__c) + '\' ';
                }
            }  // 虚拟货架号
            if (assetStatus != NONE) {
                if (assetStatus == '未盘点') soqlAsset += 'AND Inventory_Time__c = null ';
                if (assetStatus == '已盘点') soqlAsset += 'AND Inventory_Time__c <> null ';
            }  // 备品状态

            if (internal_Asset_Flg != NONE && String.isNotBlank(internal_Asset_Flg)) {
                soqlAsset += ' AND internal_Asset_Flg__c = ' + internal_Asset_Flg;
            }

            if (inventory_Deviation != NONE && String.isNotBlank(inventory_Deviation)) {
                soqlAsset += ' AND Inventory_Time__c != null AND Inventory_Deviation__c ' + inventory_Deviation;
            }

            //if (!String.isBlank(assetQuery.EquipmentSet_Managment_Code__c)) {
            //    soqlAsset += 'AND Asset__r.EquipmentSet_Managment_Code__c = \'' + assetQuery.EquipmentSet_Managment_Code__c + '\' ';
            //}  // 备品管理编码
            //if (!String.isBlank(assetQuery.Internal_Asset_number__c)) {
            //    soqlAsset += 'AND Asset__r.Internal_Asset_number__c = \'' + assetQuery.Internal_Asset_number__c + '\' ';
            //}  // 固定资产编号
            //if (!String.isBlank(assetQuery.SerialNumber)) {
            //    soqlAsset += 'AND Asset__r.SerialNumber = \'' + assetQuery.SerialNumber + '\' ';
            //}  // 机身号 シリアル番号
            //if (financeBranchNo != NONE) {
            //    soqlAsset += 'AND Asset__r.Finance_of_Branch__c = \'' + financeBranchNo + '\' ';
            //}  // 财务所属分公司
            //if (bodyOrAccessory != NONE) {
            //    if (bodyOrAccessory == '主体') {
            //        soqlAsset += 'AND Asset__r.Loaner_accsessary__c = false ';
            //    } else {
            //        soqlAsset += 'AND Asset__r.Loaner_accsessary__c = true ';
            //    }
            //}  // 主体/附属品
            //if (!String.isBlank(assetQuery.Product_category__c)) {
            //    soqlAsset += 'AND Asset__r.Product_category__c = \'' + assetQuery.Product_category__c + '\' ';
            //}  // 产品分类
            //if (!String.isBlank(assetQuery.Equipment_Type__c)) {
            //    soqlAsset += 'AND Asset__r.Equipment_Type__c = \'' + assetQuery.Equipment_Type__c + '\' ';
            //}  // 备品分类
            //if (!String.isBlank(assetQuery.Manage_type__c)) {
            //    soqlAsset += 'AND Asset__r.Manage_type__c = \'' + assetQuery.Manage_type__c + '\' ';
            //}  // 管理种类
            if (!String.isBlank(salesdepartment) && salesdepartment != NONE) {
                soqlAsset += ' AND Asset__r.Salesdepartment__c = \'' + String.escapeSingleQuotes(salesdepartment) + '\' ';
            }  // 所在地区 本部 Saless_Department__c
            if (!String.isBlank(salesProvince) && salesProvince != NONE) {
                soqlAsset += ' AND Asset__r.SalesProvince__c = \'' + String.escapeSingleQuotes(salesProvince) + '\' ';
            }  // 所在地区 省 Sales_Province__c
            if (consumable_Guaranteen_end != null) {
                Date tempDate = consumable_Guaranteen_end;
                //System.debug('====:tempDate' + tempDate);
                soqlAsset += ' AND Asset__r.Consumable_Guaranteen_end__c = :tempDate ';
            }  // 消耗品有效期至 Consumable_Guaranteen_End__c
            if (isConsum){
                soqlAsset += ' ORDER BY Asset__r.Fixture_Model_No_F__c nulls last, Asset__r.SerialNumber nulls last, Fixture_Model_No__c, SerialNumber__c limit 1001';
            }
            else{
                soqlAsset += ' ORDER BY Main_Asset__r.Fixture_Model_No_F__c nulls last, Main_Asset__r.SerialNumber nulls last, OneToOne_Accsessary__c, Fixture_Model_No__c, SerialNumber__c limit 1001';
            }
            system.debug('--盘点查询sql--'+soqlAsset);

            if(isConsum) {
                consumInventoryDetailList = Database.query(soqlAsset);
                if (consumInventoryDetailList.size() > 1000) {
                    consumInventoryDetailList.remove(1000);
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '备品数量超过1000条，请按货架号盘点或增加检索条件。'));
                }
                for (Consum_Inventory_Detail__c idl : consumInventoryDetailList) {
                    // 冻结的数据不可扫码
                    //if (!idl.OneToOne_Accsessary__c && idl.Asset_Status__c != '冻结') inventoryModelNo.add(idl.Fixture_Model_No__c);
                    oldCountMap.put(idl.Id, idl.Inventory_Count__c);
                    //add by rentx 20210901 start
                    allHCCodelist.add(idl.HCCodes__c);
                    //add by rentx 20210901 end
                }
                List<AggregateResult> consumAssetList = [
                        Select Internal_Asset_Flg__c fix, Asset_Status__c status, sum(toAbandon_amount__c) abAmount, sum(Amount__c) amount, sum(Inventory_Count__c) acAmount
                        From Consum_Inventory_Detail__c
                        Where Inventory_Header__c = : ih.Id
                        and Asset_Status__c != '已消耗明细'
                        group by Internal_Asset_Flg__c, Asset_Status__c];
                consumAssetMap = getInitData(consumAssetList, 'consum');
            }
            else{
                inventoryDetailList = Database.query(soqlAsset);
                system.debug('--在这里--'+inventoryDetailList.size());
                if (inventoryDetailList.size() > 1000) {
                    inventoryDetailList.remove(1000);
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '备品数量超过1000条，请按货架号盘点或增加检索条件。'));
                }
                for (Inventory_Detail__c idl : inventoryDetailList) {
                    // 冻结的数据不可扫码
                    //if (!idl.OneToOne_Accsessary__c && idl.Asset_Status__c != '冻结') inventoryModelNo.add(idl.Fixture_Model_No__c);
                    oldCountMap.put(idl.Id, idl.Inventory_Count__c);
                }

                List<AggregateResult> fixAssetList = [
                        Select Internal_Asset_Flg__c fix, Asset_Status__c status, sum(toAbandon_amount__c) abAmount, sum(Amount__c) amount, sum(Inventory_Count__c) acAmount
                        From Inventory_Detail__c //20210525 you 1650
                        Where Inventory_Header__c = :ih.Id AND Asset_Status__c <> '丢失借出明细' AND Asset_Status__c <> '丢失调拨明细'
                        group by Internal_Asset_Flg__c, Asset_Status__c];
                unfixAssetMap = getInitData(fixAssetList, 'unfix');
                fixAssetMap = getInitData(fixAssetList, 'fix');
            }
        }
        sumRateMap = getRateMap(unfixAssetMap.get('allsum')+fixAssetMap.get('allsum')+consumAssetMap.get('allsum')
        , unfixAssetMap.get('dsum')+fixAssetMap.get('dsum')+consumAssetMap.get('dsum')
        , unfixAssetMap.get('acsum')+fixAssetMap.get('acsum')+consumAssetMap.get('acsum'));
        //System.assertEquals('qyj',''+sumRateMap);



        List<Inventory_User_Permission__mdt> usrList = [select InventoryUser__c from Inventory_User_Permission__mdt where Label = :bieCunFangDi];
        Id[] usrArray = usrList[0].InventoryUser__c.split(',');
        inventoryUserList = [select id, name from user where id in :usrArray];

    }

    /**
     * 获取初始化时页面显示的数据
     * @param arList 查询盘点明细表后得到的符合地区与盘点状态的List
     * @param category 类型'fix' 'unfix' 'consum'
     * @return Map<String, Integer> 排列后的盘点明细
     */
    private Map<String, Integer> getInitData(List<AggregateResult> arList, String category) {
        Map<String, Integer> assetMap = new Map<String, Integer>{'all' => 0,
                                                                 'stock' => 0,
                                                                 'acAmount' => 0,
                                                                 'abandon' => 0,
                                                                 'inventory' => 0,
                                                                 'repair' => 0,
                                                                 'lend' => 0,
                                                                 'transfer' => 0,// 20210520 you 1650
                                                                 'lost' => 0,
                                                                 'percent' => 0,
                                                                 'percent2' => 0,
                                                                 'panying' => 0,
                                                                 'pankui' => 0,
                                                                 'allsum' => 0,
                                                                 'dsum' => 0,
                                                                 'acsum' => 0
                                                                };
        //for (String yy : this.yAxis) {
        //    for (String xx : this.xAxis) {
        //        // 维修、出借中的不能实盘,也算不了亏盈,所以设-1,加页面判断不显示
        //        if ((yy != '应盘') && (xx == '维修中' || xx == '出借中' || xx == '遗失')) {
        //            assetMap.put(xx + yy, -1);
        //        } else {
        //            assetMap.put(xx + yy, 0);
        //        }
        //    }
        //}
        Integer amount = 0, acAmount = 0, arAmount = 0, arAcAmount = 0, arAbAmount = 0;
        Boolean fixed = (category == 'fix');
        system.debug('=category=='+category+'==fixed=='+fixed);
        if (arList.size() > 0) {
            for (AggregateResult ar: arList) {
                system.debug('盘点明细表中是否是固定资产'+Boolean.valueOf(ar.get('fix')));
                boolean aa=Boolean.valueOf(ar.get('fix')) != fixed ;
                system.debug('总==='+aa+'==');  
                if (Boolean.valueOf(ar.get('fix')) != fixed) continue;
                arAmount = ar.get('amount') == null ? 0 : Integer.valueOf(ar.get('amount'));                       // 应盘
                arAbAmount = ar.get('abAmount') == null ? 0 : Integer.valueOf(ar.get('abAmount'));                       // 丢失
                arAcAmount = ar.get('acAmount') == null ? 0 : Integer.valueOf(ar.get('acAmount'));  // 实盘
                system.debug('是否进来1111=='+aa+'');                 
                if (ar.get('status') == '在库' || ar.get('status') == '冻结') {
                    assetMap.put('stock', assetMap.get('stock') + arAmount);              // 在库(包含待报废)应盘
                    assetMap.put('abandon', assetMap.get('abandon') + arAbAmount);
                    assetMap.put('inventory', assetMap.get('inventory') + arAcAmount);            // 在库(包含待报废)实盘
                } else if (ar.get('status') == '维修中') {
                    assetMap.put('repair', arAmount);              // 维修中应盘
                } else if (ar.get('status') == '出借中') {
                    assetMap.put('lend', arAmount);              // 出借中应盘
                } else if (ar.get('status') == '丢失') {
                    assetMap.put('lost', arAmount);              // 遗失应盘
                } else if (ar.get('status') == '已消耗') {
                    assetMap.put('lost', arAmount);              // 已消耗应盘
                }else if (ar.get('status') == '调拨中') {// 20210520 you 1650
                    assetMap.put('transfer', arAmount);              // 调拨中应盘
                }
                amount += arAmount;
            }
            assetMap.put('all', amount);                        // 保有数应盘

            List<AggregateResult> deviationCount;
            List<AggregateResult> allCount;
            List<AggregateResult> doneCount;
            if(category == 'consum'){
                system.debug('是否进来2=='+category); 
                deviationCount = [
                        Select count(Id) cnt, sum(Inventory_Deviation__c) sum
                        From Consum_Inventory_Detail__c
                        Where Inventory_Header__c = :consumInventoryHeader.Id and Inventory_Time__c <> null and Internal_Asset_Flg__c = :fixed and Asset_Status__c in ('在库','冻结') and Inventory_Deviation__c >= 0];
                Integer deviationcnt = Integer.valueOf(deviationCount[0].get('cnt'));
                Integer deviationsum = deviationcnt > 0 ? Integer.valueOf(deviationCount[0].get('sum')) : 0;
                assetMap.put('panying', deviationsum);

                deviationCount = [
                        Select count(Id) cnt, sum(Inventory_Deviation__c) sum
                        From Consum_Inventory_Detail__c
                        Where Inventory_Header__c = :consumInventoryHeader.Id and Inventory_Time__c <> null and Internal_Asset_Flg__c = :fixed and Asset_Status__c in ('在库','冻结') and Inventory_Deviation__c < 0];
                deviationcnt = Integer.valueOf(deviationCount[0].get('cnt'));
                deviationsum = deviationcnt > 0 ? Integer.valueOf(deviationCount[0].get('sum')) : 0;
                assetMap.put('pankui', 0 - deviationsum);

                allCount = [
                        Select count(Id) cnt, sum(Amount__c) sum
                        From Consum_Inventory_Detail__c
                        Where Inventory_Header__c = :consumInventoryHeader.Id and Internal_Asset_Flg__c = :fixed and Asset_Status__c in ('在库','冻结') and Amount__c > 0];
                doneCount = [
                        Select count(Id) cnt, sum(Amount__c) sum, sum(Inventory_Count__c) acAmount
                        From Consum_Inventory_Detail__c
                        Where Inventory_Header__c = :consumInventoryHeader.Id and Inventory_Time__c <> null and Internal_Asset_Flg__c = :fixed and Asset_Status__c in ('在库','冻结') and Amount__c > 0];
            }
            else {
                system.debug('是否进来3=='+category+''); 
                deviationCount = [
                        Select count(Id) cnt, sum(Inventory_Deviation__c) sum
                        From Inventory_Detail__c
                        Where Inventory_Header__c = :inventoryHeader.Id and Inventory_Time__c <> null and Internal_Asset_Flg__c = :fixed and Asset_Status__c in ('在库','冻结') and Inventory_Deviation__c >= 0];
                Integer deviationcnt = Integer.valueOf(deviationCount[0].get('cnt'));
                Integer deviationsum = deviationcnt > 0 ? Integer.valueOf(deviationCount[0].get('sum')) : 0;
                assetMap.put('panying', deviationsum);

                deviationCount = [
                        Select count(Id) cnt, sum(Inventory_Deviation__c) sum
                        From Inventory_Detail__c
                        Where Inventory_Header__c = :inventoryHeader.Id and Inventory_Time__c <> null and Internal_Asset_Flg__c = :fixed and Asset_Status__c in ('在库','冻结') and Inventory_Deviation__c < 0];
                deviationcnt = Integer.valueOf(deviationCount[0].get('cnt'));
                deviationsum = deviationcnt > 0 ? Integer.valueOf(deviationCount[0].get('sum')) : 0;
                assetMap.put('pankui', 0 - deviationsum);

                allCount = [
                        Select count(Id) cnt, sum(Amount__c) sum
                        From Inventory_Detail__c
                        Where Inventory_Header__c = :inventoryHeader.Id and Internal_Asset_Flg__c = :fixed and Asset_Status__c in ('在库','冻结') and Amount__c > 0];
                doneCount = [
                        Select count(Id) cnt, sum(Amount__c) sum, sum(Inventory_Count__c) acAmount
                        From Inventory_Detail__c
                        Where Inventory_Header__c = :inventoryHeader.Id and Inventory_Time__c <> null and Internal_Asset_Flg__c = :fixed and Asset_Status__c in ('在库','冻结') and Amount__c > 0];
            }

            //Integer allcnt = Integer.valueOf(allCount[0].get('cnt'));
            //Integer dcnt = Integer.valueOf(doneCount[0].get('cnt'));
            Integer allsum = allCount[0].get('sum') != null ? Integer.valueOf(allCount[0].get('sum')) : 0;
            Integer dsum = doneCount[0].get('sum') != null ? Integer.valueOf(doneCount[0].get('sum')) : 0;
            Integer acsum = doneCount[0].get('acAmount') != null ? Integer.valueOf(doneCount[0].get('acAmount')) : 0;
            if (allsum > 0) {
                Map<String, Integer> rateMap = getRateMap(allsum,dsum,acsum);
                assetMap.put('percent', rateMap.get('processRate'));         // 进展率
                assetMap.put('percent2', rateMap.get('inventoryRate'));      // 实盘率

                assetMap.put('allsum', allsum);             // 应盘数量(合计进展率&合计实盘率用)
                assetMap.put('dsum', dsum);                 // 盘点过的数量(合计进展率用)
                assetMap.put('acsum', acsum);               // 实盘数量(合计实盘率用)
            }
        }

        return assetMap;
    }

    public List<SelectOption> getInventory_DeviationOps() {
        List<SelectOption> pickListValuesList= new List<SelectOption>();
        pickListValuesList.add(new SelectOption(NONE, NONE));
        pickListValuesList.add(new SelectOption('> 0', '盘盈'));
        pickListValuesList.add(new SelectOption('< 0', '盘亏'));
        return pickListValuesList;
    }

    public List<SelectOption> getInternal_Asset_FlgOps() {
        List<SelectOption> pickListValuesList= new List<SelectOption>();
        pickListValuesList.add(new SelectOption(NONE, NONE));
        pickListValuesList.add(new SelectOption('True', '是'));
        pickListValuesList.add(new SelectOption('False', '否'));
        return pickListValuesList;
    }

    public List<SelectOption> getPlickList(String objApi, String fieldApi) {
        Schema.DescribeFieldResult fieldResult = Schema.getGlobalDescribe().get(objApi).getDescribe().fields.getMap().get(fieldApi).getDescribe();
        List<SelectOption> pickListValuesList= new List<SelectOption>();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        pickListValuesList.add(new SelectOption('', NONE));
        for( Schema.PicklistEntry pickListVal : ple){
            pickListValuesList.add(new SelectOption(pickListVal.getValue(), pickListVal.getLabel()));
        }
        return pickListValuesList;
    }

    /**
     * 获取进展率&实盘率
     * @param allsum 应盘数量(进展率&实盘率用)
     * @param dsum   盘点过的数量(进展率用)
     * @param acsum  实盘数量(实盘率用)
     */
    private Map<String, Integer> getRateMap(Integer allsum, Integer dsum, Integer acsum) {
        Map<String, Integer> rateMap = new Map<String, Integer>{'processRate' => 0,
                                                                'inventoryRate' => 0};
        if (allsum != 0) {
            Decimal sumDeci = Decimal.valueOf(allsum);
            Decimal p1 = dsum*100/sumDeci;
            Decimal p2 = acsum*100/sumDeci;
            Integer processRate = (Integer) p1.setScale(0, RoundingMode.HALF_UP);   // 进展率
            Integer inventoryRate = (Integer) p2.setScale(0, RoundingMode.HALF_UP); // 实盘率
            rateMap.put('processRate', processRate);
            rateMap.put('inventoryRate', inventoryRate);
        }
        return rateMap;
    }
    @TestVisible private static void test() {
        Integer i = 0;
        i++;
        i++;
        i++;//可以多写点
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
           i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
           i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
      }
}