//TestClass: RentalFixtureManage5Test, RentalFixtureManage2Test
public with sharing class EquipmentRentalCancelController {
    // 备品申请书
    public Rental_Apply__c rentalApply { get; set; }
    // 明细行项目
    public List<LineInfo> lineInfoList { get; set; }
    //备品申请书ID
    public String rentalApplyId { get; private set; }
    public Boolean hasError { get; private set; }
    public Boolean saveBtn { get; private set; }
    //现有备品数量（基于备品一览数量）
    public Integer EquipmentSetCnt{get;set;}
    public EquipmentRentalCancelController() {
        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
        rentalApplyId = ApexPages.currentPage().getParameters().get('raid');
    }

    // 画面初始化
    public PageReference init() {
        saveBtn = false;
        hasError = false;
        rentalApply = new Rental_Apply__c();
        lineInfoList = new List<LineInfo>();

        if (rentalApplyId != null && rentalApplyId.length() > 0) {
            // 备品借出申请取得
            List<Rental_Apply__c> raList = [
                select Id, Status__c, RA_Status__c
                  from Rental_Apply__c
                 where Id = :rentalApplyId];

            if (raList.size() > 0) {
                rentalApply = raList[0];
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '备品申请书不存在，请确认。'));
                saveBtn = true;
                return null;
            }
        } else {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '备品申请书不存在，请确认。'));
            saveBtn = true;
            return null;
        }

        // 备品借出备品set一览取得 
        List<Rental_Apply_Equipment_Set__c> raesList = [
            select id, Name, Fixture_Set__c, Fixture_Set__r.Name, Fixture_Set__r.Loaner_code__c, RAES_Status__c, Rental_Start_Date__c, Final_reply_day__c, Yi_StockDown__c,
                   StockDown_time__c, Shippment_loaner_time2__c, Cancel_Select__c, Cancel_Reason__c, Cancel_Mem__c, Loaner_cancel_Remarks__c, Fixture_Set__r.Loaner_name__c,
                   First_RAESD__r.Asset__c,Loaner_cancel_reason__c //20210708 SFDC-C448KZ you start
              from Rental_Apply_Equipment_Set__c
             where Rental_Apply__c = :rentalApply.Id
               and Cancel_Select__c = false
               and Yi_loaner_arranged__c = 0];

        if (raesList.size() == 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '备品申请书未分配明细，不能取消分配。'));
            saveBtn = true;
            return null;
        }else{
            EquipmentSetCnt = raesList.size();
        }

        // 明细行做成
        for (Rental_Apply_Equipment_Set__c raes : raesList) {
            LineInfo lineInfo = new LineInfo(raes);
            lineInfoList.add(lineInfo);
        }

        return null;
    }

    // 保存按钮
    // https://sohobb.backlog.jp/view/OLY_OCM-152#comment-20041467
    // TODO OLY_OCM-206 select from 一対一Link, 把 分配数 清 0
    public PageReference saveBtn() {
        List<Rental_Apply_Equipment_Set__c> delList = new List<Rental_Apply_Equipment_Set__c>();
        List<Rental_Apply_Equipment_Set__c> updList = new List<Rental_Apply_Equipment_Set__c>();
        Set<Id> esIdSet = new Set<Id>();

        // 明细行check
        Integer cntSelect = 0;
        hasError = false;
        for (LineInfo line : lineInfoList) {
            if (line.isSelect == true) {
                // 入力規則を利用した
                //String reason = line.raes.Cancel_Reason__c;
                //if (line.status == 'canCancel' && (reason == null || reason.length() == 0)) {
                //    line.raes.Cancel_Reason__c.addError('必须输入取消理由。');
                //    hasError = true;
                //}
                //20210708 SFDC-C448KZ you start
                if (String.isBlank(line.raes.Cancel_Reason__c)) {
                      line.raes.Cancel_Reason__c.addError('请输入取消理由');
                      hasError = true;
                  }
                  if (String.isBlank(line.raes.Loaner_cancel_reason__c)) {
                      line.raes.Loaner_cancel_reason__c.addError('请输入一览取消理由');
                      hasError = true;
                  }

                  if (String.isNotBlank(line.raes.Loaner_cancel_reason__c) && line.raes.Loaner_cancel_reason__c=='其他' && String.isBlank(line.raes.Loaner_cancel_Remarks__c)) {
                     line.raes.Loaner_cancel_Remarks__c.addError('请输入取消理由备注');
                      hasError = true;
                  }
                //20210708 SFDC-C448KZ you end
                cntSelect += 1;
            }
        }
        if (cntSelect == 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '未选择取消分配的明细。'));
            hasError = true;
        }
        if (hasError == true) {
            system.debug('=====hasError');
            return null;
        }

        Set<Id> raesdIdSet = new Set<Id>();

        // 保存逻辑
        for (LineInfo line : lineInfoList) {
            //if (line.isSelect == true && line.status == 'canCancel') {
            //    Rental_Apply_Equipment_Set__c upd = new Rental_Apply_Equipment_Set__c(Id = line.raes.Id);
            //    // delList.add(del);
            //    // esIdSet.add(line.raes.Fixture_Set__c);
            //    upd.Cancel_Select__c = true;
            //    upd.Cancel_Date__c = Date.today();
            //    upd.Cancel_Reason__c = line.raes.Cancel_Reason__c;
            //    upd.Loaner_cancel_Remarks__c = line.raes.Loaner_cancel_Remarks__c;
            //    updList.add(upd);
            //}
            //if (line.isSelect == true && line.status == 'OnStock_Pre_Inspection') {
            //    Rental_Apply_Equipment_Set__c upd = new Rental_Apply_Equipment_Set__c(Id = line.raes.Id);
            //    //upd.OnStock_Pre_Inspection__c = true;
            //    upd.Cancel_Select__c = true;
            //    upd.Cancel_Date__c = Date.today();
            //    upd.Cancel_Reason__c = line.raes.Cancel_Reason__c;
            //    upd.Loaner_cancel_Remarks__c = line.raes.Loaner_cancel_Remarks__c;
            //    updList.add(upd);
            //    //esIdSet.add(line.raes.Fixture_Set__c);
            //}
            if (line.isSelect == true) {
                Rental_Apply_Equipment_Set__c upd = new Rental_Apply_Equipment_Set__c();
                upd = line.raes;
                upd.Cancel_Select__c = true;
                upd.Cancel_Date__c = Date.today();
                upd.Cancel_Time__c = MainFixtureSelectController.getCurrentTime();
                upd.Cancel_Reason__c = line.raes.Cancel_Reason__c;
                //20210708 SFDC-C448KZ you start
                upd.Loaner_cancel_reason__c = line.raes.Loaner_cancel_reason__c;
                upd.Loaner_cancel_Remarks__c = line.raes.Loaner_cancel_Remarks__c==null ? line.raes.Loaner_cancel_reason__c : line.raes.Loaner_cancel_Remarks__c;
                //20210708 SFDC-C448KZ you end
                if (String.isNotBlank(upd.First_RAESD__r.Asset__c)) {
                    raesdIdSet.add(upd.First_RAESD__r.Asset__c);
                }
                updList.add(upd);
            }
        }

        // 保存
        Savepoint sp = Database.setSavepoint();
        try {
            // if  (   delList.size()  >   0   )   delete  delList;
            if (!raesdIdSet.isEmpty()) {
                List<Fixture_OneToOne_Link__c> fotos = [Select Id From Fixture_OneToOne_Link__c
                        Where Main_Asset__c =: raesdIdSet
                        for update];
                if (!fotos.isEmpty()) {
                    for (Fixture_OneToOne_Link__c foto : fotos) {
                        foto.Select_Accessory_Asset_Cnt__c = 0;
                    }
                    FixtureUtil.withoutUpdate(fotos);
                }
            }
            if  (   updList.size()  >   0   ) {
                Set<Id> assetIdSet = new Set<Id>();
                for (Rental_Apply_Equipment_Set_Detail__c raesd : [SELECT Id, Asset__c
                                                                     FROM Rental_Apply_Equipment_Set_Detail__c
                                                                    WHERE Rental_Apply_Equipment_Set__c = :updList FOR UPDATE]
                ) {
                    if (String.isNotBlank(raesd.Asset__c)) {
                        assetIdSet.add(raesd.Asset__c);
                    }
                }
                if (assetIdSet.size() > 0) {
                    List<Asset> assetList = [SELECT Id
                             FROM Asset
                            WHERE Id = :assetIdSet FOR UPDATE];
                }
                FixtureUtil.withoutUpdate(updList);
            }
            // system.debug(EquipmentSetCnt+'2223333'+updList.size()   );
            // if  ((  updList.size()  ==  EquipmentSetCnt ||  
            //         delList.size()  ==  EquipmentSetCnt ||
            //         delList.size()  +   updList.size()  ==  EquipmentSetCnt )
            //         &&  EquipmentSetCnt !=  0
            //         &&  (   rentalApply.Status__c =='引当完了'  
            //             ||  rentalApply.Status__c =='出库指示完了'      )){
            //     Rental_Apply__c RaUpdate    =   new Rental_Apply__c();
            //     RaUpdate.id =   rentalApplyId;
            //     RaUpdate.Status__c  =   '已批准';
            //     update  RaUpdate;
            // }
//bp2            ControllerUtil.setEquipmentSetProvisionFlg(esIdSet);
        }   catch (Exception ex)    {
            system.debug('=====' + ex.getMessage());
            hasError = true;
            ApexPages.addMessages(ex);
            Database.rollback(sp);
            return null;
        }
        return null;
    }

    @TestVisible
    class LineInfo {
        // 选择
        public boolean isSelect { get; set; }
        // 借出备品set一览
        public Rental_Apply_Equipment_Set__c raes { get; set; }
        // 状态：可以删除、可以取消、不能取消
        //public String status { get; private set; }
        public String esName { get; private set; }
        public String loanerCode { get; private set; }
        public LineInfo(Rental_Apply_Equipment_Set__c r) {
            isSelect = false;
            raes = r;
            loanerCode = r.Fixture_Set__r.Loaner_name__c;
            ////cancel
            //if (r.Yi_StockDown__c > 0) {
            //    status = 'canCancel';
            ////下架以后改成待上架的checkbox
            ////cancel
            //} else {
            //    status = 'OnStock_Pre_Inspection';
            //}
            esName = r.Fixture_Set__r.Name;
        }
    }

}