public without sharing class TradeCustomerManagerController {

    public String orderId{get;set;}
    public String id{get;set;}
    public String saveYes{get;set;}
    public TradeCustomerManager__c trade{get;set;}
    public Order order{get;set;}
    public List<Attachment> fileList{get;set;}
    public List<Attachment> fileListNew{get;set;}
    public List<Attachment> militaryFileList{get;set;}
    public List<Attachment> personalFileList{get;set;}
    public Integer personalListSize{get;set;}
    public Integer militaryListSize{get;set;}
    public String errorMessage{get;set;}
    public String fileIdDelete{get;set;}
    public String fileIdSee{get;set;}
    public String sendType{get;set;}
    public Boolean isOnClick{get;set;}
    public String oppLink{get;set;}
    public String oppCode{get;set;}
    public String baseUrl{get;set;}
    public String isdeleteFile{get;set;}

    public TradeCustomerManagerController() {
        //获取url中携带的参数
        orderId = System.currentPageReference().getParameters().get('orderId');
        id = System.currentPageReference().getParameters().get('id');
    }
    public TradeCustomerManagerController(ApexPages.StandardController stdController) {
        //获取url中携带的参数
        orderId = System.currentPageReference().getParameters().get('orderId');
        id = System.currentPageReference().getParameters().get('id');
    }

    public void init() {
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        String path = URL.getCurrentRequestUrl().getPath();
        if (path.indexOf('/apex') > 0) {
            baseUrl += path.substring(0,path.indexOf('/apex'));
        } else if (path.indexOf('production/') > 0) {
            baseUrl += '/production';
        }
        saveYes = '';
        isOnClick = false;
        fileList = new List<Attachment>();
        personalFileList = new List<Attachment>();
        militaryFileList = new List<Attachment>();
        fileListNew = new List<Attachment>();
        trade = new TradeCustomerManager__c();
        if(id != null){
            //如果Id不为null 根据Id初始化TradeCustomerManager__c
            trade = [select Id,useNo__c,userNo__c,placeNo__c,productNo__c,useYes__c,userYes__c,placeYes__c,productYes__c,DealerId__c,
                        customerInfoIsUpdate__c,studyDirection__c,endUser__c,model__c,PCmodel__c,contractNum__c,PCcontractNum__c,oppId__c,
                        isAloneCustomer__c,isPC__c,isAlone__c,isHaveLink__c,peopleLink__c,opportunity__c,militaryLink__c,companyLink__c,oppCodeLink__c,
                        application__c,work__c,watchObject__c,order__c,buyTo__c,OrderIdSave__c,remark__c,isFuelNo__c,isFuelYes__c,productSegment__c from TradeCustomerManager__c 
                        where Id=:id];
            order = [select Id,EndUserD__c,applicationForm__c,ProductSegment__c,tradeCustomerApplay__c,ApproveStatus__c,DealerId__c from Order where Id =:trade.OrderIdSave__c];
            fileList = [select Id,Name,CreatedDate,BodyLength,Body,CreatedById,ParentId from Attachment where ParentId =:id];
            for(Attachment att :fileList){
                if(att.Name.startsWith('个人信息')){
                    personalFileList.add(att);
                }else if (att.Name.startsWith('军事')) {
                    militaryFileList.add(att);
                } else{
                    fileListNew.add(att);
                }
            }
        }
        if(orderId!=null){
            //点击新建申请表，查询TradeCustomerManager__c  判断此合同下是否有已经创建的申请表
            order = [select Id,EndUserD__c,applicationForm__c,ProductSegment__c,tradeCustomerApplay__c,ApproveStatus__c,DealerId__c from Order where Id =:orderId];
            List<TradeCustomerManager__c> tradeIsHaveList = [select Id,useNo__c,userNo__c,placeNo__c,productNo__c,useYes__c,userYes__c,placeYes__c,productYes__c,
                        customerInfoIsUpdate__c,studyDirection__c,endUser__c,model__c,PCmodel__c,contractNum__c,PCcontractNum__c,oppId__c,DealerId__c,
                        isAloneCustomer__c,isPC__c,isAlone__c,isHaveLink__c,peopleLink__c,opportunity__c,militaryLink__c,companyLink__c,
                        application__c,work__c,watchObject__c,order__c,buyTo__c,OrderIdSave__c,remark__c,isFuelNo__c,isFuelYes__c,productSegment__c,oppCodeLink__c from TradeCustomerManager__c 
                        where order__c=:orderId];
            System.debug(tradeIsHaveList.size());
            if(tradeIsHaveList != null && tradeIsHaveList.size()!=0){
                trade = tradeIsHaveList[0];
                fileList = [select Id,Name,CreatedDate,BodyLength,Body,CreatedById from Attachment where ParentId =:trade.Id];
                for(Attachment att :fileList){
                    if(att.Name.startsWith('个人信息')){
                        personalFileList.add(att);
                    }else if (att.Name.startsWith('军事')) {
                        militaryFileList.add(att);
                    }else{
                        fileListNew.add(att);
                    }
                }
            }
            trade.endUser__c = order.EndUserD__c;
            trade.productSegment__c = order.ProductSegment__c;
            trade.OrderIdSave__c = orderId;
            trade.DealerId__c = order.DealerId__c;
        }

        personalListSize = personalFileList.size();
        militaryListSize = militaryFileList.size();
        
        if(String.isNotBlank(trade.Id)){
            sendType = 'init';
            send();
        }
        System.debug('ApproveStatus__c:'+order.ApproveStatus__c);
        //检查合同  合同为提交状态 申请表不允许操作
        if(order.ApproveStatus__c == 'OrderPass' || order.ApproveStatus__c == 'OrderSubmit'){
            isOnClick = true;
        }
    }
    // 保存申请表，必填项验证，更新合同中的申请表是否有效的标记
    public void send(){
        //a 是否通过必填验证标志
        Boolean a = true;
        errorMessage = '1'; 
        List<String> strList = new List<String>();
        //必填项验证
        trade.Name = '贸易管理悬念客户（B类）申请表';
        if(trade.isAloneCustomer__c == '是' && (trade.customerInfoIsUpdate__c == null || String.isBlank(trade.oppCodeLink__c))){
            strList.add('重复客户选择是，客户是否有更新、已被审核通过的询价必填;');
            a = false;
        } else if(trade.isAloneCustomer__c == null){
            strList.add('是、否重复客户必须选择一个;');
            a = false;
        }
        if(trade.work__c == null){
            strList.add('职务必填;');
            a = false;
        }
        if(trade.watchObject__c == null){
            strList.add('观察对象必填;');
            a = false;
        }
        if((trade.productSegment__c == 'IE' || trade.productSegment__c == 'RVI') && trade.application__c == null){
            strList.add('工业部门提交，应用领域必填;');
            a = false;
        }
        if(trade.isHaveLink__c == '是' && trade.peopleLink__c==null){
            strList.add('用户是否有个人网址选择是，个人网址链接信息必填;');
            a = false;
        } else if(trade.isHaveLink__c == '否' && trade.companyLink__c == null){
            strList.add('用户是否有个人网址选择否，所在单位网址必填;');
            a = false;
        } else if(trade.isHaveLink__c == null){
            strList.add('用户是、否有个人网址必须选择一个;');
            a = false;
        }
        if(trade.isAlone__c == '是' && (trade.model__c == null || trade.contractNum__c == null)){
            strList.add('是否单独部品采购选择是，对应IF YES,主机型号、IF YES,主机合同号必填;');
            a = false;
        } else if(trade.isAlone__c == null){
            strList.add('是、否单独部品采购必须选择一个;');
            a = false;
        }
        /*if(trade.isPC__c == '是' && (trade.PCmodel__c == null || trade.PCcontractNum__c == null)){
            strList.add('是否PC/显示器采购选择是，对应IF YES,主机型号、IF YES,主机合同号必填;');
            a = false;
        }*/
        if(trade.militaryLink__c == null){
            strList.add('使用者的军用关联web检索链接必填;');
            a = false;
        }
        if ((trade.useYes__c || trade.userYes__c || trade.placeYes__c || trade.productYes__c || trade.isFuelYes__c) && (trade.remark__c == null || trade.remark__c == '确认项目有任何一项选yes，备注必填')) {
            strList.add('确认项目有任何一项选yes，备注必填;');
            trade.remark__c = '';
            a = false;
        }else{
            if(trade.remark__c == '确认项目有任何一项选yes，备注必填'){
                trade.remark__c = '';
            }
        }
        if(militaryFileList.size()!=0){
            Integer i = 0;
            for(Attachment att:militaryFileList){
                if(att.Name.startsWith('军事')){
                    i++;
                    break;
                }
            }
            if(i == 0){
                strList.add('附件命名规则：军事+询价号+使用者个人信息，必须上传军事关联web检索PDF文件;');
                a = false;
            }
        }else{
            strList.add('附件命名规则：军事+询价号+使用者个人信息，必须上传军事关联web检索PDF文件;');
            a = false;
        }
        if(trade.isHaveLink__c == '是'){
            if(personalFileList.size()!=null && personalFileList.size()!=0){
                Integer i = 0;
                for(Attachment att:personalFileList){
                    if(att.Name.startsWith('个人信息')){
                        i++;
                        break;
                    }
                }
                if(i == 0){
                    strList.add('附件命名规则：个人信息+询价号+使用者个人信息，用户是否有个人网址选择是，必须上传个人网址PDF文件;');
                    a = false;
                }
            }else{
                strList.add('附件命名规则：个人信息+询价号+使用者个人信息，用户是否有个人网址选择是，必须上传个人网址PDF文件;');
                a = false;
            }
        }
        trade.order__c = trade.OrderIdSave__c;
        System.debug(sendType);
        if(strList!=null && strList.size()!=0){
            errorMessage = '';
            for(String str:strList){
                errorMessage += str + '-';
            }
        }
        if(sendType != 'init'){
            upsert trade;
        }
        System.debug(a);
        System.debug(order.applicationForm__c);
        if(a != order.applicationForm__c || (errorMessage!= '1' && order.tradeCustomerApplay__c != errorMessage)){
            order.applicationForm__c = a;
            order.tradeCustomerApplay__c = errorMessage;
            update order;
        }
        if(a && sendType=='send'){
            saveYes = '保存成功！';
        }else{
            saveYes = '';
        }
        return;
    }
    public PageReference uploadFile(){
        sendType = 'uploadFile';
        send();
        String b = trade.Id;
        if(b != null && b != ''){
            PageReference ref = new Pagereference('/p/attach/NoteAttach?pid=' + trade.Id + '&retURL=%2Fapex/TradeCustomerManager?id='+trade.Id);
            ref.setRedirect(true);
            return ref;
        }
        return null;
    }

    public void deleteFile(){
        isdeleteFile = 'YES';
        if(fileIdDelete!=null && fileIdDelete !=''){
            for(Integer i=0 ; i<fileListNew.size() ; i++){
                if(fileListNew[i].Id == fileIdDelete){
                    TradeCustomerManager__c tra = [select Id,order__c,isHaveLink__c from TradeCustomerManager__c where Id =: fileListNew[i].ParentId];
                    if(tra!=null){
                        Order order = [select Id,applicationForm__c,ApproveStatus__c from Order where id=:tra.order__c];
                        if(order!=null){
                            if(order.ApproveStatus__c == 'OrderPass' || order.ApproveStatus__c == 'OrderSubmit'){
                                isdeleteFile = 'NO';
                                return;
                            }
                        }
                    }
                    delete fileListNew[i];
                    fileListNew.remove(i);
                    return;
                }
            }
        }
    }
    
    public PageReference deleteForm(){
        if(String.isNotBlank(trade.Id)){
            PageReference ref = new Pagereference('/'+trade.OrderIdSave__c);
            delete trade;
            order.applicationForm__c = false;
            update order;
            //ref.setRedirect(true);
            return ref;
        }else{
            errorMessage = '申请表没有保存！';
        }
        return null;
    }

    public PageReference seeFile(){
         System.debug('fileIdSee:'+fileIdSee);
        if(fileIdSee!=null && fileIdSee !=''){
            PageReference ref = new Pagereference('/'+fileIdSee);
            //ref.setRedirect(true);
            return ref;
        }
        return null;
    } 

    public PageReference returnOrder(){
        /*sendType = 'send';
        send();*/
        PageReference ref = new Pagereference('/'+trade.OrderIdSave__c);
        ref.setRedirect(true);
        return ref;
    } 

    public void getOppCode(){
        
    }
}