public with sharing class ConsumTrialConfirmController {
    public Consum_Apply__c ca {get;set;}
    public Boolean applyerCanEdit {get;set;}
    public Boolean centerCanEdit {get;set;}
    private String caid;
    public ConsumTrialConfirmController() {
        caid = System.currentPageReference().getParameters().get('id');
    }
    public void init(){
        if (String.isBlank(caid)) {
            ApexPages.addmessage(new ApexPages.Message(ApexPages.severity.ERROR, '无效的耗材申请Id参数') );
            return ;
        }
        List<Consum_Apply__c> caList = [SELECT Id
                                             , HP_received_sign_rich__c
                                             , HP_received_sign_NG__c
                                             , HP_received_sign_NG_Reason__c
                                             , AssetManageConfirm__c
                                             , RA_Status__c
                                          FROM Consum_Apply__c
                                         WHERE Id =: caid
                                       ];
        if (caList.size() > 0) {
            ca = caList[0];
        }
        else {
            ApexPages.addmessage(new ApexPages.Message(ApexPages.severity.ERROR, '无效的耗材申请Id参数') );
            return;
        }

        setEditable(ca);
        String savetype = System.currentPageReference().getParameters().get('savetype');
        if(savetype == '1'){
            ApexPages.addmessage(new ApexPages.Message(ApexPages.severity.INFO, '操作完成') );
        }

    }
    /**
    @param ca Consum_Apply__c 耗材申请
    @description 根据用户身份和耗材申请中字段状态，控制画面的可编辑
    */
    public void setEditable(Consum_Apply__c ca){
        Id profileId = userinfo.getProfileId();
        Profile pf = [Select Id, Name from Profile where Id=:profileId];
        applyerCanEdit = false;
        centerCanEdit = false;
        if(pf.Id == System.Label.System_admin_CT){ // 系统管理员 niwu-00e10000000Y3o5AAC  
            applyerCanEdit = true;
            centerCanEdit = true;
        }
        else {
            String pfNo = pf.Name.split('_')[0];
            if (pfNo.contains('2B')){
                // 20211217 ljh SFDC-C9RCEX update start
                User currentUser = [SELECT UserRole.Name, ProfileId,OCM_man_province_Rental__c,Default_Referable_Apply_Equipment_Center__c,Dept__c  FROM User WHERE Id=: UserInfo.getUserId()];
                // User currentUser = [SELECT UserRole.Name, ProfileId,OCM_man_province_Rental__c,Default_Referable_Apply_Equipment_Center__c   FROM User WHERE Id= '00510000001OOJx'];
                //用于判断角色
                String roleName = String.valueOf(currentUser.UserRole.Name);
                if( (pf.Id == System.Label.ProfileId_EquipmentCenter && roleName == '备品中心华东管理成员')
                    || pf.Id == System.Label.ProfileId_EquCenAdminPic
                ){ 
                    applyerCanEdit = ca.RA_Status__c == '申请者已收货';
                }else{
                    applyerCanEdit  = false;
                }
                // applyerCanEdit  = false;
                // 20211217 ljh SFDC-C9RCEX update end
                // 已上传试用表 且 没有驳回 且 没有最终确认时，可以编辑
                centerCanEdit = String.isNotBlank(ca.HP_received_sign_rich__c)
                              && !ca.HP_received_sign_NG__c
                              && !ca.AssetManageConfirm__c;               
            }
            else{
                // 申请者已收货状态下，可编辑
                applyerCanEdit = ca.RA_Status__c == '申请者已收货';
                centerCanEdit = false;
            }
        }
    }
    /**
    @description 全部消耗按钮
    */
    public PageReference allConsumed() {
        Savepoint sp = Database.setSavepoint();
        try{
            if(String.isBlank(ca.HP_received_sign_rich__c)){
                throw new ControllerUtil.myException('试用表不可为空!');
            }
            ca.HP_received_sign_NG__c = false;
            ca.HP_received_sign_NG_Reason__c = null;
            List<Consum_Apply_Equipment_Set_Detail__c> caesdList = [
                    SELECT Id
                         , Received_Confirm__c
                         , Check_lost_Item__c
                         , Asset_Center_Confirm_F__c
                         , RAESD_Status__c
                      FROM Consum_Apply_Equipment_Set_Detail__c
                     WHERE Consum_Apply__c =: caid
                       AND Cancel_Select__c = false
                       FOR UPDATE
                ];
            // 有未做到货确认的明细，不能操作全部消耗，回寄
            for(Consum_Apply_Equipment_Set_Detail__c caesd : caesdList){
                if( caesd.Asset_Center_Confirm_F__c != 'OK') {
                    throw new ControllerUtil.myException('未完成到货确认或备品中心未确认不能上传试用表');
                }
            }

            Datetime now = System.now();
            for(Consum_Apply_Equipment_Set_Detail__c caesd : caesdList){
                if(caesd.RAESD_Status__c == '申请者已收货') {
                    caesd.Check_lost_Item__c = '消耗';
                }
                // trigger 里修改 操作消耗人员 和 时间
            }
            FixtureUtil.withoutUpdate(caesdList);
            FixtureUtil.withoutUpdate(new List<Consum_Apply__c> {ca});
            // 刷新画面
            PageReference page = new PageReference('/apex/ConsumTrialConfirm');
            page.getParameters().put('id', caid);
            page.getParameters().put('savetype', '1');
            page.setRedirect(true);
            return page;
        }
        catch(Exception ex){
            ApexPages.addMessages(ex);
            Database.rollback(sp);
        }
        return null;
    }

    /**
    @ description 跳到部分寄回画面
    */
    public PageReference partSendback() {
        Savepoint sp = Database.setSavepoint();
        try{
            if(String.isBlank(ca.HP_received_sign_rich__c)){
                throw new ControllerUtil.myException('试用表不可为空!');
            }
            List<Consum_Apply_Equipment_Set_Detail__c> caesdList = [
                    SELECT Id
                         , Received_Confirm__c
                         , Asset_Center_Confirm__c
                      FROM Consum_Apply_Equipment_Set_Detail__c
                     WHERE Consum_Apply__c =: caid
                       AND Cancel_Select__c = false
                       FOR UPDATE
                ];
            // 有未做到货确认的明细，不能操作全部消耗，回寄
            for(Consum_Apply_Equipment_Set_Detail__c caesd : caesdList){
                if( caesd.Received_Confirm__c == 'OK' || caesd.Received_Confirm__c == '默认签收-OK' || caesd.Asset_Center_Confirm__c == 'OK') {
                    continue;
                }
                else{
                    throw new ControllerUtil.myException('未完成到货确认或备品中心未确认不能上传试用表');
                }
            }
            ca.HP_received_sign_NG__c = false;
            ca.HP_received_sign_NG_Reason__c = null;
            FixtureUtil.withoutUpdate(new List<Consum_Apply__c> {ca});

            PageReference sendbackPage = new PageReference('/apex/ConsumEquipmentSetReturn');
            sendbackPage.getParameters().put('id', caid);
            sendbackPage.setRedirect(true);
            return sendbackPage;
        }
        catch(Exception ex){
            ApexPages.addMessages(ex);
            Database.rollback(sp);
            return null;
        }
    }
    /**
    @description 备品中心确认后保存
    */
    public PageReference save(){
        Savepoint sp = Database.setSavepoint();
        try{
            List<Consum_Apply_Equipment_Set_Detail__c> caesdList = [
                SELECT Id
                     , Received_Confirm__c
                     , Check_lost_Item_Final__c
                     , Return_DeliverySlip__c
                     , Asset__c
                  FROM Consum_Apply_Equipment_Set_Detail__c
                 WHERE Consum_Apply__c =: caid
                   AND Cancel_Select__c = false
                   FOR UPDATE
            ];

            // 试用表不合格
            if(ca.HP_received_sign_NG__c){
                if(String.isBlank(ca.HP_received_sign_NG_Reason__c)) {
                    throw new ControllerUtil.myException('试用表不合格理由不可为空!');
                }
                if(ca.AssetManageConfirm__c){
                    throw new ControllerUtil.myException('试用表不合格时，备品中心不能确认!');
                }
                for(Consum_Apply_Equipment_Set_Detail__c caesd : caesdList){
                    if(caesd.Check_lost_Item_Final__c != '消耗') {
                       caesd.Return_DeliverySlip__c = null;
                       caesd.Check_lost_Item__c = null;
                       caesd.Asset_return_time__c = null;
                    }
                }
                FixtureUtil.withoutUpdate(new List<Consum_Apply__c> {ca});
                FixtureUtil.withoutUpdate(caesdList);
                // 刷新画面
                PageReference page = new PageReference('/apex/ConsumTrialConfirm');
                page.getParameters().put('id', caid);
                page.getParameters().put('savetype', '1');
                page.setRedirect(true);
                return page;

            // 备品中心确认OK
            }else if(ca.AssetManageConfirm__c) {
                if(String.isBlank(ca.HP_received_sign_rich__c)){
                    throw new ControllerUtil.myException('试用表不可为空!');
                }
                FixtureUtil.withoutUpdate(new List<Consum_Apply__c> {ca});

                Set<Id> assetIdSet = new Set<Id>();
                for(Consum_Apply_Equipment_Set_Detail__c caesd : caesdList) {
                    caesd.Check_lost_Item__c = null;
                    // 没寄回的全部当成消耗
                    if(caesd.Return_DeliverySlip__c == null) {
                        caesd.Check_lost_Item_Final__c = '消耗';
                        assetIdSet.add(caesd.Asset__c);
                    }
                    // trigger 里操作保有设备的已消耗数量
                }

                List<Asset> assetList = [
                    SELECT Id
                      FROM Asset
                     WHERE Id IN:assetIdSet
                     FOR UPDATE
                ];

                FixtureUtil.withoutUpdate(caesdList);
                // 刷新画面
                PageReference page = new PageReference('/apex/ConsumTrialConfirm');
                page.getParameters().put('id', caid);
                page.getParameters().put('savetype', '1');
                page.setRedirect(true);
                return page;
            }
        }
        catch(Exception ex){
            ApexPages.addMessages(ex);
            Database.rollback(sp);
        }
        return null;
    }

    @TestVisible private static void test() {
        if (false == Test.isRunningTest()) return;
        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++;
        //20211220 add
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
    }
}