public without sharing class LostReportEditController {

    public String lrid {get; set;}
    public PageBean pBean {get; set;}
    public Map<String, String> DESC_RW {get; private set;}
    public Map<String, String> DESC_RW1 {get; private set;}

    private static Set<String> DESC_RWField = new Set<String> {'Asset_day__c',
                                                               'Asset_Value__c'};

    private static Set<String> DESC_RW1Field = new Set<String> {'CC_User1__c',
                                                                'CC_User2__c',
                                                                'CC_User3__c',
                                                                'CC_User4__c',
                                                                'CC_User5__c',
                                                                'CC_Email1__c',
                                                                'CC_Email2__c',
                                                                'Situation_description__c',
                                                                'Confirmation_process__c',
                                                                'Rental_Apply_SplitUser__c',
                                                                'Rental_Apply_SplitUser_Agency__c'
                                                            };

    public LostReportEditController() {
        lrid = System.currentPageReference().getParameters().get('Id');
        if (String.isBlank(lrid)) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '不能明确遗失报告。请确认数据'));
        }
    }

    public LostReportEditController(ApexPages.StandardController controller) {
        lrid = controller.getId();
        if (String.isBlank(lrid)) {
            lrid = System.currentPageReference().getParameters().get('Id');
        }
        if (String.isBlank(lrid)) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '不能明确遗失报告。请确认数据'));
        }
    }

    public void init() {

        List<LostReport__c> lrList = [SELECT Id,
                                             Name,
                                             CC_User1__c,
                                             CC_User2__c,
                                             CC_User3__c,
                                             CC_User4__c,
                                             CC_User5__c,
                                             CC_Email1__c,
                                             CC_Email2__c,
                                             Confirmation_process__c,
                                             Situation_description__c,
                                             Rental_Apply_SplitUser__c,
                                             CreatedDate,
                                             CreatedBy.Name,
                                             //CreatedBy.Department,
                                             CreatedBy.Dept__c,  // User 本部(选项)
                                             Rental_Apply__r.Owner.Name,
                                             Rental_Apply__r.Account__c,
                                             Rental_Apply__r.Bollow_Date__c,
                                             Rental_Apply__r.demo_purpose2__c,
                                             Rental_Apply__r.Demo_purpose_text__c,
                                             Rental_Apply__r.RecordType.Name,//20210428 1653 you
                                             Status_F__c,
                                             TransferApplyOwner__c, //申请人
                                             YunYingBuZhang__c, // 运营部长 20211224 ljh SFDC-C933NJ add
                                             RA_BuchangApprovalManagerSales__c, // 部长 20211224 ljh SFDC-C933NJ add
                                             BuchangManager_approval_time__c, // 部长审批时间 20211214 ljh SFDC-C933NJ add
                                             YunYingBuZhang_approval_time__c, // 运营部长审批时间 20211214 ljh SFDC-C933NJ add
                                             Internal_asset_location_F__c, //备品存放地
                                             TransferApply__r.Bollow_Date__c, //备品中心出库日
                                             TransferApplyDeveloperName__c, //调拨类型
                                             TransferApply__r.TransferReason__c, //调拨理由
                                             // TransferApply__r.From_Location__c,   //备品存放地先取调拨申请的调拨前地区
                                             Rental_Apply__r.Account__r.Name,      //备品借出申请的 借用医院名(科室)  
                                             From_Location__c, //add by rentx 20210518 1635
                                             isBeipin__c,          //add by rentx 20210609
                                             Inventory_Header__c, //add by rentx 20210611
                                             Rental_Apply_SplitUser_Agency__c//20210622 you 1650
                                        FROM LostReport__c
                                       WHERE Id = :lrid];
        if (lrList.size() == 0) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '不能明确遗失报告。请确认数据'));
            return;
        }

        pBean = new PageBean(lrList[0]);
        // 20211216 ljh SFDC-C933NJ add start
        String bz = lrList[0].RA_BuchangApprovalManagerSales__c;
        String yybz = lrList[0].YunYingBuZhang__c;
        if((String.isNotBlank(bz) && bz.substring(0,15) == System.Label.PersonalId && lrList[0].BuchangManager_approval_time__c != null )
            ||(String.isNotBlank(yybz) && yybz.substring(0,15) == System.Label.PersonalId && lrList[0].YunYingBuZhang_approval_time__c != null)){
           pBean.isShowPunish = true; 
        }
        // 20211216 ljh SFDC-C933NJ add end
        Set<String> assetRecordTypeList = new Set<String>();
        List<LostReport_Detail__c> lrdList = [SELECT Id,
                                                     Asset__c,
                                                     Asset__r.Id,
                                                     Fixture_Model_No_F__c,
                                                     SerialNumber__c,
                                                     IsPunishObj__c, // 20211213 ljh SFDC-C933NJ add
                                                     Asset_Value_F__c,
                                                     Asset_Value__c,
                                                     Asset_day_F__c,
                                                     Asset_day__c,
                                                     Internal_Asset_number__c,
                                                     Asset__r.Asset_day__c,
                                                     Asset__r.Asset_Value__c,
                                                     Asset__r.Account.AgentCode_Ext__c,// 20211227 ljh SFDC-C933NJ add
                                                     Asset__r.RecordTypeId
                                                FROM LostReport_Detail__c
                                               WHERE LostReport__c = :lrid
                                                 AND Asset__c != null];
        pBean.setAssetList(lrdList);

        for (LostReport_Detail__c lrd : lrdList) {
            if (!assetRecordTypeList.contains(lrd.Asset__r.RecordTypeId)) {
                assetRecordTypeList.add(lrd.Asset__r.RecordTypeId);
            }
        }

        Map<String, Map<String, String>> lgLayoutMap = SoapApi.getEditLayoutItemRW('LostReport__c', null);
        for (String str : lgLayoutMap.keySet()) {
          DESC_RW1 = lgLayoutMap.get(str);
          break;
        }

        for (String field : DESC_RW1Field) {
            if (!DESC_RW1.containsKey(field)) {
                DESC_RW1.put(field, 'r');
            }
        }

        Map<String, Map<String, String>> lgLayout2Map = SoapApi.getEditLayoutItemRW('LostReport_Detail__c', null);
        for (String str : lgLayoutMap.keySet()) {
          DESC_RW = lgLayout2Map.get(str);
          break;
        }
        // 20211214 ljh SFDC-C933NJ add start
        // 当前登录人等于 古芳利
        String uId = UserInfo.getUserId();
        if(uId.substring(0,15) == System.Label.PersonalId
            && (lrList[0].Status_F__c == '草案中' || lrList[0].Status_F__c == '申请中')
            && lrdList[0].Asset__r.Account.AgentCode_Ext__c != System.Label.Account_Asset_FJZ){
            DESC_RW.put('IsPunishObj__c','wm');  
            // 保存按钮显示
            pBean.bzCanEdit = true;
            pBean.isShowPunish = true;
        }else{
            DESC_RW.put('IsPunishObj__c','r');
        }
        // 20211214 ljh SFDC-C933NJ add end
        for (String field : DESC_RWField) {
            if (!DESC_RW.containsKey(field)) {
                DESC_RW.put(field, 'r');
            }
        }

        String saveMessage = System.currentPageReference().getParameters().get('saveMessage');
        // 保存并提交审批，成功后提醒：已提交审批
        // 保存，成功后提醒：保存完了
        if (String.isNotBlank(saveMessage)) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, saveMessage));
        }   
    }

    public PageReference saveLR() {
        Savepoint sp = Database.setSavepoint();
        String saveMessage = '';
        try {
            String saveType = System.currentPageReference().getParameters().get('saveType');
            if (String.isNotBlank(saveType) && saveType == '1') {
                List<LostReport__c> lrList = [SELECT Id,
                                                     Status__c
                                                FROM LostReport__c
                                               WHERE Id = :pBean.lr.Id];
                if (lrList.size() == 0) {
                    throw new ControllerUtil.myException('遗失报告数据出错,请刷新画面重试');
                }
                LostReport__c lr = lrList[0];
                if (lr.Status__c == '填写完毕'
                        || lr.Status__c == '申请中'
                        || lr.Status__c == '已批准') {
                    throw new ControllerUtil.myException('请确认遗失报告状态，已经提交过的申请，不能重复提交');
                }
                pBean.lr.Status__c = '填写完毕';
            }

            if (pBean.rowList != null && pBean.rowList.size() > 0) {
                List<LostReport_Detail__c> lrdList = new List<LostReport_Detail__c>();
                for (PageRowBean prb : pBean.rowList) {
                    // 20211215 ljh  SFDC-C933NJ add start 
                    if(pBean.bzCanEdit && String.isBlank(prb.lrd.IsPunishObj__c)){
                        throw new ControllerUtil.myException('【是否罚则对象】 必须填写保存后才能审批');
                    }
                    // 20211215 ljh  SFDC-C933NJ add end
                    lrdList.add(prb.lrd);
                }

                if (lrdList.size() > 0) {
                    update lrdList; 
                    // 20211215 ljh  SFDC-C933NJ add start
                    if(pBean.bzCanEdit){
                        pBean.lr.IsFinishPunishObj__c = true;
                    }
                    // 20211215 ljh  SFDC-C933NJ add start
                }
            }
            if (String.isNotBlank(saveType) && saveType == '1') {
                saveMessage = '已提交审批';
            } else {
              saveMessage = '保存完了';
            }
            update pBean.lr;
        }
        catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage()));
            return null;
        }
        //return new PageReference('/' + lrid); 
        // 点击保存按钮后，不要跳转到标准画面，保留在原画面
        PageReference pg = new PageReference('/apex/LostReportEdit');
        pg.getParameters().put('Id', this.lrid);
        pg.getParameters().put('saveMessage', saveMessage);
        pg.setRedirect(true);
        return pg;

    }

    public Class LrdPageBean {
      public String modeNo {get; set;}
      public String serialNo {get; set;}
      public String internalAssetNumber {get; set;}

      public LrdPageBean(LostReport_Detail__c lrd) {
        modeNo = lrd.Fixture_Model_No_F__c;
        serialNo = lrd.SerialNumber__c;
        internalAssetNumber = lrd.Internal_Asset_number__c;
      }
    }

    public Class PageBean {
        public LostReport__c lr {get; set;}
        public Rental_Apply__c ra {get; set;}
        public String bollow_DateStr {get; set;}
        public List<PageRowBean> rowList {get; set;}
        public String lrCreateDate {get; set;}
        public ProcessInfo jingliInfo {get; set;}
        public ProcessInfo buzhangInfo {get; set;}
        public ProcessInfo fuzongjianInfo {get; set;}
        public ProcessInfo zongjianliInfo {get; set;}
        public ProcessInfo fenpeirenInfo {get; set;}
        public ProcessInfo yunyingbuzhangInfo {get; set;}
        public ProcessInfo beipinzhongxinInfo {get; set;}
        // 20210430 1653 you start  
        public ProcessInfo BSCfenpeirenInfo {get; set;}
        public ProcessInfo BSCbeipinzhongxinslckInfo {get; set;}
        // 20210430 1653 you end 
        public Boolean hasApprovedFlag {get; set;}
        public Boolean islock {get; set;}
        public Boolean bzCanEdit {get; set;} // 20211215 ljh SFDC-C933NJ add 
        public Boolean isShowPunish {get; set;} // 20211215 ljh SFDC-C933NJ add 
        //add by rentx 20210605 start
        public ProcessInfo beiPinWindowInfo {get; set;}
        public ProcessInfo managerapprovalInfo {get; set;}
        public ProcessInfo ministerapprovedInfo {get;set;}
        public ProcessInfo approvedbyDeputyDirectorofEastChinaInfo {get; set;}
        public ProcessInfo districtGovernorApprovalInfo {get;set;}
        public ProcessInfo contactpersonapprovalInfo {get;set;}
        public ProcessInfo operationsMinisterInfo {get;set;}
        public ProcessInfo approvalbytheDirectorofSparePartsInfo {get;set;}
        //备品中心提交 的运营部长审批
        public ProcessInfo directorofOperationsApprovalInfo {get; set;}
        //统括总监审批
        public ProcessInfo generalDirectorApprovalInfo {get; set;}
        //add by rentx 20210605 end

        //add by rentx 2021-05-18 start 1635
        public TransferApply__c tr {get;set;}
        public String addressOrAccount {get;set;}  //当当前遗失报告为 调拨申请的遗失报告时 存备品存放地 反之存借用医院名（科室）
        public String applicant {get;set;}          //申请人
        public String mdOrType {get;set;}           //当当前遗失报告为 调拨申请时 存调拨类型 反之存使用目的
        public String cjOrdbReason {get;set;}       //当当前遗失报告为 调拨申请时 存调拨理由 反之存出借理由
        //add by rentx 2021-05-18 end 1635

        public PageBean () {
            rowList = new List<PageRowBean>();
        }

        public PageBean (LostReport__c lr1) {
            if (lr1.Status_F__c != '已批准') {  // 判断条件: 遗失报告的状态是否已批准
                hasApprovedFlag = false;  // 遗失报告批准前，领导处理意见处要显示空
            } else {
                hasApprovedFlag = true;  // 盘点报告批准之后，保存和保存并提交审批的按钮需要隐藏
            }

            lr = lr1;
            islock = System.Approval.isLocked(lr1.Id);
            bzCanEdit = false; // 20211215 ljh SFDC-C933NJ add 
            isShowPunish = false;// 20211216 ljh SFDC-C933NJ add 
            lrCreateDate = lr.CreatedDate.format('yyyy/MM/dd');
            ra = lr.Rental_Apply__r;
            bollow_DateStr = '';
            if (String.isNotBlank(lr.Rental_Apply__c) && lr.Rental_Apply__r.Bollow_Date__c != null) {
                bollow_DateStr = lr.Rental_Apply__r.Bollow_Date__c.format();
            }
            jingliInfo = new ProcessInfo();
            buzhangInfo = new ProcessInfo();
            fuzongjianInfo = new ProcessInfo();
            zongjianliInfo = new ProcessInfo();
            fenpeirenInfo = new ProcessInfo();
            yunyingbuzhangInfo = new ProcessInfo();
            beipinzhongxinInfo = new ProcessInfo();
            // 20210430 1653 you start 
            BSCfenpeirenInfo = new ProcessInfo(); 
            BSCbeipinzhongxinslckInfo = new ProcessInfo();
            // 20210430 1653 you end 

            //add by rentx 20210605 start
            beiPinWindowInfo = new ProcessInfo();
            managerapprovalInfo = new ProcessInfo();
            ministerapprovedInfo = new ProcessInfo();
            approvedbyDeputyDirectorofEastChinaInfo = new ProcessInfo();
            districtGovernorApprovalInfo = new ProcessInfo();
            contactpersonapprovalInfo = new ProcessInfo();
            operationsMinisterInfo = new ProcessInfo();
            approvalbytheDirectorofSparePartsInfo= new ProcessInfo();
            directorofOperationsApprovalInfo = new ProcessInfo();
            generalDirectorApprovalInfo = new ProcessInfo();
            //add by rentx 20210605 end
            rowList = new List<PageRowBean>();

            //add by rentx 2021-05-18 start
            tr = lr.TransferApply__r;
            //借用医院名（科室） 或 备品存放地 (暂时先取调拨申请的调拨前地区)
            addressOrAccount = '';
            if (String.isNotBlank(lr.Rental_Apply__c) && lr.Rental_Apply__r.Account__c != null) {
                addressOrAccount = lr.Rental_Apply__r.Account__r.Name;
            }else{
                // addressOrAccount = tr != null ? tr.From_Location__c : '';
                addressOrAccount = lr1.From_Location__c;
            }
            //申请人
            applicant = '';
            if (String.isNotBlank(lr.Rental_Apply__c) && lr.Rental_Apply__r.Owner.Name != null) {
                applicant = lr.Rental_Apply__r.Owner.Name;
            }else{
                applicant = lr1.TransferApplyOwner__c;
            }
            //使用目的或调拨类型
            mdOrType = '';
            if (String.isNotBlank(lr.Rental_Apply__c) && lr.Rental_Apply__r.demo_purpose2__c != null) {
                mdOrType = lr.Rental_Apply__r.demo_purpose2__c;
            }else{
                mdOrType = lr1.TransferApplyDeveloperName__c;
            }
            //出借或调拨理由
            cjOrdbReason = '';
            if (String.isNotBlank(lr.Rental_Apply__c) && lr.Rental_Apply__r.demo_purpose2__c != null) {
                cjOrdbReason = lr.Rental_Apply__r.Demo_purpose_text__c;
            }else{
                cjOrdbReason = tr != null ? tr.TransferReason__c : '';
            }
            //备品中心出库日
            if ((bollow_DateStr == null || bollow_DateStr == '') && tr != null && tr.Bollow_Date__c != null) {
                bollow_DateStr = tr != null ? tr.Bollow_Date__c.format() : '' ;
            }
            
            //add by rentx 2021-05-18 end


            List<ProcessInstance> plList = [SELECT Id
                                                   ,CompletedDate
                                                   ,LastActorId
                                                   ,ProcessDefinitionId
                                                   ,Status
                                                   ,TargetObjectId,
                                                   (
                                                        SELECT Id,
                                                               ProcessNode.DeveloperName,
                                                               CreatedDate,
                                                               StepStatus,
                                                               OriginalActorId,
                                                               ActorId,
                                                               Actor.Name,
                                                               Comments
                                                          FROM StepsAndWorkitems
                                                          order by CreatedDate desc
                                                    )
                                                FROM
                                                    ProcessInstance
                                                WHERE
                                                    TargetObjectId = :lr.Id
                                                ORDER BY CreatedDate DESC
                                                LIMIT 50];
            if (plList.size() > 0) {
                ProcessInstance pl = plList[0];
                for (Integer i = 0 ; i < pl.StepsAndWorkitems.size(); i ++) {
                    ProcessInstanceHistory plh = pl.StepsAndWorkitems[i];
                    if (plh.StepStatus != 'Approved' && plh.StepStatus != 'Pending') {
                        break;
                    }
                    //add by rentx 20210605 start
                    //备品总窗口审批
                    if (String.isBlank(beiPinWindowInfo.userName)
                            && plh.ProcessNode.DeveloperName == 'Distributorapproval') {
                        beiPinWindowInfo = new ProcessInfo(plh);
                    }
                    //经理审批
                    if (String.isBlank(managerapprovalInfo.userName)
                            && plh.ProcessNode.DeveloperName == 'managerapproval') {
                        managerapprovalInfo = new ProcessInfo(plh);
                    }
                    //部长审批
                    if (String.isBlank(ministerapprovedInfo.userName)
                            && plh.ProcessNode.DeveloperName == 'Ministerapproved') {
                        ministerapprovedInfo = new ProcessInfo(plh);
                    }
                    //副总监审批
                    if (String.isBlank(approvedbyDeputyDirectorofEastChinaInfo.userName )
                          && plh.ProcessNode.DeveloperName == 'approvedbyDeputyDirectorofEastChina') {
                        approvedbyDeputyDirectorofEastChinaInfo = new ProcessInfo(plh);
                    }
                    //总监审批
                    if (String.isBlank(districtGovernorApprovalInfo.userName )
                          && plh.ProcessNode.DeveloperName == 'districtGovernorApproval') {
                        districtGovernorApprovalInfo = new ProcessInfo(plh);
                    }

                    //统括总监审批
                    if (String.isBlank(generalDirectorApprovalInfo.userName)
                          && plh.ProcessNode.DeveloperName == 'generalDirectorApproval') {
                        generalDirectorApprovalInfo = new ProcessInfo(plh);
                    }
                    //联络人审批
                    if (String.isBlank(contactpersonapprovalInfo.userName )
                          && plh.ProcessNode.DeveloperName == 'contactpersonapproval') {
                          contactpersonapprovalInfo = new ProcessInfo(plh);
                    }
                    //运营部长审批
                    if (String.isBlank(operationsMinisterInfo.userName)
                          && plh.ProcessNode.DeveloperName == 'operationsMinister') {
                          operationsMinisterInfo = new ProcessInfo(plh);
                    }
                    //备品中心提交审批 -- 运营部长
                    if (String.isBlank(directorofOperationsApprovalInfo.userName)
                          && plh.ProcessNode.DeveloperName == 'directorofOperationsApproval') {
                          directorofOperationsApprovalInfo = new ProcessInfo(plh);
                    }
                    //备品中心总监审批
                    if (String.isBlank(approvalbytheDirectorofSparePartsInfo.userName)
                        && plh.ProcessNode.DeveloperName == 'approvalbytheDirectorofSpareParts') {
                        approvalbytheDirectorofSparePartsInfo = new ProcessInfo(plh);
                    }
                    //add by rentx 20210605 end

                    if (String.isBlank(jingliInfo.userName)
                            && plh.ProcessNode.DeveloperName == 'Manager_ApprovalProcess') {
                        jingliInfo = new ProcessInfo(plh);
                    }
                    else if (String.isBlank(buzhangInfo.userName)
                            && plh.ProcessNode.DeveloperName == 'Minister_Approval') {
                        buzhangInfo = new ProcessInfo(plh);
                    }
                    else if(String.isBlank(fuzongjianInfo.userName)
                            && plh.ProcessNode.DeveloperName == 'FuZongJian_Approval') {
                        fuzongjianInfo = new ProcessInfo(plh);
                    }
                    else if (String.isBlank(zongjianliInfo.userName)
                            && (plh.ProcessNode.DeveloperName == 'Chief_Approval'
                                    || plh.ProcessNode.DeveloperName == 'LastApproval'
                                )
                            ) {
                        zongjianliInfo = new ProcessInfo(plh);
                    }
                    else if (String.isBlank(fenpeirenInfo.userName)
                            && plh.ProcessNode.DeveloperName == 'Fenpei') {
                        fenpeirenInfo = new ProcessInfo(plh);
                    }
                    else if (String.isBlank(yunyingbuzhangInfo.userName)
                            && plh.ProcessNode.DeveloperName == 'YunYingBuZhang_Approval') {
                        yunyingbuzhangInfo = new ProcessInfo(plh);
                    }
                    else if (String.isBlank(beipinzhongxinInfo.userName)
                            && plh.ProcessNode.DeveloperName == 'CentreApproval') {
                        beipinzhongxinInfo = new ProcessInfo(plh);
                    }
                    // 20210430 1653 you start 
                    else if (String.isBlank(BSCfenpeirenInfo.userName)
                            && plh.ProcessNode.DeveloperName == 'Fenpeiren_Ban') {
                        BSCfenpeirenInfo = new ProcessInfo(plh);
                    }
                    else if (String.isBlank(BSCbeipinzhongxinslckInfo.userName)
                            && plh.ProcessNode.DeveloperName == 'BPZXApprovalProcess') {
                        BSCbeipinzhongxinslckInfo = new ProcessInfo(plh);
                    }
                    // 20210430 1653 you end 
                }
            }
        }

        public void setAssetList(List<LostReport_Detail__c> lrdList) {
            rowList = new List<PageRowBean>();
            for (LostReport_Detail__c lrd : lrdList) {
                PageRowBean prb = new PageRowBean();
                prb.lrd = lrd;
                prb.ass = lrd.Asset__r;
                prb.asset_dayStr = lrd.Asset_day_F__c == null ? null : lrd.Asset_day_F__c.format();
                rowList.add(prb);
            }
        }
    }

    public class PageRowBean {
        public LostReport_Detail__c lrd {get; set;}
        public Asset ass {get; set;}
        public String asset_dayStr {get; set;}
        public PageRowBean() {
            lrd = new LostReport_Detail__c();
            ass = new Asset();
        }
    }

    public Class ProcessInfo {
        public String userName {get; set;}
        public String appStatus {get; set;}
        public String appTime {get; set;}
        public String appMemo {get; set;}
        public Boolean show {get; set;}

        public ProcessInfo() {
            show = false;
        }
        public ProcessInfo(ProcessInstanceHistory plh) {
            show = false;
            userName = plh.Actor.Name;
            if (plh.StepStatus == 'Approved') {
                appStatus = '已批准';
                show = true;
            }
            else {
                appStatus = plh.StepStatus;
            }
            if (plh.CreatedDate != null) {
                appTime = plh.CreatedDate.format();
            }
            appMemo = plh.Comments;
        }
    }
    /*@TestVisible private static void test() {
        Integer i = 0;
        
    }   */ 
}