public  without sharing class OPDNoReportApplicationController {
    //定义OPD计划
    public  OPDPlan__c opdPlan { get; set; }
    //是否上传附件
    public Boolean IsUpload { get; set; }
    //跳过上传附件判断 
    public Boolean IsHavFile { get; set; }
    //附件
    public List<Attachment> attachmentinfo { get; set; }
    // //执行审批流成功标识
    public Boolean approvalFlag { get; set; }

    //选择演示有无附件标识
    public Boolean noAttachment { get; set; }

    // //执行保存成功
    public Boolean saveFlag { get; set; }

    //因为用户权限不足 不能在页面上直接使用该字段。
    //文本 型号
    public String ModelLendingProductCode { get; set; }
    //id 型号
    public String ModelLendingProductId { get; set; }
    //配套 id
    public String ModelLendingCodeId { get; set; }

    public OPDNoReportApplicationController(ApexPages.StandardController controller) {
    }
    public OPDNoReportApplicationController() {
        
    }
    public void init(){
        //获取页面参数
        String paramId = ApexPages.currentPage().getParameters().get('id');
        //检索opd计划的状态、出借目的、出借目的(工作流用)、模型出借产品型号、对应修理维修NO,无报告状态,追加配套,opd来源,推广经理
        List<OPDPlan__c> OPDPlanList = [select Id,Status__c,RentalReson__c,RentalResonTemp__c,ModelLendingProduct__c,ModelLendingProduct__r.Name,CorrespondingRepairNo__c,noReportStatus__c,AdditionalSupport__c,ModelLending__c,OPDType__c,SalesManager__c,ownerId   from OPDPlan__c where Id = :paramId];

        if( OPDPlanList.size() == 0){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '找不到对应的OPD计划！'));
            return;
        }else{
            opdPlan = OPDPlanList[0];
            this.ModelLendingProductCode = opdPlan.ModelLendingProduct__r.Name;
            this.ModelLendingProductId = opdPlan.ModelLendingProduct__c;
            this.ModelLendingCodeId = opdPlan.ModelLending__c;
        }

        attachmentinfo = [SELECT Id, Name,OwnerId FROM Attachment WHERE  parentid = :paramId];
        if(attachmentinfo.size()>0){
            IsHavFile =true;
        } else {
            IsHavFile = false;
        }
        //审批标识
        approvalFlag =false;
        //保存标识
        saveFlag = false;
    }
    //上传附件
    @RemoteAction
     public static String testAddAttachment(String attachmentName,String attachmentType, String attachmentBody,String parentId) {
         String operateResult;
         Attachment tmpAttachment = new Attachment();
         tmpAttachment.Name = attachmentName;
         tmpAttachment.Body = EncodingUtil.base64Decode(attachmentBody);
         tmpAttachment.ParentId = parentId;
         tmpAttachment.ContentType = attachmentType;
         try {
             insert tmpAttachment;
             operateResult = '您已上传文件成功！';
         } catch (Exception e){
             operateResult = '上传文件失败，请重试！';
         }
         return operateResult;
     }
    //保存
    public PageReference Save() {
        //后台验证
        System.debug('opdPlan3:'+opdPlan);
        Boolean checkFlag =  checkList(IsUpload,IsHavFile);
        if(checkFlag){
            return null;
        }
        if(opdPlan.AdditionalSupport__c !=null){
            //拷贝原OPD计划补充申请
            opdPlan.OriginalOpdPlanApplication__c = opdPlan.AdditionalSupport__c;
        }

            System.debug('opdPlan1:'+opdPlan);
        try{
            //后台赋值
            if(String.isNotBlank(this.ModelLendingProductId)){
                opdPlan.ModelLendingProduct__c = this.ModelLendingProductId;
            }
            else{
                opdPlan.ModelLendingProduct__c=null;
            }
            if(String.isNotBlank(this.ModelLendingProductId)){
                opdPlan.ModelLending__c = this.ModelLendingCodeId;
            }
            else{
                opdPlan.ModelLending__c=null;
            }
            opdPlan.noReportStatus__c = '已保存';
            System.debug('opdPlan2:'+opdPlan);
            update opdPlan;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM, '保存完毕！'));
            saveFlag = true;
        }catch(exception e){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
            saveFlag =false;

        }

        return null;

    }
    //提交待审批
    public PageReference CommitNeedApproval(){
        
        System.debug('提交待审批11');
        Savepoint sp = Database.setSavepoint();
        //后台验证
        Boolean checkFlag =  checkList(IsUpload,IsHavFile);
        if(checkFlag){
            return null;
        }
        //2021-01-27  mzy  模型出借号,不保存直接审批没有值  start
        //在提交审批之前再次保存一下
        Save();
        //2021-01-27  mzy  模型出借号,不保存直接审批没有值  end
        if(opdPlan.AdditionalSupport__c !=null){
            //拷贝原OPD计划补充申请
            opdPlan.OriginalOpdPlanApplication__c = opdPlan.AdditionalSupport__c;
        }
        //判断来源是否是学会
        if(opdPlan.OPDType__c == '学会' && opdPlan.SalesManager__c == null){
            String id = opdPlan.ownerId;
            List<User> userList = [select id,SalesManager__c from user where id =:id ];
            if(userList.size()>0){
                opdPlan.SalesManager__c = userList[0].SalesManager__c;
            }
        }

        //更新状态为计划中
        opdPlan.noReportStatus__c = '提交';
        List<OPDPlan__c> opdList = new List<OPDPlan__c>();
        try{
            if(opdPlan!=null){
                opdList.add(opdPlan);
            }
            update opdPlan;
                Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
                psr.setObjectId(this.opdPlan.id);
                Approval.ProcessResult submitResult = Approval.process(psr);
                if(opdList.size()>0){
                    Approval.UnLockResult[] results = Approval.unlock(opdList, false);
                }
                
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM, '审批已提交'));
                approvalFlag = true;
           
        }catch(exception e){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
            approvalFlag = false;
            Database.rollback(sp);
            return null;
        }

        
        return null;
    }
    //check验证
    public Boolean checkList( Boolean IsUpload,Boolean IsHavFile){
        System.debug('IsUpload:'+IsUpload);
        System.debug('opdPlan.RentalResonTemp__c:'+opdPlan.RentalResonTemp__c);
        System.debug('IsHavFile:'+IsHavFile);
        //①出借目的选择模型出借时，模型出借产品型号必填
        if(opdPlan.RentalResonTemp__c.equals('模型出借')&&string.isBlank(this.ModelLendingProductId)){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请您填写1.模型出借产品型号！'));
            return true;
        }
        //出借目的选择对应修理时，对应修理维修NO必填
        else if(opdPlan.RentalResonTemp__c.equals('对应修理')&&string.isBlank(opdPlan.CorrespondingRepairNo__c)){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请您填写2.对应修理维修NO！'));
            return true;
        }
        //出借目的选择演示或疫情时，必须上传文件说明
        else if((opdPlan.RentalResonTemp__c.equals('演示')||opdPlan.RentalResonTemp__c.equals('无法进入手术室'))&&!IsUpload&&!IsHavFile){
            noAttachment = true;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请您上传文件证明！'));
            return true;
        }
        //出借目的选择演示或疫情时，必须上传文件说明
        else if(opdPlan.RentalResonTemp__c.equals('追加配套')&&string.isBlank(opdPlan.AdditionalSupport__c)){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请填写4.追加配套！'));
            return true;
        }
        if(opdPlan.RentalResonTemp__c.equals('--无--')){
            opdPlan.RentalResonTemp__c = null;
        }
        return false;
    }
    //获取选项列表的值
    public List<SelectOption> getRentalReson() {

        map<string, list<pickerWrapper>> pickerFields = new map<string, list<pickerWrapper>>();

        // OPD计划 出借目的（工作流用）copy 选项值动态获取
        list<pickerWrapper> taskStatusOptions = new list<pickerWrapper>();
        Schema.DescribeFieldResult taskStatusfieldResult = OPDPlan__c.RentalResonTemp__c.getDescribe();
        List<Schema.PicklistEntry> taskStatusple = taskStatusfieldResult.getPicklistValues();
        for ( Schema.PicklistEntry pickListVal : taskStatusple) {
            pickerWrapper temppickerWrapper =
                new pickerWrapper(pickListVal.getLabel(), pickListVal.getValue());
            taskStatusOptions.add(temppickerWrapper);
        }
        pickerFields.put('taskStatusOptions', taskStatusOptions);

        List<pickerWrapper> pickerWrapperList = pickerFields.get('taskStatusOptions');

        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('--无--', '--无--'));
        for(pickerWrapper pw : pickerWrapperList){
            //无报告申请 页面上去掉 OPD 选项
            if(!pw.value.equals('OPD')){
                options.add(new SelectOption(pw.value, pw.value));
            }
        }

        return options;
    }


    //定义动态获取选项值的构造类
    public class pickerWrapper {
        @AuraEnabled
        public string label;
        @AuraEnabled
        public string value;
        public pickerWrapper(string label, string value) {
            this.label = label;
            this.value = value;
        }

    }
}