global class AuthRentalApplyRepairBatch implements Database.Batchable<sObject>,Database.Stateful {
    public String repId;
    private Boolean testCheck = false;
    private BatchIF_Log__c iflog;
    global AuthRentalApplyRepairBatch() {

    }
    global AuthRentalApplyRepairBatch(String repId) {
        this.repId = repId;
    }
    global AuthRentalApplyRepairBatch(String repId,Boolean testCheck) {
        this.repId = repId;
        this.testCheck = true;
    }
    global Database.QueryLocator start(Database.BatchableContext bc) {
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'AuthRentalApplyRepairBatch';
        iflog.Log__c  = 'AuthRentalApplyRepairBatch start\n';
        iflog.ErrorLog__c = '';
        insert iflog;
        String query = 'SELECT Id, Status__c,Delivered_Product__r.Product2.Family,Hospital__c,RepairSource__c,SAP_Transfer_time__c,IfCheckFixture__c,Maintenance_Contract__c,NewProductGuaranteeObject__c,Department_Class__c,Account__c,Incharge_Staff__c,Incharge_Staff__r.Name,Incharge_Staff__r.Email,Delivered_Product__r.Product2.Asset_Model_No__c,QIS_ID__c from Repair__c WHERE Status__c != \'草案中\' AND Status__c != \'取消\' AND Status__c != \'删除\' AND RentalApplyCheck__c = true AND MAINITIAL__c = false AND Repair_Final_Inspection_Date__c = NULL AND Repair_Shipped_Date__c = NULL AND Account__r.Management_Code_Auto__c != \'9999998\'';
        if (String.isNotBlank(this.repId)) {
            query += 'AND Id = \''+repId+'\'';
            System.debug('testzyh===='+query);
        }
        // String query = 'SELECT Id, Status__c,Delivered_Product__r.Product2.Family,Hospital__c,RepairSource__c,SAP_Transfer_time__c,IfCheckFixture__c,Maintenance_Contract__c,NewProductGuaranteeObject__c,Department_Class__c,Account__c,Incharge_Staff__c,Delivered_Product__r.Product2.Asset_Model_No__c,QIS_ID__c from Repair__c WHERE Status__c != \'草案中\' AND Status__c != \'取消\' AND Status__c != \'删除\' AND RentalApplyCheck__c = true AND MAINITIAL__c = false';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, list<Sobject> scope) {
        try {
            System.debug('scope====' + scope);
            List<Rental_Apply__c> raInList = new List<Rental_Apply__c>();
            List<Repair__c> repList = new List<Repair__c>();
            List<String> repIdList = new List<String>();
            List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
            Map<String,String> mailMap = new Map<String,String>();
            repList = scope;
            if (repList.size() > 0) {
                for (Repair__c rep : repList) {
                    repIdList.add(rep.Id);
                }
                System.debug('zyhtest===repIdList===' + repIdList);
                // 查询该修理是否已申请备品
                List<Rental_Apply__c> raList = [SELECT Id FROM Rental_Apply__c WHERE Repair__c IN :repIdList AND Status__c != '取消' AND Status__c != '删除'];
                System.debug('zyhtest=====raList:' + raList);
                // System.debug('zyhtest=====raList:' + raList.size() == 0);
                System.debug('zyhtest=====raList.size():' + raList.size());
                if (raList.size() == 0) {
                    EmailTemplate et=[Select id from EmailTemplate where name =:'修理自动创建备品' limit 1];
                    for (Repair__c rep : repList) {
                        String Demo_purpose2 = '';
                        Rental_Apply__c ra =  new Rental_Apply__c();
                        ra.Name = '*';
                        // ra.Person_In_Charge__c = '00510000001OOSN'; // 备品出借申请 -- 吕世伟,测试用
                        // ra.Person_In_Charge__c = System.UserInfo.getUserId(); // 备品出借申请
                        ra.Person_In_Charge__c = rep.Incharge_Staff__c; // 备品出借申请
                        ra.Loaner_received_staff__c = rep.Incharge_Staff__r.Name; // 收件者姓名 (销售或FSE)
                        ra.applyUser__c = rep.Incharge_Staff__c; // 操作者 2023-11-27：zyh 操作者从Batch改成FSE
                        // ra.applyUser__c = System.UserInfo.getUserId(); // 操作者
                        ra.Hospital__c = rep.Hospital__c; // 医院
                        ra.Strategic_dept__c = rep.Department_Class__c; // 战略科室
                        ra.Account__c = rep.Account__c; // 科室
                        ra.Is_Auto__c = true;
                        if (rep.Delivered_Product__r.Product2.Family == 'GI') {
                            ra.Product_category__c = 'GI';
                        } else {
                            ra.Product_category__c = 'SP';
                        }
                        ra.Product_category__c = rep.Delivered_Product__r.Product2.Family;
                        ra.Demo_purpose1__c = '维修代用'; // 使用目的1
                        System.debug('zyhtest======QIS转修理+' + rep.RepairSource__c);
                        if (rep.RepairSource__c != 'QIS转修理') {
                            System.debug('zyhtest======rep.NewProductGuaranteeObject__c:' + rep.NewProductGuaranteeObject__c);
                            System.debug('zyhtest======rep.Maintenance_Contract__c:' + rep.Maintenance_Contract__c);
                            System.debug('zyhtest======rep.IfCheckFixture__c:' + rep.IfCheckFixture__c);
                            if (rep.NewProductGuaranteeObject__c == '8: 市场多年保修') {
                                Demo_purpose2 = '市场多年保修';
                            }else if (String.isNotBlank(rep.Maintenance_Contract__c)) {
                                Demo_purpose2 = '保修用户';
                            }else if (rep.IfCheckFixture__c) {
                                Demo_purpose2 = '故障排查';
                            }else{
                                if (rep.NewProductGuaranteeObject__c == '2: 服务多年保修' && 
                                    (rep.Delivered_Product__r.Product2.Asset_Model_No__c == 'LTF-190-10-3D' || rep.Delivered_Product__r.Product2.Asset_Model_No__c == 'LTF-S190-5' 
                                    || rep.Delivered_Product__r.Product2.Asset_Model_No__c == 'CYF-VHA' || rep.Delivered_Product__r.Product2.Asset_Model_No__c == 'CYF-VA2' 
                                    || rep.Delivered_Product__r.Product2.Asset_Model_No__c == 'CYF-5A' || rep.Delivered_Product__r.Product2.Asset_Model_No__c == 'LTF-S190-10' 
                                    || rep.Delivered_Product__r.Product2.Asset_Model_No__c == 'OER-AW' || rep.Delivered_Product__r.Product2.Asset_Model_No__c == 'URF-V' 
                                    || rep.Delivered_Product__r.Product2.Asset_Model_No__c == 'URF-V2' || rep.Delivered_Product__r.Product2.Asset_Model_No__c == 'URF-P6')) {
                                        Demo_purpose2 = '保修用户';
                                }else {
                                    Demo_purpose2 = '一般用户';
                                }
                            }
                        }else{
                            Demo_purpose2 = '索赔QIS';
                        }
                        System.debug('zyhtest======Demo_purpose2:' + Demo_purpose2);
                        ra.Demo_purpose2__c = Demo_purpose2; // 使用目的2
                        if (Demo_purpose2 == '索赔QIS' && String.isNotBlank(rep.QIS_ID__c)) {
                            ra.Demo_purpose2__c = '索赔QIS'; // 使用目的2
                        }
                        ra.Repair__c = rep.Id;
                        System.debug('zyhtest======JinlaiIf'+ra);
                        // if (ra.Demo_purpose2__c == '故障排查' && rep.SAP_Transfer_time__c == null) {
                        if (ra.Demo_purpose2__c == '故障排查' || ra.Demo_purpose2__c == '索赔QIS') {
                            // return '没有上传SAP,不可创建备品,请手动创建';
                            continue;
                        }
                        raInList.add(ra);
                        mailMap.put(rep.Incharge_Staff__c,rep.Incharge_Staff__r.Email);
                        System.debug('zyhtest111====mailMap'+mailMap);
                        // System.debug(rep.Person_In_Charge__r.Email + '====' + ra.Incharge_Staff__r.Email);
                    }
                    if (raInList.size() > 0) {
                        Insert raInList;
                        for (Rental_Apply__c ra : raInList) {
                            List<String> toAddresses = new List<String>();
                            // toAddresses.add('zhangyuheng@prec-tech.com');
                            System.debug('zyhtest111====Incharge_Staff__c'+ra.Person_In_Charge__c);
                            System.debug('zyhtest111====Incharge_Staff__r.Email'+ra.Person_In_Charge__r.Email);
                            if(String.isNotBlank(mailMap.get(ra.Person_In_Charge__c))){
                                System.debug('zyhtest====Incharge_Staff__r.Email'+ra.Person_In_Charge__r.Email);
                                toAddresses.add(mailMap.get(ra.Person_In_Charge__c));
                            }
                            //发送邮件
                            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                            mail = Messaging.renderStoredEmailTemplate(et.Id, null , ra.Id);
                            mail.setToAddresses(toAddresses);
                            // String[] toAddresses1 = System.Label.AssetCountErrorMailAddress.split(',');
                            if (String.isNotBlank(System.Label.AuthRental_Apply_TEST)) {
                                String[] toAddresses1 = System.Label.AuthRental_Apply_TEST.split(',');
                                if(toAddresses1 != null) {
                                    mail.setCcAddresses(toAddresses1);
                                }
                            }
                            
                            mail.setSaveAsActivity(false);
                            System.debug('zyhtest=====mail_' + mail);
                            System.debug('zyhtest=====mailMap_' + mailMap);
                            emails.add(mail);
                        }
                    }
                    Messaging.sendEmail(emails);
                }
            }
        } catch (Exception ex) {
            iflog.ErrorLog__c = ex.getLineNumber()+'  行错误 :   '+ex.getMessage();
            return;
        }
    }
    global void finish(Database.BatchableContext BC) {
        iflog.Log__c += '\nAuthRentalApplyRepairBatch end';
        String tmp = iflog.ErrorLog__c;
        if (tmp.length() > 65000) {
            tmp = tmp.substring(0, 65000);
            tmp += ' ...have more lines...';
            iflog.ErrorLog__c = tmp;
        }
        update iflog;
        // 打插队标识的batch
        // Database.executeBatch( new AuthRentalApplyQueueRemindBatch(),1);
        System.debug('2023-12-09zyhxinjianfinish' + DateTime.now());
        // 借用机会可视化--批次从数字改成自定义标签--20231212--zyh--start
        // 自动分单的batch
        // Database.executeBatch( new AuthRentalApplySplitBatch(),1);
        // Integer num = Integer.valueOf(System.Label.AutoSplitNum);
        // if (testCheck == false && !Test.isRunningTest()) { // 2024-1-3 zyh 测试判断
        //     Database.executeBatch( new AuthRentalApplySplitBatch(System.Label.BeijingEmail),num);
        //     Database.executeBatch( new AuthRentalApplySplitBatch(System.Label.GuangzhouEmail),num);
        //     Database.executeBatch( new AuthRentalApplySplitBatch(System.Label.ShanghaiEmai),num);
        // }
        // Database.executeBatch( new AuthRentalApplySplitBatch(),num);
        // 借用机会可视化--批次从数字改成自定义标签--20231212--zyh--end
    }

}