public without sharing class StraightBackAddressController {
    /**
     * 页面顶部检索数据
     */
    public String typeText { get; set; } //第一个下拉列表
    public Address__c optionAddressClassification{get;set;}
    public String txtName{get;set;}//客户名
    public String txtAddress{get;set;}//地址

    /***************表格数据*********************/
    public List<AddressData> tableData { get; set; }
    public String tableDataStr{ get; set; }
    public String staticResource {get; set;}
    public String staticResourceContact {get; set;}
    public String staticResourceRepair {get; set;}
    public Contact newCon{get; set;}

    /***************底部 编辑和新增的 对象*******************/
    public Address__c insUpdData{get;set;}
    public String insUpdDataStr{get;set;}

    /***************被编辑数据的id********************/
    public String UpdId{get;set;}

    /***************复选框选中id*********************/
    public String adoptId{get;set;}

    /***************联系人的对象*********************/
    public Contact addContact{get;set;}

    /***************修理表的对象*********************/
    public Repair__c pc{get;set;}

    /***************url传来的修理单id********************/
    public String RepairId{get;set;}

    /***************获取科室的类型*********************/
    public String hospitalTypp {get;set;}

    /*******************修理表上医院的id**********************/
    public String hospitalId{get;set;}

    /*******************修理表上保有设备的id**********************/
    public String equipmentlId{get;set;}

    /**************采用按钮展示名称（采用，采用并上传SAP）*************/
    public String FSEApplyForRepairTime{get;set;}

    /**************是否上传SAP*************/
    public Boolean isUpload{get;set;}

    /**************判断页面是否需要检索*************/
    public Boolean isSearchBtn{get;set;}

     /**************当前登录人*************/
    public String loginPerson{get;set;}

    /***************经销商名*************/
    public String addressDealers{get;set;}

    /***************是否发生数据接口的序号*************/
    public Integer AddressTypeIndex{get;set;}

    public String contactId{set;get;}//For Lookup field

    // Add by Li Jun for PIPL 20220308 Start
    public String contactNameValue{set;get;}
    public String contactIdValue{set;get;}
    public String addressDataIds{set;get;} 
    public String sfRecordId{set;get;} 
    // Add by Li Jun for PIPL 20220308 End

    public String accRecordTypeId {set;get;}//当前 记录类型id 

    public String accOfficeTypeId {set;get;}//记录类型id  办事处
    public String accAgencyTypeId {set;get;}//记录类型id  販売店
    public String accAgencyContactTypeId {set;get;}//记录类型id  经销商联系人

    public StraightBackAddressController() {
        //获取url数据
        RepairId = System.currentPageReference().getParameters().get('id');
        //获取当前登录人
        loginPerson = (Userinfo.getUserId()).substring(0,15);
        typeText = '';
        tableData = new List<AddressData>();
        insUpdData = new Address__c();
        pc = new Repair__c();
        optionAddressClassification = new Address__c();
        FSEApplyForRepairTime = '';
        isUpload = false;
        UpdId = '';
        adoptId = '';
        hospitalId = '';
        equipmentlId = '';
        addressDealers = '';
        isSearchBtn = true;
        AddressTypeIndex = 0;
        addContact = new Contact();
        //查询到所有的科室类别
        hospitalTypp = '診療科 その他,診療科 呼吸科,診療科 婦人科,診療科 普外科,診療科 泌尿科,診療科 消化科,診療科 耳鼻喉科,診療科（共通）';


        staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('Address__c'));
        staticResourceContact = JSON.serialize(PIHelper.getPIIntegrationInfo('Contact'));
        staticResourceRepair = JSON.serialize(PIHelper.getPIIntegrationInfo('Repair__c'));
    }

    /**
     * 开始方法
     */
    public PageReference init(){
        Schema.RecordTypeInfo recordTypeValue = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Office');
        if(recordTypeValue == null){
            recordTypeValue = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('office');
        }
        accOfficeTypeId = recordTypeValue.getRecordTypeId();
        accAgencyTypeId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Agency').getRecordTypeId();
        accAgencyContactTypeId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('AgencyContact').getRecordTypeId();
        String RepairSql = makeTextRepairSql(RepairId);
        try{
            pc = Database.query(RepairSql);
            system.debug('pc = ' + pc);
            //给一个全局变量赋值医院id
            if(!String.isBlank(pc.HP_ID__c)){
                hospitalId = pc.HP_ID__c;
            }
            //获取修理表上的保有设备id
            if(!String.isBlank(pc.Delivered_Product__c)){
                equipmentlId = pc.Delivered_Product__c;
            }
            //获取当前修理的申请修理时间  SAP_Transfer_time__c：SAP修理申请时间
            if(!String.isBlank(pc.SAP_Transfer_time__c+'')){
                FSEApplyForRepairTime = pc.SAP_Transfer_time__c+'';
            }
            //主要用于记录是否需要触发接口使用
            if(pc.Address_Type_Index__c != null){
                AddressTypeIndex = pc.Address_Type_Index__c.intValue();
            }
            if(!String.isBlank(pc.Returns_Product_way__c)){
                if('返送医院'.equals(pc.Returns_Product_way__c)){
                    //获取修理表的医院，用于第一次进入页面时，检索条件：客户名 的默认值
                    if(!String.isBlank(pc.HP_Name__c)){
                        txtName = pc.HP_Name__c; 
                        optionAddressClassification.Address_Classification__c = '医院';
                    }
                }else if('返送办事处'.equals(pc.Returns_Product_way__c)){
                    optionAddressClassification.Address_Classification__c = '办事处';
                }else{
                    //获取当前修理的返送经销商
                    if(!String.isBlank(pc.Dealer__c) && '返送经销商'.equals(pc.Returns_Product_way__c)){
                        txtName = pc.Dealer__r.Name; 
                        optionAddressClassification.Address_Classification__c = '经销商';
                    }
                }
            }
            //所有的查询方法
            searchBtn();
        }catch(exception e){
            //失败提示
            ApexPages.addMessages(e);
        }
        insUpdData = new Address__c();
        newCon = new Contact();
        return null;
    }
    
    //查询客户记录类型
    public PageReference queryRecordType(){
        if(insUpdData.Customer__c!=null){
            String accid = insUpdData.Customer__c;
            Account acc = [SELECT id,name,RecordTypeId FROM Account WHERE id =: accid];
            System.debug('acc---'+acc);
            System.debug('insUpdData---'+insUpdData);
            if(acc!=null&&acc.RecordTypeId!=null&&insUpdData.Customer__c!=null){
                accRecordTypeId = acc.RecordTypeId;
            }
        }
        return null;
    }
    //编辑获取数据
    public PageReference onEditor(){
        if(!String.isBlank(UpdId)){
            if(tableData != null && tableData.size() > 0){
                insUpdData = new Address__c();
                ID newId = ID.valueOf(UpdId);
                for(Integer i = 0;i<tableData.size();i++){
                    ID oldid = tableData[i].address.id;
                    if(oldid == newId){
                        insUpdData = tableData[i].address;
                    }
                }
                insUpdDataStr = JSON.serialize(insUpdData);
            }
        }
        return null;
    }
    //复制，克隆一条数据，数据没有id
    public PageReference onCopy(){
        if(!String.isBlank(UpdId)){
            if(tableData != null && tableData.size() > 0){
                if('空'.equals(UpdId)){//如果为 空 ，那么证明此数据是从修理表上带过来的数据
                    insUpdData = new Address__c();
                    insUpdData = tableData[0].address.clone();
                }else{
                    insUpdData = new Address__c();
                    ID newId = ID.valueOf(UpdId);
                    for(Integer i = 0;i<tableData.size();i++){
                        ID oldid = tableData[i].address.id;
                        if(oldid == newId){
                            insUpdData = tableData[i].address.clone();//克隆
                            insUpdData.id = null;//由于是复制，是需要insert的操作，所以把id设为空
                        }
                    }
                }
                insUpdDataStr = JSON.serialize(insUpdData);
            }
        }
        return null;
    }
    /*
    //采用按钮
    public PageReference adoptSave(){
        //adoptId  要采用的地址数据id
        if(!String.isBlank(adoptId)){
            if(tableData != null && tableData.size() > 0){
                //由于要把采用时间记录到地址表中，所以新建一个地址对象
                Address__c DatetimeUpdate = new Address__c();
                for(Integer i = 0;i<tableData.size();i++){
                    ID oldid = tableData[i].address.id;
                    //采用id和遍历的id相同，证明此调数据就是要采用的数据
                    if(oldid == adoptId){
                        DatetimeUpdate = tableData[i].address;
                        //详细地址
                        String address = tableData[i].address.Detailed_Address__c.trim();
                        String cityName = '';//市
                        //市不为空，因为要使用 __r.Name  如果为空，会报错
                        if(String.isNotBlank(tableData[i].address.City__c)){
                            cityName = tableData[i].address.City__r.Name.trim();
                            //省 同上
                            if(!String.isBlank(tableData[i].address.Province__c)){
                                String ProvinceCity = tableData[i].address.Province__r.name.trim()+cityName;
                                //防止详细地址里面带着省份和市
                                if(!address.contains(ProvinceCity)){
                                    address = ProvinceCity + address;
                                }
                            }
                        }
                        //联系人
                        String contactsName = '';
                        String contactsNameEncrypt ='';
                        String contactawsDataId = '';
                        if(!String.isBlank(tableData[i].address.Contacts__c)){
                            contactsName = tableData[i].address.Contacts__r.Name;
                            contactsNameEncrypt = tableData[i].address.Contacts__r.LastName_Encrypted__c;
                            contactawsDataId = tableData[i].address.Contacts__r.AWS_Data_Id__c;
                        }
                        //客户
                        String ContactPerson = '';
                        if(!String.isBlank(tableData[i].address.Customer__c)){
                            ContactPerson = tableData[i].address.Customer__r.Name;
                        }
                        try{
                            //保存数据到修理表中
                            Repair__c rc = new Repair__c();
                            rc.id = RepairId;
                            rc.Address_AWS_Data_Id__c = tableData[i].address.AWS_Data_Id__c;
                            rc.Contact_AWS_Data_Id__c = contactawsDataId;
                            rc.address_Contacts__c = contactsName;
                            rc.Address_Contacts_Encrypt__c = contactsNameEncrypt;
                            rc.address_ZipCode__c = tableData[i].address.ZipCode__c;
                            rc.Address_ZipCode_Encrypt__c = tableData[i].address.ZipCode_Encrypted__c;
                            rc.address_City__c = cityName;
                            rc.address_Contacts_Name__c = ContactPerson;
                            rc.Detailed_Address__c = tableData[i].address.Detailed_Address__c;
                            rc.Detailed_Address_Encrypt__c = tableData[i].address.Detailed_Address_Encrypted__c;
                            rc.address_Telephone__c = tableData[i].address.Telephone__c;
                            rc.Address_Telephone_Encrypt__c = tableData[i].address.Telephone_Encrypted__c;
                            //isUpload：是否上传SAP  FSEApplyForRepairTime：SAP修理申请时间
                            if(isUpload && (FSEApplyForRepairTime != null)){
                                rc.Address_type__c = 'X';
                                rc.Address_Type_Index__c = AddressTypeIndex+1;
                            }
                            rc.address_Telephone__c=tableData[i].address.Telephone__c;
                            rc.Detailed_Address__c=address;
                            if(!Test.isRunningTest()){
                                update rc;
                            }

                             //保存数据到保有设备表中
                            Asset ast = new Asset(
                                id=equipmentlId,
                                address_Contacts__c=contactsName,
                                address_ZipCode__c = tableData[i].address.ZipCode__c,
                                address_City__c = cityName,
                                address_Telephone__c=tableData[i].address.Telephone__c,
                                address_Contacts_Name__c = ContactPerson,
                                Detailed_Address__c=address);
                            update ast;

                            //最后把当前时间保存到地址表中，作为采用时间
                            DatetimeUpdate.Using_Datetime__c = Datetime.now();
                            update DatetimeUpdate;

                            //页面重定向
                            return redirectPag();
                        }catch(Exception e){
                            //失败提示
                            ApexPages.addMessages(e);
                        }
                    }
                }
            }
        }
        return null;
    }
*/
    //重定向到 修理页面
    public PageReference redirectPag(){
        PageReference ref = new Pagereference('/' + RepairId);
        ref.setRedirect(true);
        return ref;
    }
	

    /**
     * 检索数据查询
     */
    public PageReference searchBtn(){
        //获取搜索框类型的值
        typeText = optionAddressClassification.Address_Classification__c;
        //统计总共查询到的数量
        integer indexCou = 0;
        tableData = new List<AddressData>();
        insUpdData = new Address__c();
        String typeSearchId = '';
        //由于salseforce 的选项列表中的 无 删除不了，所以默认如果为 无，那么就是 医院
        if(String.isBlank(typeText)){
            typeText = '办事处';
        }
        try{
            if(('医院'.equals(typeText)) && pc.HP_ID__c != null){
                //HP_ID__c  医院id
                typeSearchId = pc.HP_ID__c;
                String AccountSql = makeTextAccountSql(pc.HP_ID__c);
                //获取地址信息
                List<Account> accoutList = Database.query(AccountSql);
                if(accoutList != null && accoutList.size() > 0){
                    indexCou++;
                    tableData.add(new AddressData(accoutList[0],'none','inline','none','医院'));
                }
            }
            //办事处
            /*if('办事处'.equals(typeText)){
                String AccountOfficeSql = makeTextAccOfficeSql();
                //获取地址信息
                List<Account> accDataList = Database.query(AccountOfficeSql);
                if(accDataList != null && accDataList.size() > 0){
                    for(Integer i = 0;i<accDataList.size();i++){
                        indexCou++;
                        tableData.add(new AddressData(accDataList[i],'none','办事处'));
                    }
                }
            }*/
            //经销商：
            //1：如果查到多条经销商，并且在地址中查到有数据，只显示地址数据，如果地址数据没查不到，就不显示，
            //2：如果查到有一条经销商，那么第一行就是此经销商数据，从第二行开始为地址数据
            if('经销商'.equals(typeText) && txtName != ''){
                String AccountSql = makeTextAccountDealersSQl();
                //获取地址信息
                List<Account>  accoutList = Database.query(AccountSql);
                if(accoutList != null && accoutList.size() > 0){//防止一条也没查到
                    if(accoutList.size() == 1){
                        indexCou++;
                        tableData.add(new AddressData(accoutList[0],'none','inline','none','经销商'));
                    }else{
                        tableData = new List<AddressData>(); 
                    }
                }
            }
            //获取地址信息
            //参数：typeSearchId  类型为医院值为：医院的id   如果类型为经销商：值为返送经销商id   办事处：参数为空
            String AddressSql = makeTextAddressSql(typeSearchId);
            List<Address__c> dataList = Database.query(AddressSql);
            if(dataList != null && dataList.size()> 0){
                indexCou += dataList.size();
                System.debug('dataList-----'+dataList);
                for(Integer i = 0;i<dataList.size();i++){
                    String createID = dataList[i].CreatedByid;
                    createId = createId.substring(0,15);
                    //办事处的地址不可修改
                    
                    if(dataList[i].Address_Classification__c == '办事处'){
                        tableData.add(new AddressData(dataList[i],'none','none','inline'));
                    }else{
                        //只能改自己创建的地址数据，系统管理员、GPI_系统管理员New 没限制
                        if(loginPerson == createId ||loginPerson == '00e10000000dzzG' ||loginPerson == '00e10000000Y3o5'){
                            tableData.add(new AddressData(dataList[i],'inline','inline','inline'));
                        }else{
                            tableData.add(new AddressData(dataList[i],'none','inline','inline'));
                        }
                    }
                }
            }else{
                //如果地址里面一条也没查到，那么需要判断是否为经销商的数据，如果为经销商数据，那么提示需要修改
                 if('经销商'.equals(typeText) && txtName != null){
                    if(tableData.size() == 0){
                        tableData = new List<AddressData>(); 
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '共有 0 条数据，如果没有想要的经销商地址，请尝试精确检索条件。'));
                        return null;
                    }
                }
            }
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '共有 '+indexCou+' 条数据'));
            tableDataStr = JSON.serialize(tableData);
            system.debug('tableDataStr = ' + tableDataStr);
        }catch(Exception e){
            //失败提示
            ApexPages.addMessages(e);
        }
        return null;
    }

    /**
     * 保存和修改的方法
     */
    public PageReference save(){
        system.debug('Address value:'+JSON.serialize(insUpdData));       
        if(String.isNotBlank(contactIdValue)&&String.isNotEmpty(contactIdValue)){
            system.debug('Contact Value:'+contactIdValue);
            insUpdData.Contacts__c = contactIdValue;
        }
        system.debug('Address value:'+JSON.serialize(insUpdData));
        savepoint sp = Database.setsavepoint();
        if(insUpdData != null){
            boolean flag = true;

            //类型不能为空
            if(String.isBlank(insUpdData.Address_Classification__c)){
                flag = false;
                this.insUpdData.Address_Classification__c.addError('不能为空！');
            }else if(insUpdData.Address_Classification__c == '办事处'){
                this.insUpdData.Address_Classification__c.addError('办事处地址不能新增和修改！');
                flag = false;
                return null;
            }
            //省份不能为空
            if(String.isBlank(insUpdData.Province__c)){
                flag = false;
                this.insUpdData.Province__c.addError('不能为空！');
            }
            //市不能为空
            if(String.isBlank(insUpdData.City__c)){
                flag = false;
                this.insUpdData.City__c.addError('不能为空！');
            }
            //电话不能为空
            if(String.isBlank(insUpdData.Telephone__c)){
                flag = false;
                this.insUpdData.Telephone__c.addError('不能为空！');
            }
            //详细地址不能为空
            if(String.isBlank(insUpdData.Detailed_Address__c)){
                flag = false;
                this.insUpdData.Detailed_Address__c.addError('详细地址不能为空！');
            }
            
            //客户不能为空
            if(String.isBlank(String.valueOf(insUpdData.Customer__c))){
                flag = false;
                this.insUpdData.Customer__c.addError('不能为空！');
            }else{
                //如果类型为医院，那么客户字段必须选择修理表下医院的科室
                if(insUpdData.Address_Classification__c == '医院'){
                    String ty = insUpdData.Customer__c;
                    String AccSQl = makeAccoutSoql(ty);
                    List<Account> AccList = new List<Account>();
                    try{
                        AccList = Database.query(AccSQl);
                        if(AccList != null && AccList.size() > 0){
                            for(Integer i = 0;i<AccList.size();i++){
                                //首先判断是否是修理表下的医院科室
                                String parentId = AccList[i].Parent.parent.id;
                                if(parentId != null){
                                    parentId = parentId.substring(0,15);
                                    hospitalId = hospitalId.substring(0,15);
                                    if(hospitalId != parentId){
                                        flag = false;
                                        this.insUpdData.Customer__c.addError('必须是当前修理表医院下的科室！');
                                    }
                                }else{//客户必须为科室
                                    flag = false;
                                    this.insUpdData.Customer__c.addError('必须选具体科室！!');
                                   /*String se = AccList[i].RecordType.name;
                                   if(!hospitalTypp.contains(se)){
                                        flag = false;
                                        this.insUpdData.Customer__c.addError('必须选具体科室！');
                                   }*/
                                }
                            }
                        }
                    }catch(exception e){
                        //失败提示
                        ApexPages.addMessages(e);
                    }
                }
            }
            //判断联系人是否都为空
            if(insUpdData.Contacts__c == null || String.isBlank(insUpdData.Contacts__c)){
                //判断新建联系人是否为空
                if(insUpdData.Create_Contacts__c == null || String.isBlank(insUpdData.Create_Contacts__c)){
                    flag = false;
                    this.insUpdData.Create_Contacts__c.addError('【联系人】和【联系人（新建）】不能同时为空！');
                }else{//如果联系人为空，但是新建联系人不为空，那么新增一条联系人数据
                    if(flag){
                        String typeL = '';//类型
                        if(insUpdData.Address_Classification__c == '医院'){
                            typeL = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Doctor').getRecordTypeId();//医師
                        }else if(insUpdData.Address_Classification__c == '经销商'){
                            typeL = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Agency').getRecordTypeId();//販売店
                        }else if(insUpdData.Address_Classification__c == '办事处'){
                            typeL = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Internal_staff').getRecordTypeId();//社内员工
                        }
                        String surname = String.valueOf(insUpdData.Create_Contacts__c);//姓
                        String monicker = '';//名
                        if(surname.length() >= 2){
                            monicker = surname.substring(1,surname.length());
                            surname = surname.substring(0,1);
                        }
                        System.debug('newCon = '+newCon);
                        addContact = new Contact(LastName = surname,
                                                FirstName = monicker,
                                                AccountId = insUpdData.Customer__c,
                                                RecordTypeId = typeL,
                                                AWS_Data_Id__c = newCon.AWS_Data_Id__c,
                                                LastName_Encrypted__c = newCon.LastName_Encrypted__c);
                        try{
                            //新增一条联系人数据
                            insert addContact;
                            sfRecordId = addContact.id;
                            insUpdData.Create_Contacts__c = '';
                        }catch(Exception e){
                            //ApexPages.addMessages(e);
                            Database.rollback(sp);
                            //失败提示
                            System.debug('myException caught when save or submit: ' + e.getMessage() + e.getStackTraceString());
                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage()));
                            isSearchBtn = false;
                            return null;
                        }
                        insUpdData.Contacts__c = addContact.id;
                        //name赋值
                        /*if(insUpdData.Contacts__c == null){
                            insUpdData.name =  insUpdData.Customer__r.Name+'_'+insUpdData.Contacts__r.Name;
                        }else{
                            insUpdData.name =  insUpdData.Customer__r.Name+'_'+insUpdData.Create_Contacts__c;
                        }*/
                    }
                }
            }else{//联系人和新建联系人不能都有值
                //判断新建联系人是否为空
                if(!String.isBlank(insUpdData.Create_Contacts__c)){
                    flag = false;
                    this.insUpdData.Create_Contacts__c.addError('【联系人】和【联系人（新建）】不能同时都有值！');
                }
            }
            if(flag){
                try{
                    //新增或修改数据
                    upsert insUpdData;
                    
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '保存成功！'));
                    isSearchBtn = true;
                    //保存成功，需要初始化一下此对象，防止再次点击此按钮保存一个条同样的数据
                    insUpdData = new Address__c();
                }catch(Exception e){
                    ApexPages.addMessages(e);
                    //ApexPages.addMessages(e);
                    Database.rollback(sp);
                    //失败提示
                    System.debug('myException caught when save or submit: ' + e.getMessage() + e.getStackTraceString());
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage()));
                    isSearchBtn = false;
                    return null;
                }
            }else{
                //判断保存是否成功，如果失败不需要刷新列表
                isSearchBtn = false;
            }
        }
        return null;
    }


    //查询修理表数据
    private String makeTextRepairSql(String uuid){
        String RepairSql = 'SELECT ID,NAME,HP_ID__c,HP_Name__c,Delivered_Product__c,FSE_ApplyForRepair_time__c,SAP_Transfer_time__c,Dealer__c,Dealer__r.Name,Returns_Product_way__c,Address_Type_Index__c,AWS_Data_Id__c FROM Repair__c where id = \''+RepairId+'\'';
        return RepairSql;
    }
    //查询地址表数据
    private String makeTextAddressSql(String typeSearchId) {
        String AddressSql = 'SELECT AWS_Data_Id__c,ID,Address_Classification__c,Customer__c,Customer__r.Name,Customer__r.Type,Customer__r.RecordTypeId,Contacts__c,Contacts__r.Name,Contacts__r.AWS_Data_Id__c,Telephone__c'
                        +',Province__c,Province__r.Name,City__c,City__r.name,Detailed_Address__c,Create_Contacts__c,ZipCode__c,CreatedByid,Detailed_Address_Encrypted__c,Telephone_Encrypted__c,ZipCode_Encrypted__c,Contacts__r.LastName_Encrypted__c'
                        + ' FROM Address__c where id != null';
        //类型筛选
        if(!String.isBlank(typeText)){
            if('医院'.equals(typeText)){
                if(String.isBlank(typeSearchId)){
                    AddressSql += ' and Address_Classification__c LIKE \'%' + typeText.trim() + '%\'' ;
                }else{
                    //查询医院id为修理表上医院id
                    AddressSql += ' and Hospital__c = \'' + typeSearchId + '\'  and Address_Classification__c LIKE \'%' + typeText.trim() + '%\'';
                }
            }
            if('办事处'.equals(typeText)){
                AddressSql += ' and Address_Classification__c LIKE \'%' + typeText.trim() + '%\'' ;
            }
            if('经销商'.equals(typeText)){
                if(String.isBlank(typeSearchId)){
                    AddressSql += ' and Address_Classification__c LIKE \'%' + typeText.trim() + '%\'' ;
                }
            }
        }
        //客户筛选
        if(!String.isBlank(txtName)){
            AddressSql += ' and Customer__r.Name LIKE \'%' + txtName.trim() + '%\'' ;
        }
        //详细地址筛选
        // if(!String.isBlank(txtAddress)){
        //     AddressSql += ' and Detailed_Address__c LIKE \'%' + txtAddress.trim() + '%\'' ;
        // }
        if(!String.isBlank(addressDataIds)){
            AddressSql += ' and AWS_Data_Id__c in('+addressDataIds.trim()+')';
        }
        //排序，根据上次修改时间和采用时间进行降序排序,值为空放到后面
        AddressSql += ' order by LastModifiedDate desc,Using_Datetime__c desc NULLS LAST';
        //如果修理表的经销商或医院为空，那么查询地址表前200条的经销商或医院地址
        if(String.isBlank(typeSearchId)){
            AddressSql += ' limit 1000 ';
        }
        System.debug('AddressSql = '+AddressSql);
        return AddressSql;
    }
    //查询医院客户人员信息
    private String makeTextAccountSql(String accId){
        String AccountSql = 'SELECT ID,NAME,Phone,State_Master__c,State_Master__r.name,City_Master__c,City_Master__r.name,Address__c '
                            + ' FROM Account WHERE ID = \'' + accId + '\'';
        if(!String.isBlank(txtName)){
            AccountSql += ' and Name LIKE \'%' + txtName.trim() + '%\'' ;
        }
        if(!String.isBlank(txtAddress)){
            AccountSql += ' and Address__c LIKE \'%' + txtAddress.trim() + '%\'' ;
        }
        return AccountSql;
    }
    //查询经销商信息
    private String makeTextAccountDealersSQl(){
        String AccountSQl = 'SELECT ID,NAME,Phone,State_Master__c,State_Master__r.name,City_Master__c,City_Master__r.name,Address__c '
                        + ' FROM Account WHERE ID !=  null ';
        if(!String.isBlank(txtName)){
            AccountSQl += ' and Name LIKE \'%' + txtName.trim() + '%\'' ;
        }
        if(!String.isBlank(txtAddress)){
            AccountSQl += ' and Address__c LIKE \'%' + txtAddress.trim() + '%\'' ;
        }
        return AccountSQl;
    }
    //查询办事处信息
    /*private String makeTextAccOfficeSql(){
        String AccountOfficeSql = 'SELECT ID,NAME,Phone,State_Master__c,State_Master__r.name,City_Master__c,City_Master__r.name,Address__c '
                            +' FROM Account WHERE Whether_Office__c = true';
        if(!String.isBlank(txtName)){
            AccountOfficeSql += ' and Name LIKE \'%' + txtName.trim() + '%\'' ;
        }
        if(!String.isBlank(txtAddress)){
            AccountOfficeSql += ' and Address__c LIKE \'%' + txtAddress.trim() + '%\'' ;
        }
        return AccountOfficeSql;
    }*/
    //获取account 表的所有数据
    private String makeAccoutSoql(String accId){
        String AccountSql = 'SELECT ID,NAME,Phone,State_Master__c,State_Master__r.name,City_Master__c,City_Master__r.name,Address__c,'
                        + ' RecordType.name,Parent.Parent.Id FROM Account WHERE ID = \'' + accId + '\'';
        return AccountSql;
    }
    
    @RemoteAction
    public static string SaveEx(string repaire_json,string asset_json, string address_id){
        return SaveExCore(repaire_json,asset_json,address_id);
    }

    public static string SaveExCore(string repaire_json,string asset_json, string address_id){
        string message = null;
        string savemessage = null;
        savepoint sp = Database.setsavepoint();
        try {
            Repair__c r = (Repair__c)JSON.deserialize(repaire_json,Repair__c.class);
            Asset ast = (Asset)JSON.deserialize(asset_json,Asset.class);
            Address__c add = new Address__c(Id=address_id,Using_Datetime__c = Datetime.now());
            update r;
            update ast;
            update add;
        }catch(DmlException e) {
            Integer index = 0;
            System.debug(e.getNumDml());
            System.debug(e.getDmlFields(index));
            System.debug(e.getDmlId(index));
            System.debug(e.getDmlIndex(index));
            System.debug(e.getDmlMessage(index));
            System.debug(e.getDmlStatusCode(index));
            System.debug(e.getDmlType(index));
			system.debug(e.getMessage());
            system.debug(e.getStackTraceString());

            System.debug('into catch'+e.getMessage());
            Database.rollback(sp);
            
            message ='保存失败，原因:'+ e.getDmlMessage(index);
            savemessage = e.getMessage()+e.getStackTraceString();            
        } catch (Exception e) {
            System.debug('into catch'+e.getMessage());
            Database.rollback(sp);
            
            savemessage = e.getMessage()+e.getStackTraceString();
            message = '保存失败';
        } finally {
            PIHelper.saveTransLog('StraightBackAddressController',address_id,address_id,address_id, repaire_json ,asset_json,message);
        }
        return message;
    }

    /**
     * 为了方便前段table获取值
     */
    class AddressData {
        //数据
        public Address__c address { get; set; }

        public string addressJson { get{
            if (address == null) {
                return null;
            }
            return JSON.serialize(address);
        } }

        //编辑按钮是否展示
        public String canEdit { get; private set; }
        //编辑按钮是否展示
        public String canCopy {get;private set;}
        //采用按钮是否展示
        public  String canAdopt{get;private set;}
        
        public AddressData(Address__c record) {
            address = record;
            canEdit = '';
        }
        //主要用于判断是否那修改此调数据
        public AddressData(Address__c record,String disCanEdit,String disCanCopy,String canAdopt) {
            address = record;
            canEdit = disCanEdit;
            canCopy = disCanCopy;
            canAdopt = canAdopt;
        }
        //主要是用于第一行展示和复选框是否显示
        public AddressData(Account record,String disCanEdit,String disCanCopy,String disCanAdopt,String AccType) {
            this.address = new Address__c(
                Address_Classification__c = AccType,
                Customer__c= record.id,
                Telephone__c = record.phone,
                Province__c = record.State_Master__c,
                City__c = record.City_Master__c,
                Detailed_Address__c = record.Address__c);
            canEdit = disCanEdit;
            canCopy = disCanCopy;
            canAdopt = disCanAdopt;
        }
    }
}