public with sharing class StraightBackAddressControllerX {
    /**
     * 页面顶部检索数据
     */
    public String numtextA1 { get; set; } //第一个下拉列表
    public List<SelectOption> optionType { get; set; } //类型
    public String txtName{get;set;}//客户名
    public String txtAddress{get;set;}//地址

    /***************表格数据*********************/
    public List<AddressData> tableData { get; set; }

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

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

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

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

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

    /***************修理单的收货地址id*********************/
    public String Repair_Address_ID{get;set;}

    public StraightBackAddressControllerX() {
        //获取url数据
        RepairId = System.currentPageReference().getParameters().get('id');
        /**
         * 初始化搜索框
         */
        numtextA1 = '医院';
        optionType = new List<SelectOption>();
        optionType.add(new SelectOption('医院', '医院'));
        optionType.add(new SelectOption('办事处', '办事处'));
        optionType.add(new SelectOption('经销商', '经销商'));

        //table 数据
        tableData = new List<AddressData>();
        insUpdData = new Address__c();
        UpdId = '';
        adoptId = '';
        Repair_Address_ID = '';
        addContact = new Contact();
    }

    /**
     * 开始方法
     */
    public PageReference init(){
        searchBtn();

        /*tableData = new List<AddressData>();
        try{
            //获取修理单的数据
            String RepairSql = makeTextRepairSql(RepairId);
            Repair__c pc = Database.query(RepairSql);

            //获取地址信息
            String AddressSql = makeTextAddressSql(pc.HP_ID__c,pc.Dealer__c);
            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]));
                }
            }
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '共有 '+dataList.size()+' 条数据'));
        }catch(Exception e){
            //失败提示
            ApexPages.addMessages(e);
        }
        */
        insUpdData = new Address__c();
        return null;
    }

    //编辑获取数据
    public PageReference onEditor(){
        if(!String.isBlank(UpdId)){
            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;
                }
            }
        }
        return null;
    }
    public PageReference onCopy(){
        if('空'.equals(UpdId)){//如果为空，那么证明当前数据为第一行数据
            insUpdData = new Address__c();
            insUpdData = tableData[0].address.clone();
        }else{
            if(!String.isBlank(UpdId)){
                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设为空
                    }
                }
            }
        }
        return null;
    }
    //采用按钮 保存放大
    public PageReference adoptSave(){
        //需求变动
        if(!String.isBlank(adoptId)){
            for(Integer i = 0;i<tableData.size();i++){
                ID oldid = tableData[i].address.id;
                if(oldid == adoptId){
                    String oldType = tableData[i].address.Address_Classification__c;
                    if(oldType == '医院'){
                        //由于在account表中，地址字段是一个公式，所以这里要做处理
                        //把详细地址里面的省和市去掉，然后把剩下的值赋给街道字段
                        String province = '';
                        String City = '';
                        String Address = '';
                        Address = Address.replace(province,'');
                        Address = Address.replace(City,'');

                    }else if(oldType == '办事处'){
                        
                    }else if(oldType == '经销商'){
                        
                    }
                }
            }
        }
        return redirectPag();
    }

    //重定向到 修理页面
    public PageReference redirectPag(){
        PageReference ref = new Pagereference('/' + RepairId);
        ref.setRedirect(true);
        return ref;
    }

    /**
     * 检索数据查询
     */
    public void searchBtn(){
        integer indexCou = 0;
        tableData = new List<AddressData>();
        String RepairSql = makeTextRepairSql(RepairId);
        try{
            Repair__c pc = Database.query(RepairSql);
            //由于如果查询条件为类型中的任意一个，那么他需要查询到修理表上对应的数据，放到列表的第一行
            if(!String.isBlank(numtextA1)){
                if('医院'.equals(numtextA1) && pc.HP_ID__c != null){
                    //查询医院  
                    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','医院'));
                    }
                }
                //办事处  待开发
                if('办事处'.equals(numtextA1)){
                    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','办事处'));
                        }
                    }
                }
                if('经销商'.equals(numtextA1) && pc.Dealer__c != null){
                    //查询经销商 
                    String AccountSql = makeTextAccountSql(pc.Dealer__c);
                    //获取地址信息
                    List<Account>  accoutList = Database.query(AccountSql);
                    if(accoutList != null && accoutList.size() > 0){//防止一条也没查到
                        indexCou++;
                        tableData.add(new AddressData(accoutList[0],'none','经销商'));
                    }
                }
            }
            //获取地址信息
            String AddressSql = makeTextAddressSql(pc.HP_ID__c,pc.Dealer__c);
            List<Address__c> dataList = Database.query(AddressSql);
            if(dataList != null && dataList.size()> 0){
                indexCou += dataList.size();
                for(Integer i = 0;i<dataList.size();i++){
                    tableData.add(new AddressData(dataList[i]));
                }
            }
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '共有 '+indexCou+' 条数据'));
        }catch(Exception e){
            //失败提示
            ApexPages.addMessages(e);
        }
    }
    //查询修理表数据
    private String makeTextRepairSql(String uuid){
        String RepairSql = 'SELECT ID,NAME,Address_ID__c,HP_ID__c,Dealer__c FROM Repair__c where id = \''+RepairId+'\'';
        return RepairSql;
    }
    //查询地址表数据
    //HPID  医院id     DeslerC  经销商id    Whether_Office__c  是否为办事处
    private String makeTextAddressSql(String HPID,String DeslerC) {
        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';
        //类型查询
        if(!String.isBlank(numtextA1)){
            if('医院'.equals(numtextA1)){
                AddressSql += ' and Contacts__r.accountid = \'' + HPID + '\' and Address_Classification__c LIKE \'%' + numtextA1.trim() + '%\'' ;
            }
            if('办事处'.equals(numtextA1)){
                AddressSql += ' and Customer__r.Whether_Office__c = true and Address_Classification__c LIKE \'%' + numtextA1.trim() + '%\'' ;
            }
            if('经销商'.equals(numtextA1)){
                AddressSql += ' and Contacts__r.AccountId = \'' + DeslerC + '\' and Address_Classification__c LIKE \'%' + numtextA1.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() + '%\'' ;
        }

        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,Whether_Office__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 makeTextAccOfficeSql(){
        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(txtName)){
            AccountOfficeSql += ' and Name LIKE \'%' + txtName.trim() + '%\'' ;
        }
        if(!String.isBlank(txtAddress)){
            AccountOfficeSql += ' and Address__c LIKE \'%' + txtAddress.trim() + '%\'' ;
        }
        return AccountOfficeSql;
    }

    /**
     * 保存和修改的方法
     */
    public PageReference save(){
        if(insUpdData != null){
            boolean flag = true;
            //判断联系人是否都为空
            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{//如果联系人为空，并且新建联系人不为空，那么新增一条联系人数据
                    String typeL = '';//类型
                    String customerName = '';//客户名称
                    //判断类型是否为空
                    if(!String.isBlank(insUpdData.Address_Classification__c)){
                        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();
                        }
                    }else{
                        flag = false;
                        this.insUpdData.Address_Classification__c.addError('【类型】不能为空！');
                    }
                    if(String.isBlank(String.valueOf(insUpdData.Customer__c))){
                        flag = false;
                        this.insUpdData.Customer__c.addError('【客户】 不能为空！');
                    }
                    if(flag){
                        addContact = new Contact(LastName=insUpdData.Create_Contacts__c,AccountId=insUpdData.Customer__c,RecordTypeId=typeL);
                        try{
                            //新增一条联系人数据
                            insert addContact;
                        }catch(Exception e){
                            //失败提示
                            ApexPages.addMessages(e);
                        }
                        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;
                        }*/
                    }
                }
            }
            if(flag){
                try{
                //新增或修改数据
                    upsert insUpdData;
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '保存成功！'));
                    //保存成功，需要初始化一下此对象，防止点击此按钮再次保存一个条同样的数据
                    insUpdData = new Address__c();
                }catch(Exception e){
                    //失败提示
                    ApexPages.addMessages(e);
                }
            }
        }
        return null;
    }


    /**
     * 为了方便前段table获取值
     */
    class AddressData {
        //数据
        public Address__c address { get; set; }
        //编辑按钮是否展示
        public String canEdit { get; private set; }
        public Boolean hasError { get; private set; }
        public Boolean hasFieldError { get; private set; }
        public Integer lineNo { get; private set; }
        public String changeFlg { get; set; }
        public String reasonFlg { get; set; }
        //复选框id值
        public String chk { get;set; }
        
        public AddressData(Address__c record) {
            address = record;
            canEdit = '';
            hasError = false;
            hasFieldError = false;
            lineNo = 0;
            changeFlg = '0';
            reasonFlg = '0';
            chk = 'chk'+lineNo;
        }
        //主要是用于第一个展示和复选框是否显示
        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;
            hasError = false;
            hasFieldError = false;
            lineNo = 0;
            changeFlg = '0';
            reasonFlg = '0';
            chk = 'chk'+lineNo;
        }
    }
}