public with sharing class LostSingleController {
    public LostSingleController() {

    }

    // 获取已保存的询价信息 LostProductDatas LostCompanyDatas productlist
    @AuraEnabled
    public  static string GetLostDataList(String LostId) {
      

      String sqlLost = 'select ';
      sqlLost += CommonUtils.GetSqlToPorps(PCLLostBrand__c.SObjectType);
      sqlLost += ' from PCLLostBrand__c';
      sqlLost += ' where Lost_cancel_report__c = :LostId';
      List<PCLLostBrand__c> arrays = Database.query(sqlLost);

      if (arrays == null && arrays.size() <= 0) {
          return '[]';
      }
      List<LostDataView> brandList = new List<LostDataView>();
      for (PCLLostBrand__c brand : arrays) {
        LostDataView view = new LostDataView();
        view.brand =brand;


        String BrandID = brand.Id;
        String sqlProduct = 'select ';
        sqlProduct += CommonUtils.GetSqlToPorps(PCLLostProduct__c.SObjectType);
        sqlProduct += ' from PCLLostProduct__c';
        sqlProduct += ' where PCLLostBrand__c = :BrandID';
        List<PCLLostProduct__c> productArrays = Database.query(sqlProduct);

        view.productList = productArrays;

        brandList.add(view);

      }
      return JSON.serialize(brandList); 
    }

    public class LostDataView
    {
        public PCLLostBrand__c brand;
        public List<PCLLostProduct__c> productList;

    }
    //获取 中标经销
    @AuraEnabled
    public  static string GetZBJS(String content) {
        // select id, name from account where recordtype.developername ='Agency'
      String parem1 = 'Agency';
      String sql = 'select ';
      sql += CommonUtils.GetSqlToPorps(account.SObjectType);
      sql += ' from account';
      sql += ' where recordtype.developername = :parem1';
      if(content != null && content != '' && content != ' ')
      {
          content = '%'+content+'%';
        sql += ' and Name like :content';
      }
      sql += ' limit 5';
      List<account> arrays = Database.query(sql);
      return JSON.serialize(arrays); 
    }
    

    //获取 产品
    //SELECT Id FROM product2 where Category5__c = '竞争对手' and Brand_Name__c != '奥林巴斯' limit 100
    @AuraEnabled
    public  static string GetProduct2Datas(String Name,String ProductCode,String Description ) {
        // select id, name from account where recordtype.developername ='Agency'
        String parem1 = '竞争对手';
        String parem2 = '奥林巴斯';
        String sql = 'select ';
        sql += CommonUtils.GetSqlToPorps(Product2.SObjectType);
        sql += ' from Product2';
        sql += ' where Category5__c = :parem1';
        sql += ' and Brand_Name__c != :parem2';

        if(Name != null && Name != '')
        {
            sql += ' and Name = :Name';
        }

        if(ProductCode != null && ProductCode != '')
        {
            sql += ' and ProductCode = :ProductCode';
        }


        if(Description != null && Description != '')
        {
            sql += ' and Description = :Description';
        }

        sql += ' limit 100';
        List<Product2> arrays = Database.query(sql);
        return JSON.serialize(arrays); 
    }
      

    ///获取失单品牌
    @AuraEnabled
    public  static string GetSDPP(){
        String JsonData = CommonUtils.GetSelectedValues(Lost_cancel_report__c.Lost_By_Company__c.getDescribe());
        return JsonData;
    }

     ///获取失单原因主
     @AuraEnabled
     public  static string GetSDYYZ(){
         String JsonData = CommonUtils.GetSelectedValues(Lost_cancel_report__c.Lost_reason_main__c.getDescribe());
         return JsonData;
     }

    ///获取失单原因次
    @AuraEnabled
    public  static string GetSDYYC(){
        String JsonData = CommonUtils.GetSelectedValues(Lost_cancel_report__c.Lost_Reason_Sub__c.getDescribe());
        return JsonData;
    }


     //失单
     public class LostData {
        String Id;
        String Opportunity;//询价ID
        String Salesassistant;  //询价助理ID
        String Buchangsales;  //销售担当
        String LostByCompany;  //失单对手名
        String LostByCompanyTxt;  //失单公司(手写)
        String LostReasonmain;  //第一个品牌的失单理由
        String LostReasonSub;  //第一个品牌的失单理由
        String LostType; //失单类型
        Integer systemprocessor;  //失单主机台数

        public Lost_cancel_report__c getLostCancel()
        {
            Lost_cancel_report__c temp =  new Lost_cancel_report__c();
            temp.Opportunity__c = this.Opportunity;
            temp.Sales_assistant__c = this.Salesassistant;
            temp.Buchang_sales__c = this.Buchangsales;
            temp.Submit_Day__c =Date.today();
            temp.Lost_By_Company__c = this.LostByCompany;
            temp.Lost_By_Company_Others__c = this.LostByCompanyTxt;
            temp.Lost_reason_main__c = this.LostReasonmain;
            temp.Lost_Reason_Sub__c = this.LostReasonSub;
            temp.of_lost_system_processor__c = this.systemprocessor;
            temp.LostType__c = this.LostType;

            return temp;
        }

        public Lost_cancel_report__c getLostCancelUpdate()
        {
            Lost_cancel_report__c temp =  new Lost_cancel_report__c();
            temp.Opportunity__c = this.Opportunity;
            temp.Sales_assistant__c = this.Salesassistant;
            temp.Buchang_sales__c = this.Buchangsales;
            temp.Submit_Day__c =Date.today();
            temp.Lost_By_Company__c = this.LostByCompany;
            temp.Lost_By_Company_Others__c = this.LostByCompanyTxt;
            temp.Lost_reason_main__c = this.LostReasonmain;
            temp.Lost_Reason_Sub__c = this.LostReasonSub;
            temp.of_lost_system_processor__c = this.systemprocessor;
            temp.LostType__c = this.LostType;
            temp.Id = this.Id;
            return temp;
        }
  
     }


     //失单品牌
     public  class LostCompanyDatas {
         public String Id;
         public Integer LostPrice; //失单金额（元）
         public string LostCompany; //失单品牌
         public string LostCompanyTxt; //失单品牌（手动）
         public string LostReasonmain; //失单理由(主)
         public string LostReasonSub; //失单理由(副)
         public string LostAgency; //中标经销商
         public string LostCancelreport;//询价失单/取消报告
         public string LostClass; //失单类别
         public string LostCategory; //失单产品
        //  public LostDatas(string label, string value) {
        //      this.label = label;
        //      this.value = value;
        //  }
        public PCLLostBrand__c getBrand()
        {
            PCLLostBrand__c temp =  new PCLLostBrand__c();
            temp.LostPrice__c = this.LostPrice;
            temp.Lost_By_Company__c = this.LostCompany;
            // temp.ProductClass__c = this.LostClass;
            // temp.ProductCategory__c = this.LostCategory;
            //temp.Lost_By_Company_Txt__c =this.LostCompanyTxt;
            temp.Lost_reason_main__c = this.LostReasonmain;
            temp.Lost_Reason_Sub__c = this.LostReasonSub;
            temp.Lost_reason_main__c = this.LostReasonmain;
            temp.Agency__c = this.LostAgency;
            return temp;
        }

        public PCLLostBrand__c getBrandUpdate()
        {
            PCLLostBrand__c temp =  new PCLLostBrand__c();
            temp.LostPrice__c = this.LostPrice;
            temp.Lost_By_Company__c = this.LostCompany;
            // temp.ProductClass__c = this.LostClass;
            // temp.ProductCategory__c = this.LostCategory;
            //temp.Lost_By_Company_Txt__c =this.LostCompanyTxt;
            temp.Lost_reason_main__c = this.LostReasonmain;
            temp.Lost_Reason_Sub__c = this.LostReasonSub;
            temp.Lost_reason_main__c = this.LostReasonmain;
            temp.Agency__c = this.LostAgency;
            temp.Id = this.Id;
            return temp;
        }


        // public static  LostCompanyDatas setBrand(PCLLostBrand__c data,List<LostProductDatas> productList)
        // {
        //     LostCompanyDatas tempData = new LostCompanyDatas();
        //     tempData.LostPrice =   (Integer)data.LostPrice__c ;
        //     tempData.LostCompany =   data.Lost_By_Company__c ;
        //     tempData.LostCompanyTxt =   data.Lost_By_Company_Txt__c ;
        //     tempData.LostReasonmain =   data.Lost_reason_main__c ;
        //     tempData.LostReasonSub =   data.Lost_Reason_Sub__c ;
        //     tempData.LostReasonmain =   data.Lost_reason_main__c ;
        //     tempData.LostAgency  =   data.Agency__c ;
        //     tempData.productlist = productList;
        //     return tempData;
        // }
         public List<LostProductDatas> productlist;
     }


     //失单型号
     public class LostProductDatas {
         public string LostProduct; //失单型号
         public string LostProductTxt; //失单型号（手动）
         public Integer Quantity; //失单数量
         public Boolean IsSD ; //是否选中
         public string Id;

        //  public string PCLLostBrand; //询价失单品牌

        public PCLLostProduct__c getProduct()
        {
            PCLLostProduct__c temp =  new PCLLostProduct__c();
            temp.LostProduct__c = this.LostProduct;
            // temp.LostProductName__c =LostCompanyTxt;
            //temp.LostProductTxt__c = this.LostProductTxt;
            temp.Quantity__c = this.Quantity;
           // temp.IsMannual__c = this.IsSD;
            return temp;
        }

        
        public PCLLostProduct__c getProductUpdate()
        {
            PCLLostProduct__c temp =  new PCLLostProduct__c();
            temp.LostProduct__c = this.LostProduct;
            // temp.LostProductName__c =LostCompanyTxt;
            //temp.LostProductTxt__c = this.LostProductTxt;
            temp.Quantity__c = this.Quantity;
            //temp.IsMannual__c = this.IsSD;
            temp.Id = this.Id;
            return temp;
        }
   
     }

   //查询询价根据ID 
    @AuraEnabled
    public  static string GetOpportunityById(String XJID) {
        // XJID = '0061000000hr5x6AAA';
        QueryWrapper query = new QueryWrapper(Opportunity.SObjectType);
        query.eq('Id', XJID);
        List<Opportunity> arrays = DataBasePlus.listPlus(query);
        return JSON.serialize(arrays);
    }

    
   //查询询价根据ID 
   @AuraEnabled
   public  static string GetLostCancelById(String Id) {
       // XJID = '0061000000hr5x6AAA';
       QueryWrapper query = new QueryWrapper(Lost_cancel_report__c.SObjectType);
       query.eq('Id', Id);
       List<Lost_cancel_report__c> arrays = DataBasePlus.listPlus(query);
       return JSON.serialize(arrays);
   }


    //获取 保存
    @AuraEnabled
    public  static string SaveProduct(String LostDataJSON,String LostCompanyDatasJSON) {
        Savepoint sp = Database.setSavepoint();
        try{
            List<LostData> LostDataList = (List<LostData>)JSON.deserialize(LostDataJSON,List<LostData>.class);
            Lost_cancel_report__c tempLostCancel = LostDataList[0].getLostCancel();
            insert tempLostCancel;

            List<LostCompanyDatas> LostCompanyDatasLists = (List<LostCompanyDatas>)JSON.deserialize(LostCompanyDatasJSON,List<LostCompanyDatas>.class);
            for (LostCompanyDatas  company :  LostCompanyDatasLists )
            {
                PCLLostBrand__c brandTemp = company.getBrand();
                brandTemp.Lost_cancel_report__c = tempLostCancel.Id;
                insert brandTemp;
                for (LostProductDatas pro : company.productlist) {
                    PCLLostProduct__c proTemp =  pro.getProduct();
                    proTemp.PCLLostBrand__c = brandTemp.Id;
                    insert proTemp;
                }
                
            }
            return '成功';
            // insert tempLostCancel;
    
        }catch(Exception ex)
        {
          Database.rollback(sp);
           return  ex.getMessage();
        } 
    }

     //获取 保存
     @AuraEnabled
     public  static string UpdateProduct(String LostDataJSON,String LostCompanyDatasJSON) {
        Savepoint sp = Database.setSavepoint();
         try{
             List<LostData> LostDataList = (List<LostData>)JSON.deserialize(LostDataJSON,List<LostData>.class);
             Lost_cancel_report__c tempLostCancel = LostDataList[0].getLostCancelUpdate();
             update tempLostCancel;
 
             List<LostCompanyDatas> LostCompanyDatasLists = (List<LostCompanyDatas>)JSON.deserialize(LostCompanyDatasJSON,List<LostCompanyDatas>.class);
             for (LostCompanyDatas  company :  LostCompanyDatasLists )
             {
                 PCLLostBrand__c brandTemp = company.getBrandUpdate();
                 // 删除逻辑
                 if(brandTemp.Id != null && (brandTemp.Lost_By_Company__c == null || brandTemp.Lost_By_Company__c == ''))
                 {
                    DeleteBrand(brandTemp.Id);
                    continue;
                 }
                 //新增逻辑
                 if(brandTemp.Id == null )
                 {
                    brandTemp.Lost_cancel_report__c = tempLostCancel.Id;
                    insert brandTemp;
                    for (LostProductDatas pro : company.productlist) {
                        PCLLostProduct__c proTemp =  pro.getProduct();
                        proTemp.PCLLostBrand__c = brandTemp.Id;
                        insert proTemp;
                    }
                    continue;
                 }

                //  brandTemp.Lost_cancel_report__c = tempLostCancel.Id;
                 update brandTemp;
                 for (LostProductDatas pro : company.productlist) {
                     PCLLostProduct__c proTemp =  pro.getProductUpdate();
                     if(proTemp.Id != null && (proTemp.Quantity__c == null || proTemp.Quantity__c == 0) &&  (proTemp.LostProduct__c == null || proTemp.LostProduct__c == '') )
                     {
                        DeleteProducet(proTemp.Id);
                        continue;
                     }

                     if(proTemp.Id == null )
                     {
                        proTemp.PCLLostBrand__c = brandTemp.Id;
                        insert proTemp;
                        continue;
                     }
                    //  proTemp.PCLLostBrand__c = brandTemp.Id;
                     update proTemp;
                 }
                 
             }
             return '成功';     
         }catch(Exception ex)
         {
            Database.rollback(sp);
            return  ex.getMessage();
         } 
     }


     public static void DeleteBrand(string brandId)
     {
         string sql = 'select Id from PCLLostBrand__c where Id = :brandId';
         List<PCLLostBrand__c> arrays = Database.query(sql);
        if(arrays.size() > 0)
        {
            Database.delete(arrays,false);
        }
         sql = 'select Id from PCLLostProduct__c where PCLLostBrand__c = :brandId';
        List<PCLLostProduct__c> proarrays = Database.query(sql);
        if(proarrays.size() > 0)
        {
            Database.delete(proarrays,false);
        }

     }

     public static void DeleteProducet(string proId)
     {
         String sql = 'select Id from PCLLostProduct__c where Id = :proId';
        List<PCLLostProduct__c> proarrays = Database.query(sql);
        if(proarrays.size() > 0)
        {
            Database.delete(proarrays,false);
        }

     }
    

}