public with sharing class LostReportEditAssetController {

    public String lrid {get; set;}
    public String assetId {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;}

    public static final String NONE = system.label.StartTrading_None;  // 「なし」ラベル [Chinese:--无--]

    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'
                                                            };

    public LostReportEditAssetController() {
        assetId = System.currentPageReference().getParameters().get('assetid');
        lrid = System.currentPageReference().getParameters().get('Id');
    }

    public LostReportEditAssetController(ApexPages.StandardController controller) {
        assetId = System.currentPageReference().getParameters().get('assetid');
        lrid = controller.getId();
    }

    // public LostReportEditAssetController(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() {

        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;
        }

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

        if (String.isNotBlank(assetid)) {
            String res = AssetWebService.createLostReport(assetId);

            List<String> resList = res.split(':');
            if (resList[0] == '2') {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, resList[1]));
                return;
            }
            List<Asset> assList = [SELECT Id
                                        , Asset_day__c
                                        , Fixture_Model_No_F__c
                                        , SerialNumber
                                        , Internal_Asset_number_key__c
                                     FROM Asset
                                    WHERE Id = :assetId];
            if (assList.size() == 0) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '不能明确保有设备。请确认数据'));
                return;
            }
            Asset ass = assList[0];
            // Savepoint sp = Database.setSavepoint();
            LostReport__c lr = new LostReport__c();

            lr.Asset__c = assetId;
            // FixtureUtil.withoutInsert(new LostReport__c[]{lr});

            // 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,
            //                                      CreatedDate,
            //                                      CreatedBy.Name,
            //                                      OwnerSys__c,
            //                                      AccountSys__c,
            //                                      Bollow_DateSys__c,
            //                                      demo_purpose2Sys__c,
            //                                      Demo_purpose_textSys__c,
            //                                      Asset__c,
            //                                      Status__c,
            //                                      //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,
            //                                      Status_F__c,
            //                                      Auto_Lost_item_giveupDetailCount__c
            //                                 FROM LostReport__c
            //                                WHERE Id = :lr.Id];
            // if (lrList.size() == 0) {
            //     ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '不能明确遗失报告。请确认数据'));
            //     return;
            // }

            LostReport_Detail__c lrd = new LostReport_Detail__c();
            lrd.LostReport__c = lr.Id;
            lrd.Asset__c = assetId;
            lrd.Quantity__c = 1;
            lrd.Asset_day__c = assList[0].Asset_day__c;
            // FixtureUtil.withoutUpsertObjects(new LostReport_Detail__c[]{lrd});

            // List<LostReport_Detail__c> lrdList = [SELECT Id,
            //                                              Asset__c,
            //                                              Asset__r.Id,
            //                                              Fixture_Model_No_F__c,
            //                                              SerialNumber__c,
            //                                              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.RecordTypeId,
            //                                              LostReport__c
            //                                         FROM LostReport_Detail__c
            //                                        WHERE LostReport__c = :lr.Id
            //                                          AND Asset__c != null];

            // Database.rollback(sp);
            // lrList[0].Name = '';
            pBean = new PageBean(lr);
            pBean.createdByName = UserInfo.getName();
            pBean.createdByDep = [Select Dept__c FROM User WHERE Id = :UserInfo.getUserId()].Dept__c;
            pBean.setAssetList(new LostReport_Detail__c[]{lrd});
            pBean.rowList[0].Fixture_Model_No_F = ass.Fixture_Model_No_F__c;
            pBean.rowList[0].SerialNumber = ass.SerialNumber;
            pBean.rowList[0].Internal_Asset_number = ass.Internal_Asset_number_key__c;
        }
        else {
            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,
                                                 CreatedDate,
                                                 CreatedBy.Name,
                                                 OwnerSys__c,
                                                 AccountSys__c,
                                                 Bollow_DateSys__c,
                                                 demo_purpose2Sys__c,
                                                 Demo_purpose_textSys__c,
                                                 Asset__c,
                                                 Status__c,
                                                 //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,
                                                 Status_F__c,
                                                 Auto_Lost_item_giveupDetailCount__c
                                        FROM LostReport__c
                                       WHERE Id = :lrid];
            if (lrList.size() == 0) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '不能明确遗失报告。请确认数据'));
                return;
            }

            pBean = new PageBean(lrList[0]);
            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,
                                                         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.RecordTypeId,
                                                         LostReport__c
                                                    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);
                }
            }

        }


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

    }

    // public List<SelectOption> getdemo_purpose2SysList() {
    //     Schema.DescribeFieldResult fieldResult = Rental_Apply__c.sObjectType.getDescribe().fields.getMap().get('demo_purpose2__c').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;
    // }

    public PageReference saveLR() {
        Savepoint sp = Database.setSavepoint();
        String saveMessage = '';
        try {
            String saveType = System.currentPageReference().getParameters().get('saveType');
            if (String.isNotBlank(assetid)) {

                String res = AssetWebService.createLostReport(assetId);

                List<String> resList = res.split(':');
                if (resList[0] == '2') {
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, resList[1]));
                    return null;
                }
                pBean.lr.Id = null;
                insert pBean.lr;
                if (pBean.rowList != null && pBean.rowList.size() > 0) {
                    List<LostReport_Detail__c> lrdList = new List<LostReport_Detail__c>();
                    for (PageRowBean prb : pBean.rowList) {
                        prb.lrd.Id = null;
                        prb.lrd.LostReport__c = pBean.lr.Id;
                        lrdList.add(prb.lrd);
                    }
                    if (lrdList.size() > 0) {
                        insert lrdList;
                    }
                }
            }


            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 && String.isBlank(assetid)) {
                List<LostReport_Detail__c> lrdList = new List<LostReport_Detail__c>();
                for (PageRowBean prb : pBean.rowList) {
                    lrdList.add(prb.lrd);
                }
                if (lrdList.size() > 0) {
                    update lrdList;
                }
            }

            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/LostReportEditAsset');
        pg.getParameters().put('Id', pBean.lr.Id);
        pg.getParameters().put('saveMessage', saveMessage);
        pg.setRedirect(true);
        return pg;

    }

    public PageReference cancelRecord() {
        Savepoint sp = Database.setSavepoint(); 
        try {
            List<LostReport_Detail__c> lrdList = [SELECT Id,
                                                         Asset__c,
                                                         Asset__r.Id,
                                                         Fixture_Model_No_F__c,
                                                         SerialNumber__c,
                                                         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.RecordTypeId,
                                                         LostReport__c,
                                                         Auto_Lost_item_giveup_F__c
                                                    FROM LostReport_Detail__c
                                                   WHERE LostReport__c = :pBean.lr.Id];
            for (LostReport_Detail__c lrd : lrdList) {
                if (lrd.Auto_Lost_item_giveup_F__c) {
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '断念后不可以取消遗失报告'));
                    return null;
                }
            }
            //update by rentx 2021-05-14 start 1635
            // LostReportHandler.Loaner_AutoGiveup(null, lrdList, null);
            LostReportHandler.Loaner_AutoGiveup(null, lrdList, null, null);
            //update by rentx 2021-05-14 end 1635
        }
        catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage()));
        }
        PageReference pg = new PageReference('/' + pBean.lr.Id);
        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 String createdByName {get; set;}
        public String createdByDep {get; set;}
        public ProcessInfo jingliInfo {get; set;}
        public ProcessInfo buzhangInfo {get; set;}
        public ProcessInfo qihuakeA {get; set;}
        public ProcessInfo qihuakeB {get; set;}
        public ProcessInfo zongjianliInfo {get; set;}
        public ProcessInfo fenpeirenInfo {get; set;}
        public ProcessInfo yunyingbuzhangInfo {get; set;}
        public ProcessInfo beipinzhongxinInfo {get; set;}

        public Boolean hasApprovedFlag {get; set;}
        public Boolean islock {get; set;}

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

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

            lr = lr1;
            if (String.isNotBlank(lr1.Id)) {
                islock = System.Approval.isLocked(lr1.Id);
                lrCreateDate = lr.CreatedDate.format('yyyy/MM/dd');
                createdByName = lr.CreatedBy.Name;
                createdByDep = lr.CreatedBy.Dept__c;
            }
            else {
                lrCreateDate = Datetime.now().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();
            qihuakeA = new ProcessInfo();
            qihuakeB = new ProcessInfo();
            zongjianliInfo = new ProcessInfo();
            fenpeirenInfo = new ProcessInfo();
            yunyingbuzhangInfo = new ProcessInfo();
            beipinzhongxinInfo = new ProcessInfo();
            rowList = new List<PageRowBean>();

            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;
                    }
                    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(qihuakeA.userName)
                            && plh.ProcessNode.DeveloperName == 'Planning_DivisionA') {
                        qihuakeA = new ProcessInfo(plh);
                    }
                    else if(String.isBlank(qihuakeB.userName)
                            && plh.ProcessNode.DeveloperName == 'Planning_DivisionB') {
                        qihuakeB = 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);
                    }
                }
            }
        }
        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();
                prb.Fixture_Model_No_F = lrd.Fixture_Model_No_F__c;
                prb.SerialNumber = lrd.SerialNumber__c;
                prb.Internal_Asset_number = lrd.Internal_Asset_number__c;
                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 String Fixture_Model_No_F {get; set;}
        public String SerialNumber {get; set;}
        public String Internal_Asset_number {get; set;}

        public PageRowBean() {
            lrd = new LostReport_Detail__c();
            ass = new Asset();
            Fixture_Model_No_F = '';
            SerialNumber = '';
            Internal_Asset_number = '';
        }
    }

    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;
        }
    }
}