public with sharing class DIrectReturnToReceivingAddressController {

    //第一个下拉列表
    public String type { get; set; } 

    //类型
    public static List<SelectOption> optionType { get; set; } 

    //客户名
    public String customerName{get;set;}

    //地址
    public String testAddress{get;set;}

    //地址搜索对象
    public List<AddressData> tableData { get; set; }

    //新建地址对象
    public Address__c insUpdData{get;set;}
    
    //联系人对象
    public Contact addContact{get;set;}
    
    //修理跳转页面携带的ID
    public String RepairId{get;set;}
    
    //点击编辑时候选中数据的ID
    public String UpdId{get;set;}

    //科室类型
    public String DepartmentType{get;set;}

    //复制和编辑方法选中携带的id
    public String uuid{get;set;}

    //采用按钮的ID
    public String uuid2{get;set;}

    //修理表对象
    public Repair__c repairC{get;set;}

    //设备表ID
    public String equipmentModelId{get;set;}

    //设备表对象
    public Asset asset{get;set;}

  static{

        //类型  下拉选
        optionType = new List<SelectOption>();
        optionType.add(new SelectOption('医院', '医院'));
        optionType.add(new SelectOption('办事处', '办事处'));
        optionType.add(new SelectOption('经销商', '经销商'));
  }

    //通过构造初始化方法调用
    public DIrectReturnToReceivingAddressController() {

        //从地址栏获取修理页面跳转的时候携带的ID
         RepairId = System.currentPageReference().getParameters().get('id');

        //地址搜索数据
        tableData = new List<AddressData>();

        //新建地址对象
        insUpdData = new Address__c();

        //修理表对象
        repairC = new Repair__c();
         
        //点击编辑的时候选中数据的ID
         UpdId = '';

        //下拉列表的
         type='医院';
        
        //地址对象
         testAddress='';
        
        //联系人对象
        addContact = new Contact();

        //复制和编辑方法选中携带的id
        uuid = '';

        //采用按钮的ID
        uuid2 = '';

        //科室类型
        DepartmentType = '';

        //设备表ID
        equipmentModelId = '';

        //设备表对象
        asset = new Asset();


        

       

    }
    

    //   开始方法  init();
    public PageReference init(){
         String RepairSql = RepairTest(RepairId);
           Repair__c repair = Database.query(RepairSql);
            //获取修理表上的保有设备id
            if(!String.isBlank(repair.Delivered_Product__c)){
                equipmentModelId = repair.Delivered_Product__c;
            }
            search();
            insUpdData = new Address__c();
            return null;
    }

    //返回修理页面
     public PageReference repairPage(){
        PageReference page = new Pagereference('/' + RepairId);
        page.setRedirect(true);
        return page;
    }
 

    //保存按钮的功能实现
    public PageReference save(){  
        if(insUpdData != null){
            boolean flag = true;
            //客户不能为空
            if(String.isBlank(String.valueOf(insUpdData.Customer__c))){
                flag = false;
                this.insUpdData.Customer__c.addError('不能为空！');
            }else{
                //如果类型为医院，那么客户字段必须选择科室
                if(insUpdData.Address_Classification__c == '医院'){
                    String customerc = insUpdData.Customer__c;
                    String AccSQl = newAddress(customerc);
                    List<Account> AccList = new List<Account>();
                    try{
                        AccList = Database.query(AccSQl);
                    }catch(exception e){
                        //失败提示
                        ApexPages.addMessages(e);
                    }
                    if(AccList != null && AccList.size() > 0){
                        for(Integer i = 0;i<AccList.size();i++){
                           String recordType = AccList[i].RecordType.name;
                           if(!DepartmentType.contains(recordType)){
                                flag = false;
                                this.insUpdData.Customer__c.addError('必须选具体科室！');
                           }
                        }
                    }
                }
            }
            //判断联系人是否都为空
            if(insUpdData.Contacts__c == null || String.isBlank(insUpdData.Contacts__c)){
                if(insUpdData.Create_Contacts__c == null || String.isBlank(insUpdData.Create_Contacts__c)){
                    flag = false;
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,  '如果【联系人】为空，那么【联系人（新建）】 不能为空！'));
                }else{
                   addContact = new Contact(LastName=insUpdData.Create_Contacts__c,AccountId=insUpdData.Customer__c);
                        //新增一条联系人数据
                        insert addContact;
                        insUpdData.Contacts__c = addContact.id; 
                    }

                }

            if (flag) {
                try{
                //新增或修改数据
                    if(!Test.isRunningTest()){
                        upsert insUpdData;
                    }
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '保存成功！'));
                }catch(Exception e){
                    //失败提示
                    ApexPages.addMessages(e);
                }
                
            } 
        }
         insUpdData = new Address__c();

             return null;
    }

    //编辑按钮的方法实现
    public PageReference edit(){      
      if(!String.isBlank(uuid)){
        if (tableData != null && tableData.size()>0) {
            insUpdData = new Address__c();
            ID newId = ID.valueof(uuid);
            for (Integer i = 0; i < tableData.size(); i++ ) {
                ID oldid = tableData[i].address.id;
                    if(oldid == newId){
                        insUpdData = tableData[i].address;
                    }
            }

        }
        
      }

      return null;
    }


    //复制按钮方法的实现
    public PageReference copy(){
         if(!String.isBlank(uuid)){
            if (tableData != null && tableData.size()>0) {
                if (''.equals(uuid)) {
                    insUpdData = new Address__c();
                    tableData[0].address.clone();
                }else{
                        //创建新建地址对象(空对象)
                        insUpdData = new Address__c();
                        ID newId = ID.valueof(uuid);
                       //遍历sql查出来的数据  复制给新建地址对象
                       for (Integer i = 0; i < tableData.size(); i++ ) {
                            ID oldId = tableData[i].address.id;
                            if (oldId == newId) {
                                insUpdData = tableData[i].address.clone();
                                 //由于是复制，是需要insert的操作，所以把id设为空
                                 insUpdData.id = null;
                            }
                            
                        }
                }
            }
        }


      return null;

    }

    

    //搜索按钮方法的实现
    public void search(){
        tableData = new List<AddressData>();
         //获取修理单的数据
        System.debug('=========================='+type);
            String RepairSql = RepairTest(RepairId);
            Repair__c repair = Database.query(RepairSql);  
            String hospitalDealer = '';
            //由于如果查询条件为类型中的任意一个，那么他需要查询到修理表上对应的数据，放到列表的第一行 然后在放详细的科室信息
            if(!String.isBlank(type)){
                if('医院'.equals(type) && repair.HP_ID__c != null){
                    hospitalDealer = repair.HP_ID__c;
                    //查询医院  
                    String AccountSql = hospitalsAndDistributorsSql(hospitalDealer);
                    //获取地址信息
                    List<Account> accoutList = Database.query(AccountSql);
                    if(accoutList != null && accoutList.size() > 0){      
                        tableData.add(new AddressData(accoutList[0],'none','医院'));
                    }
                }
                //办事处
                if('办事处'.equals(type)){
                    String AccountOfficeSql = OfficeSql();
                    //获取地址信息
                    List<Account> accDataList = Database.query(AccountOfficeSql);
                    if(accDataList != null && accDataList.size() > 0){
                        for(Integer i = 0;i<accDataList.size();i++){                          
                            tableData.add(new AddressData(accDataList[i],'none','办事处'));
                        }
                    }
                }
                if('经销商'.equals(type) && repair.Dealer__c != null){
                    hospitalDealer = repair.Dealer__c;
                    //查询经销商 
                    String AccountSql = hospitalsAndDistributorsSql(hospitalDealer);
                    //获取地址信息
                    List<Account>  accoutList = Database.query(AccountSql);
                    if(accoutList != null && accoutList.size() > 0){//防止一条也没查到
                        tableData.add(new AddressData(accoutList[0],'none','经销商'));
                    }
                }
            }
            
             String AddressSql = ReceivingAddress(hospitalDealer);
               List<Address__c> dataList = Database.query(AddressSql);
                if(dataList != null && dataList.size()> 0){
                    for(Integer i = 0;i<dataList.size();i++){
                        tableData.add(new AddressData(dataList[i]));
                    }
                }   
        }  

    //采用按钮
    public PageReference methodsAdopted(){
        repairC = new Repair__c();
        asset = new Asset();
        if (!String.isBlank(uuid2)) {
            if (tableData != null && tableData.size() > 0) {
                for (Integer i = 0;i < tableData.size();i++) {
                    ID oldid = tableData[i].address.id;
                    if(oldid == uuid2){
                      String contactsName = '';
                      if(!String.isBlank(tableData[i].address.Contacts__c)){
                        contactsName = tableData[i].address.Contacts__r.Name;
                      }                 
                      repairC.id = RepairId;
                      repairC.address_Contacts__c = contactsName;
                      repairC.address_Telephone__c = tableData[i].address.Telephone__c;
                      repairC.Detailed_Address__c = tableData[i].address.Detailed_Address__c;
                      if(!Test.isRunningTest()){
                        update repairC;
                      }
                      System.debug('=====================++++++++++++++++='+equipmentModelId);
                      

                      asset.id = equipmentModelId;
                      asset.address_Contacts__c = contactsName;
                      asset.address_Telephone__c = tableData[i].address.Telephone__c;
                      asset.Detailed_Address__c = tableData[i].address.Detailed_Address__c;
                      if(!Test.isRunningTest()){
                        update asset;
                      }      
                      return repairPage();
                    }
                }
            }
        }
        
        return null;
    }
            

    //修理表的数据
     private String RepairTest(String RepairId){
        String RepairSql = 'SELECT ID,NAME,HP_ID__c,Dealer__c,Delivered_Product__c FROM Repair__c where id = \''+ RepairId +'\'';
        return RepairSql;
    }

    //收货地址表的数据
    private String ReceivingAddress(String hospitalDealer) {
        //sql语句用来查询出数据
        String AddressSql = 'SELECT ID,Address_Classification__c,Customer__c,Customer__r.Name,Contacts__c,Contacts__r.Name,Telephone__c'
                        +',Province__c,Province__r.Name,City__c,City__r.name,Detailed_Address__c,Create_Contacts__c '
                        + ' FROM Address__c where id != null';
        // Contacts__r.accountId =  \'' + HPIDC + '\'

        //判断类型
        if(!String.isBlank(type)){
          if('医院'.equals(type)){
                if(!String.isBlank(hospitalDealer)){
                    AddressSql += ' and Hospital__c = \'' + hospitalDealer + '\'  and Address_Classification__c LIKE \'%' + type.trim() + '%\'';
                }else{
                    //如果修理表的医院为空，那么查询地址表 前200条的医院地址
                    AddressSql += ' and Address_Classification__c LIKE \'%' + type.trim() + '%\'  limit 200' ;
                }
            }
            if('办事处'.equals(type)){
                AddressSql += ' and Customer__r.Whether_Office__c = true and Address_Classification__c LIKE \'%' + type.trim() + '%\'' ;
            }
            if('经销商'.equals(type)){
                if(!String.isBlank(hospitalDealer)){
                    AddressSql += ' and Contacts__r.AccountId = \'' + hospitalDealer + '\'  and Address_Classification__c LIKE \'%' + type.trim() + '%\'';
                }else{
                   //如果修理表的经销商为空，那么查询地址表 前200条的经销商地址
                    AddressSql += ' and Address_Classification__c LIKE \'%' + type.trim() + '%\' limit 200' ;
                }
            }
            
        }

         //判断客户名
        if (!String.isBlank(customerName)) {
            AddressSql += ' and Customer__r.Name LIKE \'%' + customerName.trim() + '%\'';
        }

         //判断地址
        if (!String.isBlank(testAddress)) {
            AddressSql += ' and Detailed_Address__c LIKE \'%' + testAddress.trim() + '%\'';
        }

        return AddressSql;
      
    }
    //查询医院和经销商客户人员信息
    private String hospitalsAndDistributorsSql(String afferentId){
        String AccountSql = 'SELECT ID,NAME,Phone,State_Master__c,State_Master__r.name,City_Master__c,City_Master__r.name,Address__c,Whether_Office__c '
                            + ' FROM Account WHERE ID = \'' + afferentId + '\'';
        if(!String.isBlank(customerName)){
            AccountSql += ' and Name LIKE \'%' + customerName.trim() + '%\'' ;
        }
        if(!String.isBlank(testAddress)){
            AccountSql += ' and Address__c LIKE \'%' + testAddress.trim() + '%\'' ;
        }
        return AccountSql;
    }

    //查询办事处信息
    private String OfficeSql(){
        String AccountOfficeSql = 'SELECT ID,NAME,Phone,State_Master__c,State_Master__r.name,City_Master__c,City_Master__r.name,Address__c,Whether_Office__c '
                            +' FROM Account WHERE Whether_Office__c = true';
        if(!String.isBlank(customerName)){
            AccountOfficeSql += ' and Name LIKE \'%' + customerName.trim() + '%\'' ;
        }
        if(!String.isBlank(testAddress)){
            AccountOfficeSql += ' and Address__c LIKE \'%' + testAddress.trim() + '%\'' ;
        }
        return AccountOfficeSql;
    }

    //获取新建地址表的所有数据
    private String newAddress(String afferentId){
        String AccountSql = 'SELECT ID,NAME,Phone,State_Master__c,State_Master__r.name,City_Master__c,City_Master__r.name,Address__c,'
                        + 'Whether_Office__c,RecordType.name FROM Account WHERE ID = \'' + afferentId + '\'';
        return AccountSql;
    }

    //查询医院下科室的类型
    private String departmentsSql(){
        String RecordTypeSQl = 'SELECT ID,NAME,sobjecttype from RecordType where sobjecttype = \'account\' and name like \'診療科%\'';
        return RecordTypeSQl;
    }


    // 为了方便前段table获取值
    class AddressData {
        public Address__c address { get; set; }
        public String canEdit { get; private set; }
        
        
        public AddressData(Address__c record) {
            address = record;
            canEdit = '';
           
        }

         //主要是用于第一个展示和复选框是否显示
        public AddressData(Account record,String disCanEdit,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;
            
        }
    }
}