public with sharing class OrdergoodsController {
    public List < productInfo > productInfoList { get; set;}
    public Sample_order_list__c sampleOrder { get; set;} // 订货单
    public Account AccName { get; set; } // 办事处名称
    public Integer tempSize { get { return productInfoList == null ? 0 : productInfoList.size(); } } // 产品数量
    //public Integer rowIdx { get; set;} //20211103 lt 增加行
    //public Boolean displayFlg { get; set; } //20211103 lt 增加行
    public String accId { get; set; } //add fxk客户Id
    public String orderListId { get; set; } //add fxk订货单Id
    public Boolean errormessageFlg = false;
    private List <Sample_order_list_detail__c> orderListDelList;
    public String QueryTemp { get; set;}
    public String provinceName{get; set;}
    public String cityName{get; set;}
    // add fxk
    // public OrdergoodsController() {cityops
    //     accId = ApexPages.currentPage().getParameters().get('accId');
    //     orderListId = ApexPages.currentPage().getParameters().get('Id');
    // }
    public OrdergoodsController(ApexPages.StandardController controller) {
        accId = ApexPages.currentPage().getParameters().get('accId');
        orderListId = ApexPages.currentPage().getParameters().get('Id');
    }

    //省
    public List<SelectOption> getprovinceop(){
        List<SelectOption> provincesops = new List<SelectOption>();
        List<Address_Level__c> provinces=[select name,id from Address_Level__c];
        // 20231027 It365needs kyb Start
        // cityops.add(new SelectOption('','----'));
        provincesops.add(new SelectOption('','--无--'));
        // 20231027 It365needs kyb End
        for(Address_Level__c province:provinces){
            provincesops.add(new SelectOption(province.Name,province.Name));
        }
        return provincesops;
    }

    //市
    public List<SelectOption> getCityop(){
        List<Address_Level__c> provinces=[select name,id from Address_Level__c where name=: provinceName];
        List<SelectOption> cityops = new List<SelectOption>();
        // 20231027 It365needs kyb Start
        // cityops.add(new SelectOption('','----'));
        cityops.add(new SelectOption('','--无--'));
        // 20231027 It365needs kyb End
        if(provinces.size()>0){
            id TheId=provinces[0].id;
            List<Address_Level2__c> citys=[select name,id from Address_Level2__c where  Address_Level__c=:TheId];
            for(Address_Level2__c city:citys){
                cityops.add(new SelectOption(city.Name,city.Name));
             } 
        }
        return cityops;
    }
  
    // add fxk 初始化显示
    public void init() {
        errormessageFlg = false;
        //displayFlg = true;
        sampleOrder = new Sample_order_list__c();
        productInfoList = new List < ProductInfo > ();
        AccName = new Account();
        // 页面获取客户名称
        if (String.isNotBlank(accId)) {
            AccName = [select Id, Name, Address__c, Phone from Account where id = : accId];
        }
        //编辑页面
        if (String.isNotBlank(orderListId)) {
            List<Sample_order_list__c> orderLists = [select Id, DeliveryAddress__c, Status__c, ReceivePart__c, DeliveryPhone__c,
                                                        DeliveryContact__c, AgentCode__c, Send_Date__c, Account__c, Account__r.Name, province__c, city__c
                                                        from Sample_order_list__c where Id = : orderListId];
            if (orderLists.size() > 0) {
                // 页面显示订货单信息
                sampleOrder = orderLists.get(0);
                provinceName = sampleOrder.province__c;
                cityName = sampleOrder.city__c;
                AccName = [select Id, Name, Address__c, Phone from Account where id = : sampleOrder.Account__c];
                orderListDelList = [select Id, Name, Pro_Name__c, Term_Date__c, Pro_model__c, Product__c, Standards__c, ItemQuantity__c, Sample_Classification__c,
                                        Total__c, TermDate__c, Product__r.Asset_Model_No__c, Product__r.Name, Product__r.SFDA_Expiration_Date__c, Product__r.Sample_Classification__c,
                                        Product__r.Packing_list_manual__c, Product__r.Id, Product__r.ProductCode, Sample_order_list__r.Status__c
                                        from Sample_order_list_detail__c where Sample_order_list__r.Id = : sampleOrder.Id];
                Integer rows = 0;
                productInfoList.clear();
                if (orderListDelList.size() > 0) {
                    for (Sample_order_list_detail__c orderDel: orderListDelList) {
                        rows++;
                        // 页面显示订货单明细
                        ProductInfo Info = new ProductInfo(rows, orderDel);
                        Info.check = true;
                        productInfoList.add(Info);
                    }
                }
                //暂存状态下进入编辑显示其他可以选择的样本品
                if(sampleOrder.Status__c == '暂存'){
                    List<Product2> sampleList = [select Id, Name, ProductCode, Packing_list_manual__c, SFDA_Expiration_Date__c, Asset_Model_No__c, Sample_Classification__c
                                                    FROM Product2 Where Whether_Sample__c = true and SFDA_Status__c != '停止'];
                    List<Product2> newSamleList = new List<Product2>();
                    //去掉已经选择的样本品,存入新的List
                    Map<String, Id> orderDelProductCodeMAp = new Map<String, Id>();
                    for(Sample_order_list_detail__c orderDel: orderListDelList){
                        orderDelProductCodeMAp.put(orderDel.Product__r.ProductCode, orderDel.Product__c);
                    }
                    for(Product2 sample : sampleList){
                        if(!orderDelProductCodeMAp.containsKey(sample.ProductCode)){
                            newSamleList.add(sample);
                        }
                    }
                    if(newSamleList.size() > 0){
                        for (Integer i = 0; i < newSamleList.size(); i++) {
                            productInfo pl = new productInfo((rows + i + 1), newSamleList[i]);
                            productInfoList.add(pl);
                        }
                    }
                } 
                System.debug('productInfoList1:' + productInfoList);
            }
        } else {
            searchHospital();
            sampleOrder.Account__c = accId;
            if(String.isNotBlank(AccName.Address__c)){
                sampleOrder.DeliveryAddress__c = AccName.Address__c;
            }
            if(String.isNotBlank(AccName.Phone)){
                sampleOrder.DeliveryPhone__c   = AccName.Phone;
            }
        }
    }
    // 初始化页面显示所有样本品 thh 2021-12-15 
    public PageReference searchHospital() {
        List<Product2> sampleList = [select Id, Name, ProductCode, Packing_list_manual__c, SFDA_Expiration_Date__c, Asset_Model_No__c, Sample_Classification__c
                                        FROM Product2 Where Whether_Sample__c = true and SFDA_Status__c != '停止'];
        for (Integer i = 0; i < sampleList.size(); i++) {
            productInfo pl = new productInfo(i+1, sampleList[i]);
            productInfoList.add(pl);
        }
        if(sampleList.size() <= 0 ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '没检索到任何样本品'));
            return null;
        }
        return null;
    }
    // 保存
    public PageReference save() {
        errormessageFlg = false;
        System.debug('sampleOrder.DeliveryPhone__c1:' + sampleOrder.DeliveryPhone__c);
        if (String.isBlank(sampleOrder.DeliveryAddress__c)) {
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '送达方地址不能为空!'));
            sampleOrder.DeliveryAddress__c.addError('送达方地址不能为空!');
            errormessageFlg = true;
            return null;
        }
        if (String.isBlank(sampleOrder.DeliveryContact__c)) {
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '送达方联系人不能为空!'));
            sampleOrder.DeliveryContact__c.addError('送达方联系人不能为空!');
            errormessageFlg = true;
            return null;
        }
        if (String.isBlank(sampleOrder.DeliveryPhone__c)) {
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '送达方电话不能为空!'));
            sampleOrder.DeliveryPhone__c.addError('送达方电话不能为空!');
            errormessageFlg = true;
            return null;
        }
        sampleOrder.province__c=provinceName;
        if(!String.isNotBlank(provinceName)){
           sampleOrder.province__c.addError('省不能为空!');
           errormessageFlg = true;
           return null;
        }
        sampleOrder.city__c=cityName;
        if(!String.isNotBlank(cityName)){
           sampleOrder.city__c.addError('市不能为空!');
           errormessageFlg = true;
           return null;
        }

        Map<Id, Sample_order_list_detail__c> orderListDelMap = new Map<Id, Sample_order_list_detail__c>();
        if (String.isNotBlank(orderListId) && orderListDelList.size() > 0) {
            for(Sample_order_list_detail__c orderListDel : orderListDelList){
                orderListDelMap.put(orderListDel.Id, orderListDel);
            }
        }
        sampleOrder.Status__c = '暂存';
        Set<String> productIdSet = new Set<String>();
        // List<Product2> pro2List = new List<Product2>();
        // Map < String, Product2 > proMap = getProductMap(productInfoList);
        List<Sample_order_list_detail__c> deleteSamList = new List<Sample_order_list_detail__c>();
        // 更新且添加订单明细
        List < Sample_order_list_detail__c > insertOrderDetailList = new List < Sample_order_list_detail__c > ();
        for (ProductInfo Pros: productInfoList) {
            if (Pros.check) {
                System.debug('Pros1:' + Pros);
                Sample_order_list_detail__c sod = new Sample_order_list_detail__c();
                if (String.isNotBlank(orderListId) && orderListDelMap.containsKey(Pros.SOLDel.Id)) {
                    sod = orderListDelMap.get(Pros.SOLDel.Id);
                }
                if (Pros.SOLDel.ItemQuantity__c == 0 || Pros.SOLDel.ItemQuantity__c == null) {
                    sod.Total__c = null;
                } else if (pros.SOLDel.ItemQuantity__c > 0) {
                    sod.Total__c = Pros.SOLDel.ItemQuantity__c * Pros.pro.Packing_list_manual__c;
                } else {
                    // Pros.SOLDel.Total__c.addError('第' + Pros.lineNo + '行:' + '产品型号：' + '[' + Pros.pro.Asset_Model_No__c + ']' + ' 订货数量不可为负数');
                    pros.SOLDel.ItemQuantity__c.addError('订货数量不可为负数!');
                    errormessageFlg = true;
                }
                if ((Pros.SOLDel.ItemQuantity__c == 0 || Pros.SOLDel.ItemQuantity__c == null) && String.isNotBlank(Pros.pro.Asset_Model_No__c)) {
                    // Pros.SOLDel.ItemQuantity__c.addError('第' + Pros.lineNo + '行:' + '产品型号：' + '[' + Pros.pro.Asset_Model_No__c + ']' + ' 数量必填');
                    pros.SOLDel.ItemQuantity__c.addError('数量必填!');
                    errormessageFlg = true;
                }
                // if ((Pros.pro.SFDA_Expiration_Date__c < Date.today()) && String.isNotBlank(Pros.pro.Asset_Model_No__c)) {
                //     // Pros.pro.SFDA_Expiration_Date__c.addError('第' + Pros.lineNo + '行:' + '产品型号：' + '[' + Pros.pro.Asset_Model_No__c + ']' + ' 效期过期');
                //     pros.pro.SFDA_Expiration_Date__c.addError('该产品效期过期!');
                //     errormessageFlg = true;
                // }
                // if (proMap.containsKey(Pros.proId)) {
                //     sod.Term_Date__c = proMap.get(Pros.proId).SFDA_Expiration_Date__c;
                //     Pros.SOLDel.Term_Date__c = sod.Term_Date__c;
                // }
                if (String.isBlank(Pros.pro.Asset_Model_No__c)) {
                    sod.Standards__c = null;
                } else {
                    sod.Standards__c = Pros.pro.Packing_list_manual__c;
                }
                sod.ItemQuantity__c = Pros.SOLDel.ItemQuantity__c;
                sod.Pro_Name__c = Pros.pro.Name;
                sod.Pro_model__c = Pros.pro.Asset_Model_No__c;
                sod.Product__c = Pros.proId;
                sod.Sample_Classification__c = Pros.pro.Sample_Classification__c;
                insertOrderDetailList.add(sod);    
            }
        }
        if (insertOrderDetailList.size() <= 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请选择要订货的样本品!'));
            errormessageFlg = true;
            return null;
        }
        if (errormessageFlg == true) {
            return null;
        }
        Savepoint sp = Database.setSavepoint();
        try{
            upsert sampleOrder;
            if (insertOrderDetailList.size() > 0) {
                for (Sample_order_list_detail__c orderDet : insertOrderDetailList) {
                    orderDet.Sample_order_list__c = sampleOrder.Id;
                }
                upsert insertOrderDetailList;
                //保存的时候选中的数量少了就删除对应的订货单明细
                Boolean continueFlag = false;
                for(Id samOrderId : orderListDelMap.keyset()){
                    for(Sample_order_list_detail__c samOrderDetail : insertOrderDetailList){
                        continueFlag = false;
                        if(samOrderId == samOrderDetail.Id){
                            continueFlag = true;
                            break;
                        }
                    }
                    if(continueFlag){
                        continue;
                    }
                    deleteSamList.add(orderListDelMap.get(samOrderId));
                }
                if(deleteSamList.size() > 0){
                    delete deleteSamList;
                }
            }
        } catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
            errormessageFlg = true;
            return null;
        }
        PageReference ret = new PageReference('/' + sampleOrder.Id);
        ret.setRedirect(true);
        return ret;
    }
    // 删除
    // public PageReference deleteBtn() {
    //     List < productInfo > productInfoListRefresh = new List < productInfo > ();
    //     List < Sample_order_list_detail__c > Sample_order_list = new List < Sample_order_list_detail__c > ();
    //     integer i = 0;
    //     Map < String, Product2 > proMap = getProductMap(productInfoList);
    //     for (ProductInfo Pros: productInfoList) {
    //         if (Pros.check) {
    //             if (String.isNotBlank(Pros.SOLDel.Id)) {
    //                 Sample_order_list.add(Pros.SOLDel);
    //             }
    //         } else {
    //             i++;
    //             Pros.lineNo = i;
    //             if (proMap.containsKey(Pros.proId)) {
    //                 if (pros.SOLDel.ItemQuantity__c == 0 || pros.SOLDel.ItemQuantity__c == null) {
    //                     Pros.SOLDel.Total__c = null;
    //                 } else {
    //                     Pros.SOLDel.Total__c = pros.SOLDel.ItemQuantity__c * proMap.get(Pros.proId).Packing_list_manual__c;
    //                 }
    //                 Pros.pro.SFDA_Expiration_Date__c = proMap.get(Pros.proId).SFDA_Expiration_Date__c;
    //                 Pros.inputQuantity = Integer.valueof(pros.SOLDel.ItemQuantity__c);
    //             }
    //             productInfoListRefresh.add(Pros);
    //         }
    //     }
    //     productInfoList.clear();
    //     productInfoList.addAll(productInfoListRefresh);
    //     if (Sample_order_list.size() > 0) {
    //         delete Sample_order_list;
    //     }
    //     return null;
    // }

    // 确认是否发送订单的按钮
    public PageReference confirmBtn() { 
        save();
        if (errormessageFlg) {
            return null;
        }
        Savepoint sp = Database.setSavepoint();
        try{
            sampleOrder.Status__c = '订单已发送';
            sampleOrder.Send_Date__c = Date.today(); 
            update sampleOrder;
            //订单发送后锁定记录
            Approval.LockResult lockResult = Approval.lock(sampleOrder.Id, false);
        }catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
            errormessageFlg = true;
            return null;
        }
        PageReference ret = new PageReference('/' + sampleOrder.Id);
        ret.setRedirect(true);
        return ret;
    }

    //订单已发送后查看的返回按钮
    public PageReference ReturnBtn() { 
        PageReference ret = new PageReference('/' + sampleOrder.Id);
        ret.setRedirect(true);
        return ret;
    }
    //模糊查询样本品
    public PageReference FuzzyQuery(){
        String sql = 'select Id, Name, ProductCode, Packing_list_manual__c, SFDA_Expiration_Date__c, Asset_Model_No__c, Sample_Classification__c FROM Product2 Where Whether_Sample__c = true and SFDA_Status__c != \'停止\' ';
        sql += 'and (ProductCode like \'%' + QueryTemp.trim() + '%\'' + 'or Name like \'%' + QueryTemp.trim() + '%\')';
        List<Product2> sampleList = Database.query(sql);
                                        
        productInfoList.clear();
        for (Integer i = 0; i < sampleList.size(); i++) {
            productInfo pl = new productInfo(i+1, sampleList[i]);
            productInfoList.add(pl);
        }
        if(sampleList.size() <= 0 ){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '没检索到任何样本品'));
            return null;
        }
        return null;
    }

    public class ProductInfo {
        public Integer lineNo { get; set; } //行号
        public boolean check { get; set; } // 选框
        public Product2 pro { get; set; } //产品
        //public Integer inputQuantity { get; set; } //手动输入的数量
        public String proId { get; set; } //产品Id
        public Sample_order_list_detail__c SOLDel { get; set; } //订货单明细
        // 初始化空行
        // public ProductInfo(Integer i) {
        //     lineNo = i;
        //     pro = new Product2();
        //     SOLDel = new Sample_order_list_detail__c();
        //     check = false;
        // }
        // 产品
        public ProductInfo(Integer i, Product2 e) {
            lineNo = i;
            pro = e;
            proId = e.Id;
            SOLDel = new Sample_order_list_detail__c();
            check = false;
        }
        // 订货单明细
        public ProductInfo(Integer i, Sample_order_list_detail__c del) {
            lineNo = i;
            SOLDel = del;
            pro = del.Product__r;
            proId = del.Product__r.Id;
            check = false;
        }
    }
    // 获取产品
    // public static Map < String, Product2 > getProductMap(List < productInfo > productInfoList) {
    //     Map < String, Product2 > proMap = new Map < String, Product2 > ();
    //     Set < String > productIdSet = new Set < String > ();
    //     for (ProductInfo product: productInfoList) {
    //         productIdSet.add(product.proId);
    //     }
    //     if (productIdSet.size() > 0) {
    //         List < Product2 > pro2List = [select Id, Asset_Model_No__c, Name, Packing_list_manual__c from Product2 where Id in : productIdSet];
    //         for (Product2 pro2Info: pro2List) {
    //             proMap.put(pro2Info.Id, pro2Info);
    //         }
    //     }
    //     return proMap;
    // }
}